我正在使用来自http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl的has_many
关系的FactoryGirl示例。具体来说,例子是:
型号:
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
关联的模型?
答案 0 :(得分:3)
我认为api自那时起发生了重大变化。请查看此处的关联部分以获得进一步的指导:
https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md
答案 1 :(得分: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