如何伪造 Time.now? [英] How to fake Time.now?
本文介绍了如何伪造 Time.now?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了在单元测试中测试时间敏感的方法,设置 Time.now
的最佳方法是什么?
What's the best way to set Time.now
for the purpose of testing time-sensitive methods in a unit test?
推荐答案
我真的很喜欢 Timecop 库.您可以以块形式进行时间扭曲(就像时间扭曲一样):
I really like the Timecop library. You can do time warps in block form (just like time-warp):
Timecop.travel(6.days.ago) do
@model = TimeSensitiveMode.new
end
assert @model.times_up!
(是的,你可以嵌套块形式的时间旅行.)
(Yes, you can nest block-form time travel.)
您也可以进行声明式时间旅行:
You can also do declarative time travel:
class MyTest < Test::Unit::TestCase
def setup
Timecop.travel(...)
end
def teardown
Timecop.return
end
end
我有一些 cucumber 帮助 Timecop 这里.它们让您执行以下操作:
I have some cucumber helpers for Timecop here. They let you do things like:
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"
这篇关于如何伪造 Time.now?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文