【问题标题】:Timecop is not able to mock date correctlyTimecop 无法正确模拟日期
【发布时间】:2015-10-13 06:41:55
【问题描述】:

我正在使用 TimeCop Gem 来测试时间敏感的测试用例。 lib 目录下只有一个文件。它只包含字符串常量。

示例。

module DateStr
   SAMPLE = "Some date #{Date.current}"
end

在我的黄瓜测试用例中,这部分代码没有模拟时间。它选择系统时间。这是为什么呢?

【问题讨论】:

    标签: ruby-on-rails cucumber timecop


    【解决方案1】:

    DateStr 被加载时,SAMPLE 常量被创建并分配了存在的日期。

    我会说这是常量的错误用例,因为它们不应该改变。

    编辑。

    我不会为这种行为使用常量。 hackish 方法是使用 lambda:

    module DateStr
       SAMPLE = -> {"Some date #{Date.current}"}
    end
    DateStr::SAMPLE.call # This will evaluate to current date
    

    但这不是一个好的用例,因为值不是 constant 它自己,对于这种行为,您应该使用简单的类方法:

    module DateStr
       def self.sample
         "Some date #{Date.current}"
       end
    end
    

    【讨论】:

    • 但是无论如何我都无法模拟它。模块加载总是发生在 TimeCop 模拟 Date 之前。这里有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多