How to fake Time.now?

前端 未结 14 1065
不知归路
不知归路 2020-12-02 11:47

What\'s the best way to set Time.now for the purpose of testing time-sensitive methods in a unit test?

相关标签:
14条回答
  • 2020-12-02 12:43

    Personally I prefer to make the clock injectable, like so:

    def hello(clock=Time)
      puts "the time is now: #{clock.now}"
    end
    

    Or:

    class MyClass
      attr_writer :clock
    
      def initialize
        @clock = Time
      end
    
      def hello
        puts "the time is now: #{@clock.now}"
      end
    end
    

    However, many prefer to use a mocking/stubbing library. In RSpec/flexmock you can use:

    Time.stub!(:now).and_return(Time.mktime(1970,1,1))
    

    Or in Mocha:

    Time.stubs(:now).returns(Time.mktime(1970,1,1))
    
    0 讨论(0)
  • 2020-12-02 12:43

    i just have this in my test file:

       def time_right_now
          current_time = Time.parse("07/09/10 14:20")
          current_time = convert_time_to_utc(current_date)
          return current_time
        end
    

    and in my Time_helper.rb file i have a

      def time_right_now
        current_time= Time.new
        return current_time
      end
    

    so when testing the time_right_now is overwritten to use what ever time you want it to be.

    0 讨论(0)
提交回复
热议问题