您或許可以使用timecop
作爲解決方案的一部分(它也對我評價很高,稱爲「最佳命名寶石,永遠」)。它使用起來非常簡單,並且可以同步修補大部分時間數據源,所以如果您的Utils
模塊使用標準方法來評估時間,它應該具有與Time.now
所示的「現在」相同的概念。
注意,如果Utils
正在調用另一個進程的外部API,則在此情況下,您應該將其存根以便返回測試斷言中所需的正常運行時值。
以下rspec
片段通過舉例的方式,並讓你有可用的東西(如被測模塊被稱爲Server
)
describe "#should_restart?"
before :each do
Timecop.travel(Time.parse("2013-08-01T12:00:00"))
Server.start # Just a guess
# Using `mocha` gem here
Konfig.expect(:get).with(:auto_restart_time).returns("18:00:00")
end
after :each do
Timecop.return
end
it "should be false if the server has just been started" do
Server.should_restart?.should be_false
end
it "should be false before cutoff time" do
Timecop.travel(Time.parse("2013-08-02T16:00:00"))
Server.should_restart?.should be_false
end
it "should be true when the server has been up for a while, after cutoff time" do
Timecop.travel(Time.parse("2013-08-02T18:05:00"))
Server.should_restart?.should be_true
end
end
Konfig類怎麼樣?你會在那裏做什麼? – jriff
我在我的代碼段中建議使用'mocha'來爲測試值存根。它的語法來自記憶,頭腦,它可能需要調整。儘量避免斷言它被調用的次數 - 只需知道配置值用於控制方法的行爲就足夠了。 –