2016-09-21 76 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

(注:上面的固定一些拼寫錯別字)