Ruby on rails rspec;如何测试这个函数?

Ruby on rails rspec;如何测试这个函数?,ruby-on-rails,unit-testing,testing,rspec,Ruby On Rails,Unit Testing,Testing,Rspec,ImageManager。检查启用时间 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!=否则返回false 我想测试这个函数

ImageManager。检查启用时间

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!=否则返回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\u time.在时区(“亚洲/东京”).hour
返回23而不是23


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

您可以使用gem来存根当前时间:


避免安装另一个gem的一个解决方案是重写现有方法,使其对时间没有显式依赖。现在:

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 

只是好奇-你为什么使用
时间。现在
然后在“亚洲/东京”区域转换?您知道您可以在rails设置中设置默认时区,然后只需使用
Time.current
而不进行转换吗?对不起,我不知道。你能告诉我怎么做吗?你可以从和指南开始链接。这不符合最佳实践。请使用let vars和expect语法。同意,但我试着向大家展示初学者唯一担心的改变话题。
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