0

为了模拟mochaTime.now gem ,我使用以下 oneliner。

require 'minitest/autorun'                          
require 'mocha/mini_test'                                                                           
require 'time'                                      

class TimeMockTest < Minitest::Test                 
  def test_time_mock       
    # Mocking Time.now in one line                         
    Time.expects(:now).returns(Time.parse('20:12'))

    Time.now                                        
  end                                               
end    

但是运行此代码会返回以下错误,因为Time.parse()使用了模拟Time.now()方法。

NoMethodError: undefined method `year' for nil:NilClass
    C:/Ruby22-x64/lib/ruby/2.2.0/time.rb:255:in `make_time'
    C:/Ruby22-x64/lib/ruby/2.2.0/time.rb:364:in `parse'
    time_mock.rb:8:in `test_time_mock'

你如何模拟 Time.now mocha

4

1 回答 1

1

你应该检查https://github.com/travisjeffery/timecop。它将帮助您在测试中处理时间。

于 2015-11-26T11:41:23.633 回答