2010-09-21 69 views
5

我正在嘗試Factory與投票相關的帖子。因此,Post.votes會生成與之關聯的投票。未定義的方法`每個'在一個factory_girl/rspec2場景

Factory.define :voted_post, :parent => :post, :class => Post do |p| 
    p.association :votes, :factory => :vote 
end 

而且我rspec2相對比較簡單:

describe "vote scores" do 
    it "should show me the total vote score" do 
    @post = Factory(:voted_post) 
    @post.vote_score.should == 1 
    end 
end 

那麼爲什麼會返回此錯誤:

Failures: 
    1) Post vote scores should show me the total vote score 
    Failure/Error: @post = Factory(:voted_post) 
    undefined method `each' for #<Vote:0x105819948> 

紅寶石1.8.7(2009-06-12 PATCHLEVEL 174) universal-darwin10.0]

Rails 3.0.0

回答

8
Factory.define :voted_post, :parent => :post, :class => Post do |p| 
    p.association :votes, :factory => :vote 
end 

是一樣試圖去

some_voted_post.votes = Factory(:vote) 

基本上你嘗試分配一票作爲數組。

編輯

你可以有一個包含單票數組,但你不能只是有一票。

這之間的區別:

some_voted_post.votes = Factory(:vote) 

some_voted_post.votes = [Factory(:vote)] 

前者不是一個數組,因此不能正常工作,後者是一個數組。

+1

只要執行'p.association:vote'(非複數) – 2010-09-21 03:47:19

+0

單個投票怎麼會不能用作數組? – Trip 2010-09-21 14:29:10

+1

@Trip請參閱編輯。 – 2010-09-21 14:37:00

4

如果你要分配的has_many協會,預計陣列,而不是一個單一的值,你應該使用長型:

Factory.define :voted_post, :parent => :post, :class => Post do |p| 
    p.votes { |vote| [vote.association(:vote)] } 
end 

並封裝用[]關聯的創建,以確保陣列會返回

相關問題