rspec的;如何测试这个功能?

时间:2017-02-20 08:01:30

标签: ruby-on-rails unit-testing testing rspec

ImageManager.check_enable_time

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

如果JST!= 23中的当前时间返回false,则此函数返回true。

我想测试这个功能。

我尝试了什么:

 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

make now_time.in_time_zone("Asia/Tokyo").hour如何返回23而不是23?

请帮助我是rails和rspec的新手。

2 个答案:

答案 0 :(得分:1)

避免安装另一个gem的解决方案是重写现有方法,以便它没有明确依赖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 

答案 1 :(得分:0)

您可以使用Timecop gem:

来截断当前时间
  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