【问题标题】:FactoryGirl : generate sequence for start and end dateFactoryGirl : 为开始和结束日期生成序列
【发布时间】:2014-01-15 08:56:19
【问题描述】:

我正在尝试为 start_dateend_date 定义一个序列,以便 end_date 应该比 start_date 提前 n 天。

sequence(:start_date)  { |n| Date.current.beginning_of_year.since(n.days) }
sequence(:end_date)    { |n| generate(:start_date).since(n.days) }

但这会导致 undefined_method 错误,这是预期的,因为应该在工厂块中调用 generate

NoMethodError: undefined method `generate' for #<FactoryGirl::Syntax::Default::DSL:0xe5351fc>

我也可以将 end_date 排序为

sequence(:end_date)    { |n| Date.current.beginning_of_year.ago(n.days) }

但这可能会导致我的 end_date 落后于 start_date,这是意料之中的。

有没有更好的方法来定义所需的开始和结束日期的顺序?

【问题讨论】:

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


    【解决方案1】:

    要获得随机天数,您可以这样做:

    :start_date DateTime.now  
    :end_date (rand(n)+1).from_now  
    

    n 是间隔,即如果你想要 1 到 60 之间的天数,你会这样做:

    (rand(60)+1).from_now 
    

    【讨论】:

    • 你的意思是(rand(n)+1).days.from_now 吗?但我想确保它只在一年之间而不是跨年。
    • 我没有足够的声誉来回复您在@Santosh 回复后添加的评论。在那里你问如何产生随机差异。为确保避免跨年,您可以计算自 1/1/(当前年份)以来经过的天数,并将其用于 rand() 方法的 n 参数。
    【解决方案2】:

    这对我有用:

        start_date Faker::Date.between(5.days.from_now, 55.days.from_now)
        end_date Faker::Date.between(57.days.from_now, 75.days.from_now)
    

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 2014-03-12
      相关资源
      最近更新 更多