2013-07-13 58 views
5

我使用FactoryGirl示例has_many关系从http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl。具体地,示例的是:FactoryGirl has_many association

型号:

class Article < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :article 
end 

工厂:

factory :article do 
    body 'password' 

    factory :article_with_comment do 
    after_create do |article| 
     create(:comment, article: article) 
    end 
    end 
end 

factory :comment do 
    body 'Great article!' 
end 

当我运行相同的例子(与适当的模式,当然),引发错误

2.0.0p195 :001 > require "factory_girl_rails" 
=> true 
2.0.0p195 :002 > article = FactoryGirl.create(:article_with_comment) 
ArgumentError: wrong number of arguments (3 for 1..2) 

是否有一种新方法可以与FactoryGirl建立has_many关联?

回答

1

截至今天你的例子将是这样的:

factory :article do 
    body 'password' 

    factory :article_with_comment do 
    after(:create) do |article| 
     create_list(:comment, 3, article: article) 
    end 
    end 
end 

factory :comment do 
    body 'Great article!' 
end 

或者,如果你需要一些评论灵活性:

factory :article do 
    body 'password' 

    transient do 
    comments_count 3 
    end 

    factory :article_with_comment do 
    after(:create) do |article, evaluator| 
     create_list(:comment, evaluator.comments_count, article: article) 
    end 
    end 
end 

factory :comment do 
    body 'Great article!' 
end 

然后使用像

create(:article_with_comment, comments_count: 15) 

有关详细信息,请参阅入门指南中的关联部分: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations