How to fake Time.now?

前端 未结 14 1145
不知归路
不知归路 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:20

    I really like the Timecop library. You can do time warps in block form (just like time-warp):

    Timecop.travel(6.days.ago) do
      @model = TimeSensitiveMode.new
    end
    assert @model.times_up!
    

    (Yes, you can nest block-form time travel.)

    You can also do declarative time travel:

    class MyTest < Test::Unit::TestCase
      def setup
        Timecop.travel(...)
      end
      def teardown
        Timecop.return
      end
    end
    

    I have some cucumber helpers for Timecop here. They let you do things like:

    Given it is currently January 24, 2008
    And I go to the new post page
    And I fill in "title" with "An old post"
    And I fill in "body" with "..."
    And I press "Submit"
    And we jump in our Delorean and return to the present
    When I go to the home page
    I should not see "An old post"
    

提交回复
热议问题