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

I defined this factory:

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 want him to bring out two unique countries. Instead, it simply 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?

+4
source share
4 answers

Instead of this:

 2.times { post.countries << FactoryGirl.create(:country) } 

in RSpec, you can do the after_create hook as follows:

 after_create do |post| 2.times { post.countries << FactoryGirl.create(:country) } end 

If you need to configure the number of attempts to create a country, you can make a transition 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 
+2
source

Better to use the build_list or create_list methods:

 post.countries = create_list(:country, 2) 
+7
source

It seems that the factory girl cannot be iterated correctly. Two questions that arise in my head are this.

Do you use FactoryGirl.create when you want to use FactoryGirl.create ?

You tried to replace p.country_ids with p.sequence(:country_ids)

I hope this points you in the right direction. If not, maybe more information?

0
source

OK, I fixed this by taking my creation of relations with many countries from the factory and simply creating it in RSpec:

  post = FactoryGirl.build(:post) 2.times { post.countries << FactoryGirl.create(:country) } 
0
source

Source: https://habr.com/ru/post/1440964/


All Articles