2014-02-28 56 views
3

我想在控制檯中模擬Time.now返回給定的時間,比如說從現在開始的30分鐘。這是在沒有RSpec可用的臨時服務器上。如何在沒有Ruby測試庫的情況下模擬時間?

以下沒有工作,因爲它創建了一個循環,提高SystemStackError:

t = Time.now + 30.minutes 
t.to_s 
=> "2014-02-28T17:33:37Z" 

class Time 
    def self.now 
    iso8601 "2014-02-28T17:33:37Z" 
    end 
end 

Time.now 

用Ruby 1.9.3

回答

2

工作時間設定爲整數工作對我來說:

class Time 
    def self.now 
    Time.at(1393610063) 
    end 
end 

Time.now 
#=> 2014-02-28 09:54:23 -0800 

sleep 5 

Time.now 
#=> 2014-02-28 09:54:23 -0800 
0

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 

寶石的網站有更多的信息和例子。

相關問題