我正在使用 TimeCop Gem 来测试时间敏感的测试用例。lib 目录下只有一个文件。它只包含字符串常量。
例子。
module DateStr
SAMPLE = "Some date #{Date.current}"
end
在我的黄瓜测试用例中,这部分代码没有模拟时间。它选择系统时间。这是为什么?
我正在使用 TimeCop Gem 来测试时间敏感的测试用例。lib 目录下只有一个文件。它只包含字符串常量。
例子。
module DateStr
SAMPLE = "Some date #{Date.current}"
end
在我的黄瓜测试用例中,这部分代码没有模拟时间。它选择系统时间。这是为什么?
DateStr
加载时,会SAMPLE
创建常量并分配存在的日期。
我会说这是常量的错误用例,因为它们不应该改变。
编辑。
我不会为这种行为使用常量。一种骇人听闻的方法是使用 lambdas:
module DateStr
SAMPLE = -> {"Some date #{Date.current}"}
end
DateStr::SAMPLE.call # This will evaluate to current date
但这不是一个好的用例,因为值本身不是常量,对于这种行为,您应该使用简单的类方法:
module DateStr
def self.sample
"Some date #{Date.current}"
end
end