I have this factory defined:
factory :post, :parent => :post_without_countries, class: Post do |p|
p.country_ids {|country_ids| [country_ids.association(:country), country_ids.association(:country)]}
end
And I'm wanting it to output two unique countries. Instead it just inserts the same country as the association twice:
#<Post id: nil, title: "Atque id dolorum consequatur.", body: "Praesentium saepe ullam magnam. Voluptatum tempora ...", created_at: nil, updated_at: nil, user_id: 1>
[#<Country id: 1, name: "Dominican Republic", isocode: "lyb", created_at: "2012-10-20 13:52:18", updated_at: "2012-10-20 13:52:18">, #<Country id: 1, name: "Dominican Republic", isocode: "lyb", created_at: "2012-10-20 13:52:18", updated_at: "2012-10-20 13:52:18">]
Any ideas?
Instead of doing:
2.times { post.countries << FactoryGirl.create(:country) }
in RSpec, you can make an after_create
hook like this:
after_create do |post|
2.times { post.countries << FactoryGirl.create(:country) }
end
If you need to customize the number of times you want to create a country, you can make a transient attribute:
#in the post factory definition
ignore do
num_countries 0 #default to zero
end
#different after_create
after_create do |post, proxy|
proxy.num_countries.times { post.countries << FactoryGirl.create(:country) }
end
Better use the build_list
or create_list
methods:
post.countries = create_list(:country, 2)
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