ActiveSupport includes Timecop-like helpers

Updated . Posted . Visible to the public. Repeats.

ActiveSupport (since 4.1) includes test helpers to manipulate time, just like the Timecop gem Show archive.org snapshot :

  • To freeze the current time, use freeze_time (ActiveSupport 5.2+):

    freeze_time
    
  • To travel to a specific moment in time, use travel_to:

    travel_to 1.hour.from_now
    

    Important

    When freezing time with #travel_to, time will be frozen (like with freeze_time). This means that your application can't detect passage of time by using Time.now.

  • To travel a relative amount of time, use travel:

    travel 1.day
    

All those methods may also receive a block to call and restore time afterwards. If you don't provide a block, you must call travel_back or unfreeze_time (ActiveSupport 6+, alias for travel_back) once you are done.

Simply load the TimeHelpers module as required by your test framework. Example:

RSpec.configure do |config|
  config.include ActiveSupport::Testing::TimeHelpers
end

Comparison to Timecop

Timecop allows you to choose between freezing time (Timecop.freeze) or letting the clock to tick (Timecop.travel). In contrast, the ActiveSupport helpers always freeze time. If you never need to detect the passage of time, ActiveSupport's time helpers might be good enough.

Arne Hartherz
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2019-11-13 20:38)