I'm using the FactoryGirl example for has_many
relationships from http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl. Specifically, the example is:
Models:
class Article < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :article
end
Factories:
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
When I run that same example (with the proper schema, of course), an error is thrown
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)
Is there a new way to create models with has_many
associations with FactoryGirl?
I think the api has changed significantly since then. Have a look at the section on associations here for further guidance:
https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md
As of today your example would looks like this:
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
Or if you need flexibility on a number of comments:
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
Then use like
create(:article_with_comment, comments_count: 15)
For more details please refer to associations section in getting started guide: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With