2017-02-20 59 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