一个提供“时间旅行”、“时间冻结”和“时间加速”功能的宝石,让测试依赖时间的代码变得简单。它提供了一种统一的方法。
一个提供“时间旅行”和“时间冻结”功能的 gem,让测试依赖时间的代码变得极其简单。它提供了一种统一的方法,可以在一次调用中模拟 Time.now、Date.today、DateTime.now 和 Process.clock_gettime。
bundle add timecop
#freeze 和 #travel,参数可以是以下之一:Time.now 开始的偏移秒数Timecop#travel 和 Timecop#freeze 的嵌套调用——每个块都会保持其对“现在”的解释。运行一个时间敏感的测试
joe = User.find(1)
joe.purchase_home()
assert !joe.mortgage_due?
# move ahead a month and assert that the mortgage is due
Timecop.freeze(Date.today + 30) do
assert joe.mortgage_due?
end你可以通过 setup/teardown 方法轻松地为一组测试模拟时间
describe "some set of tests to mock" do
before do
Timecop.freeze(Time.local(1990))
end
after do
Timecop.return
end
it "should do blah blah blah" do
end
end为 Rails 应用的测试环境设置时间——如果你的整个应用对时间敏感,这一点尤其有用。它允许你在某个单一时间点构建测试数据,并在测试中适当地进入/退出该时间点
在 config/environments/test.rb 中
config.after_initialize do
# Set Time.now to September 1, 2008 10:05:00 AM (at this instant), but allow it to move forward
t = Time.local(2008, 9, 1, 10, 5, 0)
Timecop.travel(t)
endfreeze 用于静态地模拟
暂无开放 Issues,或尚未同步最近议题。