2014-09-19 37 views
0

我想寫一個vote_spec模型的spec代碼。不知道我到底做錯了什麼。我認爲它可能在before塊的第一個@vote屬性中。rspec投票驗證錯誤:必須通過散列作爲參數

這是驗證應如何工作:

Console 
v = Vote.new(value: 1) 
v.valid? #=> true 

v2 = Vote.new(value: -1) 
v2.valid? #=> true 

v3 = Vote.new(value: 2) 
v3.valid? #=> false 

這是錯誤:

Failure/Error: @vote = Vote.create(:post_id) 
ArgumentError: 
    When assigning attributes, you must pass a hash as an argument. 

這是我vote_spec.rb

require 'rails_helper' 

describe Vote do 

describe "validations" do 

    before do 
     @vote = Vote.create(:post_id) 
     @vote.create(value: 1) 
     @vote.create(value: -1) 
    end 

    describe "first_validation" do 
     it "only allows -1 as a value" do 
      expect(@vote.first_validation).to eq(-1) 
     end 
    end 

    describe "second_validation" do 
     it "only allows 1 as a value" do 
      expect(@vote.second_validation).to eq(1) 
     end 
    end    
end     

+0

你想在這裏做什麼? ''@vote = Vote.create(:post_id)'' – Nobita 2014-09-19 20:54:07

+0

總的來說,我試圖驗證投票的帖子,僅限於1或-1 – Amanjot 2014-09-19 20:58:01

+0

當一個不是1的值和 - 1通過了嗎? – Nobita 2014-09-19 21:01:59

回答

4

如果你想測試有效通貨膨脹,也許你可以做這樣的事情:

describe "validations" do 
    it 'is valid if the value is 1' do 
    expect(Vote.new(value: 1)).to be_valid 
    end  

    it 'is valid if the value is -1' do 
    expect(Vote.new(value: -1)).to be_valid 
    end 

    [-3, 0, 4].each do |invalid_value| 
    it "is not valid if the value is #{invalid_value}" do 
     expect(Vote.new(value: invalid_value)).not_to be_valid 
    end 
    end  
end 
0

Amanjot,

另外,作爲薩沙在評論中提到。你可以繼續下面的代碼我想

require 'rails_helper' 

describe Vote do 

describe "validations" do 

    before do 
     @first_vote = Vote.create(value: -1) # Vote.new(value: -1) - should try this too 
     @second_vote= Vote.create(value: 1) # Vote.new(value: 1) - should try this too 
    end 

    describe "first_validation" do 
     it "only allows -1 as a value" do 
      expect(@first_vote.value).to eq(-1) 
     end 
    end 

    describe "second_validation" do 
     it "only allows 1 as a value" do 
      expect(@second_vote.value).to eq(1) 
     end 
    end    
end 

試試這樣的事情。您需要在投票模型上使用create操作。

相關問題