Rails/RSpec/FactoryGirl—如何让一个字段指向一个方法?

Rails/RSpec/FactoryGirl—How to make a field point to a method?

我有这个工厂

FactoryGirl.define do
  factory :gst_report do
    association :organisation, factory: :active_organisation
    period_months 3
    period_start_date Date.parse('2015-01-01')
    period_end_date Date.parse('2015-02-01')
  end
end

但在测试中period_start_date经常被设置为其他日期。对于这些测试中的每一个,我希望 period_end_date 只是在 period_start_date 之后一个月。

是否可以使 period_end_date 成为获取当前 period_start_date 并向其添加一个月的方法?

是的,您可以使用 FactoryGirl Callbacks

period_end_date 设置为 period_start_date 加上一个月

这应该适用于您的情况:

FactoryGirl.define do
  factory :gst_report do
    association :organisation, factory: :active_organisation
    period_months 3
    period_start_date Date.parse('2015-01-01')

    after(:build) do |gst_report|
      gst_report.period_end_date = (gst_report.period_start_date + 1.month) unless gst_report.period_end_date
    end
  end
end

请注意,period_end_date 未事先指定。如果在建造工厂时没有指定结束日期,我们也只会分配结束日期,这样您仍然可以通过您的规格指定不同的 start/end 期间。