2013-07-31 16 views
0

我有這樣的方法:如何測試簡單的Ruby方法,具有定時和配置依賴

def self.should_restart? 
    if Konfig.get(:auto_restart_time).present? 
    Time.now>=Time.parse(Konfig.get(:auto_restart_time)) && Utils.uptime_in_minutes>780 
    end 
end 

在常規的紅寶石(未Rails的)我怎麼會去測試呢?我可以monkeypatch Konfig和Utils返回我想要的東西,但看起來很醜陋。

回答

0

您或許可以使用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 
+0

Konfig類怎麼樣?你會在那裏做什麼? – jriff

+0

我在我的代碼段中建議使用'mocha'來爲測試值存根。它的語法來自記憶,頭腦,它可能需要調整。儘量避免斷言它被調用的次數 - 只需知道配置值用於控制方法的行爲就足夠了。 –

0

使用模擬框架 喜歡rspec的,模擬一些假設,RR模擬

相關問題