Timecop gem是專門爲此目的而設計的。雖然它的設計使測試變得簡單,但它不是一個「測試框架」 - 它不需要rspec或rails,並且可以用於任何ruby項目。
的freeze
方法允許你靜態模擬當前時間:
# Assume it is currently 12:00:00 on 3/1/2015
Timecop.freeze(Time.now + 30.minutes) do
puts Time.now # --> shows 12:30:00
do_something_for_fifteen_seconds
puts Time.now # --> still shows 12:30:00; time has not passed
end
的travel
方法允許你動態模擬當前時間:
Timecop.travel(Time.now + 30.minutes) do
puts Time.now # --> shows 12:30:00
do_something_for_fifteen_seconds
puts Time.now # --> shows 12:30:15; time has passed but we are still 30 minutes ahead of reality
end
而且scale
方法允許你比現實更快(或更慢)地模擬時間流逝:
Timecop.scale(60) do
puts Time.now # --> shows 12:00:00
do_something_for_fifteen_seconds
puts Time.now # --> shows 12:15:00; time has passed 60 times faster,
# so 15 seconds of real time appears as 15 minutes
end
寶石的網站有更多的信息和例子。