FactoryGirl:用参数创建动态工厂?

时间:2013-05-05 13:19:29

标签: ruby-on-rails rspec factory-bot

我有三个工厂,我想干涸。它们看起来像这样:

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

我该如何干这个?我希望能够创建这样的东西:

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

这可能吗?

2 个答案:

答案 0 :(得分:10)

如果您不喜欢继承方法,可以使用参数替代。基本上是:

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

现在你可以做到:

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

FactoryGirl.create(:stamps)

默认为年。

您可以在Factory Girl transient attributes

中找到这一切

答案 1 :(得分:1)

工厂可以继承其他工厂。因此,您可以执行以下操作:

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