instance method travel

Ruby on Rails 8.0.4

Since v4.1.16

Available in: v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

travel(duration, with_usec: false, &block)

Changes current time to the time in the future or in the past by a given time difference by stubbing Time.now, Date.today, and DateTime.now. The stubs are automatically removed at the end of the test.

Note that the usec for the resulting time will be set to 0 to prevent rounding errors with external services, like MySQL (which will round instead of floor, leading to off-by-one-second errors), unless the with_usec argument is set to true.

Time.current     # => Sat, 09 Nov 2013 15:34:49 EST -05:00
travel 1.day
Time.current     # => Sun, 10 Nov 2013 15:34:49 EST -05:00
Date.current     # => Sun, 10 Nov 2013
DateTime.current # => Sun, 10 Nov 2013 15:34:49 -0500

This method also accepts a block, which will return the current time back to its original state at the end of the block:

Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
travel 1.day do
  User.create.created_at # => Sun, 10 Nov 2013 15:34:49 EST -05:00
end
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00

Parameters

duration req
with_usec key = false
block block
Source
# File activesupport/lib/active_support/testing/time_helpers.rb, line 97
      def travel(duration, with_usec: false, &block)
        travel_to Time.now + duration, with_usec: with_usec, &block
      end

Defined in activesupport/lib/active_support/testing/time_helpers.rb line 97 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveSupport::Testing::TimeHelpers

Type at least 2 characters to search.

↑↓ navigate · open · esc close