FactoryGirl: Creating dynamic factories with options?

I have three factories that I want to shove. They look like this:

factory :sequenced_stamps_by_years, class: Stamp do ... sequence(:day_date) { |n| n.years.ago } end factory :sequenced_stamps_by_months, class: Stamp do ... sequence(:day_date) { |n| n.months.ago } end factory :sequenced_stamps_by_weeks, class: Stamp do ... sequence(:day_date) { |n| n.weeks.ago } end 

How can I dry this? I want them to have something like this:

 FactoryGirl.create_list(:sequenced_stamps_by_x, 4, x: "weeks") ## <- So that i can decide whether I want weeks, days, years, or months ago. 

Is it possible?

+4
source share
2 answers

If you do not approve of the inheritance approach, there is an alternative using a parameter. Mostly:

 factory :stamps do ignore do interval :years # possible values => :years, :months, :weeks end sequence(:date_date) { |n| n.send(interval).ago } # rest of attributes here end 

Now you can do:

 FactoryGirl.create(:stamps, :interval => :months) 

or

 FactoryGirl.create(:stamps) 

which defaults to years.

All this can be found in the Girl’s Factory Transient Attributes.

+10
source

Plants can inherit from other plants. So you can do something like:

 factory :stamps do # common attributes here ..... factory: sequenced_stamps_by_years do sequence(:day_date) { |n| n.years.ago } end factory: sequenced_stamps_by_months do sequence(:day_date) { |n| n.months.ago } end factory: sequenced_stamps_by_weeks do sequence(:day_date) { |n| n.weeks.ago } end end 
+1
source

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


All Articles