2016-09-21 41 views
0

我只是在学习使用ruby和rails编写规范。所以我有两个相似的模式,在投票时采取类似的行为:问题和答案。所以我尝试不复制代码并为这两个编写共享示例。如何设置共享示例?

RSpec.shared_examples_for 'User Votable' do 

    let!(:user){ create :user } 
    let!(:sample_user){ create :user } 
    let!(:vote){ create :vote, user: user, votable: votable, vote_field: 1} 

    it 'user different from resource user is accapteble' do   
    expect(votable.user_voted?(sample_user)).to be_falsy 
    end 

    it 'user similar to resource user is accapteble' do 

    expect(votable.user_voted?(user)).to be_truthy 
    end 

end 

和测试本身

describe 'user_voted?' do 
    def votable 
    subject{ build(:question)} 
    end 
    it_behaves_like 'User Votable' 
end 

最后它在该规范失败(我想是因为受的 - 当我创建一个投票不会改变) 所以我会,如果很开心我可以管理和理解如何正确地做到这一点。而对于任何建议

非常感激还当我尝试使用模拟这样的,它抱怨上没有主键

allow(:question){create :question} 

Failures: 

1)问题user_voted?行为就像类似于资源使用者是accapteble 故障/错误用户可投票用户:期待(votable.user_voted(用户)?),以be_truthy

expected: truthy value 
     got: false 
Shared Example Group: "User Votable" called from ./spec/models/question_spec.rb:23 
+0

只是做'高清可投票;建立(:问题);结束' –

+0

def votable build(:question)end我接收到类似的错误(更新) –

回答

1

取代具有votable方法,你可以设置subject这样:

it_behaves_like 'User Votable' do 
    subject { build(:question) } 
end 
+0

我应该如何在我的规范中解决这个问题? –

1

你其实并不需要使用subject,你可以设置你想要使用let任何情况下,它会在块中可用:

describe 'user_voted?' do 
    let(:votable) { build(:question) } 
    it_behaves_like 'User Votable' 
end 

然后,你可以参考votable共享例子中,它被定义由上下文:

RSpec.shared_examples_for 'User Votable' do 
    let!(:user) { create :user } 
    let!(:sample_user) { create :user } 
    let!(:vote) { create :vote, user: user, votable: votable, vote_field: 1 } 

    it 'user different from resource user is acceptable' do   
    expect(votable.user_voted?(sample_user)).to be_falsy 
    end 

    it 'user similar to resource user is acceptable' do 
    expect(votable.user_voted?(user)).to be_truthy 
    end 
end 

您还可以顺带传递参数到it_behaves_like块更大的灵活性。

编号:Providing context to a shared group using a block

(注:上面的固定一些拼写错别字)