4

我有三个要干燥的工厂。它们看起来像这样:

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.

这可能吗?

4

2 回答 2

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 瞬态属性中找到

于 2013-05-06T12:57:53.820 回答
2

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

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
于 2013-05-05T13:48:32.633 回答