Ruby-on-rails – Creating an array of values in FactoryGirl, each of which is unique

factory-botruby-on-railsruby-on-rails-3.2

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?

Best Answer

Better use the build_list or create_list methods:

post.countries = create_list(:country, 2)
Related Topic