Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array of values in FactoryGirl, each of which is unique

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?

like image 501
Betjamin Richards Avatar asked Dec 26 '22 15:12

Betjamin Richards


2 Answers

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
like image 45
Kenrick Chien Avatar answered Jan 13 '23 12:01

Kenrick Chien


Better use the build_list or create_list methods:

post.countries = create_list(:country, 2)
like image 83
arthur.karganyan Avatar answered Jan 13 '23 12:01

arthur.karganyan