2010-12-14 30 views
3

我正在編寫測試,並且我想知道在測試期間是否有方法更改當前日期?在測試期間模擬當前日期

問題是我正在測試應用程序的統計功能,該應用程序連接到每次調用操作時創建實例的跟蹤模型(只通過「before_filter only」調用來跟蹤某些操作)

所以我需要調用的不同點這個動作在不同的控制器時間來檢驗我的分析組件是做出正確的計算,但我沒有找到任何方式來實現在下面的示例代碼change_current_time:

test "login count" do 
    change_current_time(2.day.ago) 
    get "users/login/testuser/testpassword" 
    assert login_count(2.day.ago) == 1 
    change_current_time(1.day.ago) 
    get "users/login/testuser/testpassword" 
    get "users/login/testuser1/testpassword1" 
    assert login_count(1.day.ago) == 2 
end 

回答

1

這種測試的一種方法是模擬方法/類你想測試。

http://en.wikipedia.org/wiki/Mock_object

的想法是,你可以創建一個相同的功能,除了傳遞一個日期,而不是依賴於當前的日期,並測試替代。困難來自於確保兩個函數真的是等價的,並且保持它們同步的任何變化。

有一些現有的框架和嘲笑,但我不是很熟悉他們推薦給你。

0

在Rails中有嘲笑時間的寶石。
https://github.com/harvesthq/time-warp

time = (2.days.ago) 

pretend_now_is(time) do 
    get "users/login/testuser/testpassword" 
    assert login_count(Date.today) == 1 # it's stubbed 
end 

time = (1.days.ago) 

pretend_now_is(time) do 
    get "users/login/testuser/testpassword" 
    get "users/login/testuser1/testpassword1" 
    assert login_count(Date.today) == 2 
end