Timecop 无法正确模拟日期

Timecop is not able to mock date correctly

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

示例。

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

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

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

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

编辑。

我不会为此行为使用常量。 hackish 方法是使用 lambdas:

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

但这不是一个好的用例,因为该值本身不是 常量,对于这种行为,您应该使用简单的 class 方法:

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