Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryGirl: Creating dynamic factories with parameters?

I have three factories that i want to DRY up. 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 up? I want to be able to create them 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 this possible?

like image 966
Pål Avatar asked Dec 15 '22 11:12

Pål


1 Answers

Factories can inherit from other factories. Therefore 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
like image 58
boulder Avatar answered Dec 30 '22 07:12

boulder