为了在单元测试中测试时间敏感的方法,设置Time.now
的最佳方法是什么?
发布于 2009-08-03 12:11:25
我真的很喜欢Timecop库。您可以在块形式中进行时间扭曲(就像时间扭曲一样):
Timecop.travel(6.days.ago) do
@model = TimeSensitiveMode.new
end
assert @model.times_up!
(是的,您可以嵌套块形式的时间旅行。)
您还可以进行声明式时间旅行:
class MyTest < Test::Unit::TestCase
def setup
Timecop.travel(...)
end
def teardown
Timecop.return
end
end
我为Timecop here提供了一些cucumber助手。它们可以让你做这样的事情:
Given it is currently January 24, 2008
And I go to the new post page
And I fill in "title" with "An old post"
And I fill in "body" with "..."
And I press "Submit"
And we jump in our Delorean and return to the present
When I go to the home page
I should not see "An old post"
发布于 2009-07-31 23:10:41
就我个人而言,我更喜欢让时钟可注入,就像这样:
def hello(clock=Time)
puts "the time is now: #{clock.now}"
end
或者:
class MyClass
attr_writer :clock
def initialize
@clock = Time
end
def hello
puts "the time is now: #{@clock.now}"
end
end
然而,许多人更喜欢使用mocking/stubbing库。在RSpec/flexmock中,您可以使用:
Time.stub!(:now).and_return(Time.mktime(1970,1,1))
或者在Mocha中:
Time.stubs(:now).returns(Time.mktime(1970,1,1))
发布于 2015-09-16 16:49:18
使用Rspec 3.2,我发现伪造Time.now返回值的唯一简单方法是:
now = Time.parse("1969-07-20 20:17:40")
allow(Time).to receive(:now) { now }
现在Time.now将总是返回阿波罗11号登陆月球的日期。
https://stackoverflow.com/questions/1215245
复制相似问题