2017-02-20 55 views
0

ImageManager.check_enable_timerspec;如何測試這個功能?

def check_enable_time 
    # get current time 
    now_time = Time.now 
    # UTC to JST convestion JST = UTC + 9 hours 
    hour = now_time.in_time_zone("Asia/Tokyo").hour 
    (hour != 23) ? true : false 

該函數返回true,如果當前時間JST!= 23否則返回false。

我想測試這個功能。

我的嘗試:

describe ImageManager do 
    describe "Test check_enable_time() function" do 
    context "When current time in JST != 23" do 
     it 'should return true' do 
     image_manager = ImageManager.new 
     result = image_manager.check_enable_time 
     result.should eql(true) 
     end 
    end 
    end 
end 

如何使now_time.in_time_zone("Asia/Tokyo").hour超過23回23等?

請幫助我是新的rails和rspec。

+0

只是立方米rious - 爲什麼要使用'Time.now'然後在「亞洲/東京」區域轉換?你知道你可以在rails設置中設置默認的時區,然後簡單地使用'Time.current'而不用轉換? – MikDiet

+0

對不起,我不知道。你能告訴我該怎麼做嗎? – RajSharma

+0

您可以從http://guides.rubyonrails.org/active_support_core_extensions.html#calculations和http://guides.rubyonrails.org/configuring.html#rails-general-configuration指南 – MikDiet

回答

0

你可以使用Timecop寶石存根當前時間:

it 'should return true' do 
    image_manager = ImageManager.new 
    Timecop.travel(Time.local(2008, 9, 1, 12, 0, 0)) do 
     result = image_manager.check_enable_time 
    end 
    result.should eql(true) 
    end 
+0

對於這個問題,它工作正常。謝謝。 – RajSharma

1

,避免安裝另一顆寶石。將改寫現有的方法,使其不會對Time.now的顯式依賴一個解決方案:

def check_enable_time(now_time = Time.now) 
    # UTC to JST convestion JST = UTC + 9 hours 
    hour = now_time.in_time_zone("Asia/Tokyo").hour 
    (hour != 23) ? true : false 
end 

然後,您可以通過傳遞適當的時候對其進行測試:

it 'should return true' do 
    image_manager = ImageManager.new 
    time = Time.local(2008, 9, 1, 12, 0, 0) 
    result = image_manager.check_enable_time(time) 

    result.should eql(true) 
end