jeudi 26 novembre 2015

Mock Time.now with mocha

To mock Time.now with the mocha gem I use the following 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    

But running this code returns the following error since Time.parse() uses the the mocked Time.now() method.

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'

How do you mock Time.now with mocha?

Aucun commentaire:

Enregistrer un commentaire