skip to content

In a Rails test, how do travel_to, travel and freeze_time control time to check that a seven-day trial ends, and what do they not stub?

level: middleimportance: should knowfreq 52%

answer

  1. Time.now, Date.today, DateTime.now
  2. the clock stops, it does not tick
  3. microseconds dropped unless with_usec: true
  4. travel_back runs after every test
  5. the database's NOW() is untouched

basics

~20 s

travel_to(time), travel(duration) and freeze_time stub Time.now, Date.today and DateTime.now so the clock stops at the chosen instant, and Rails undoes the stubs after each test. Database functions like NOW(), other processes and the browser keep real time.

solid answer

~40 s

`ActiveSupport::Testing::TimeHelpers` is included in `ActiveSupport::TestCase`. `travel_to(time)` stubs `Time.now`, argument-less `Time.new`, `Date.today` and `DateTime.now` to return that instant, so `Time.current` and Active Record timestamps follow. The clock is **frozen** there, not ticking. `travel(7.days)` is `travel_to(Time.now + 7.days)`, and `freeze_time` is `travel_to(Time.now)`. Microseconds are dropped unless you pass `with_usec: true`. A block form restores the previous time afterwards; nesting a block `travel_to` inside another raises; and `after_teardown` calls `travel_back` (alias `unfreeze_time`) for every test. For a meditation app: create the user, `travel 7.days + 1.minute`, then assert `user.trial_expired?`. What is not stubbed: SQL like `NOW()` or a `CURRENT_TIMESTAMP` column default, `Process.clock_gettime`, other processes, and the browser in a system test. In RSpec, include `ActiveSupport::Testing::TimeHelpers` yourself.

code

ruby · 11 lines
ruby
test "reminder goes to users whose trial ends tomorrow" do
  travel_to Time.zone.local(2026, 3, 1, 9, 0, 0) do
    users(:mia).update!(trial_ends_at: 1.day.from_now)

    # Works: the boundary is computed in Ruby
    assert_includes User.where(trial_ends_at: ..2.days.from_now), users(:mia)

    # Fragile: NOW() is the database clock, not the stubbed one
    # User.where("trial_ends_at < NOW() + INTERVAL '2 days'")
  end
end

go deeper

for a junior

Use travel and travel_to to move into the future for expiry tests, and know that time is frozen at the target.

for a middle

Explain which methods are stubbed, the usec truncation, the block form and automatic travel_back, and how RSpec suites include the helpers.

for a senior

Find time logic that escapes the stubs, such as SQL NOW() or column defaults, and move boundaries into Ruby so tests can control them.

for a principal

Set conventions for time handling, such as Time.current in Ruby and no database clock in business rules, so the whole suite stays testable.

## What the helpers do `ActiveSupport::Testing::TimeHelpers` lets a test move the clock instead of waiting for it. It is included in `ActiveSupport::TestCase`, so every Rails test class has it. The helpers work by **stubbing** a few class methods with fixed replacements: - `Time.now` returns the chosen instant. - `Time.new` with no arguments returns it too; with arguments it behaves normally. - `Date.today` returns that instant's date. - `DateTime.now` returns that instant as a `DateTime`. `Time.current`, `Date.current`, `1.day.ago`, Active Record's `created_at` and `updated_at`, and anything else built on `Time.now` follow the stub. ## The three entry points | Helper | Equivalent | Typical use | |---|---|---| | `travel_to(time)` | | jump to a specific moment, such as `Time.zone.local(2026, 12, 24, 19)` | | `travel(duration)` | `travel_to(Time.now + duration)` | move forward relative to now, such as `travel 7.days` | | `freeze_time` | `travel_to(Time.now)` | stop the clock where it is | All three **freeze** time at the target. Code that calls `Time.now` twice gets the same value, which removes off-by-a-millisecond failures. Arguments are interpreted generously: a `Date` means midnight of that day, and a string is parsed with `Time.zone.parse`. By default the target is truncated to whole seconds, because databases often store fewer fractional digits than Ruby; `with_usec: true` keeps the microseconds. ## Undoing it - **Block form:** `travel_to(time) { ... }` restores the previous state when the block ends. - **Explicit:** `travel_back`, also available as `unfreeze_time`. - **Automatic:** the module's `after_teardown` calls `travel_back`, so no stub leaks into the next test. Calling `travel_to` with a block while already inside a `travel_to` block raises an error that recommends successive `travel` blocks instead, because nested absolute jumps are confusing to read. ## A seven-day trial ```ruby class TrialTest < ActiveSupport::TestCase test "a trial ends after seven days" do user = User.create!(email_address: "[email protected]", password: "calm-breath-42") travel 7.days - 1.minute assert_not user.reload.trial_expired? travel 2.minutes assert user.reload.trial_expired? end end ``` Because each `travel` is relative to the current, already stubbed time, the two calls add up to seven days and one minute. ## Freeze or travel? | Goal | Helper | |---|---| | Make every `Time.now` in the test identical | `freeze_time` | | Check behaviour at a named date, such as a leap day or New Year | `travel_to Time.zone.local(...)` | | Move forward past a deadline relative to now | `travel 7.days` | | Limit a time change to a few lines | any of them with a block | Freezing at the start of a test also makes later assertions on timestamps exact, because creation and comparison read the same instant. ## Time travel in other test types - **Jobs performed in the test** run in the same process and see the travelled time, which is how expiry jobs are tested. - **Integration tests** handle requests in-process, so controllers see the travelled time as well. - **System tests** share the stub with the Puma server thread, but not with the browser. ## What is not stubbed The stubs live in the Ruby process. Anything that reads time elsewhere keeps the real clock: 1. **The database.** A scope written as `where("trial_ends_at < NOW()")` or a column with `default: -> { "CURRENT_TIMESTAMP" }` uses the database server's clock. Prefer `where(trial_ends_at: ...Time.current)` in Ruby so tests can move it. 2. **Monotonic and system clocks** such as `Process.clock_gettime`, used for measuring durations. 3. **Other processes**: a separate job worker, a cron script, an external service. 4. **The browser** in a system test: the Puma thread shares the stub, but JavaScript's `Date` runs in Chrome with the real time. ## Pitfalls - Expecting time to keep moving after `travel_to`; code that polls until "a second has passed" never sees it pass. - Comparing a stubbed time with a value read from the database without considering the truncation to seconds. - Forgetting that rspec-rails does not mix the helpers in: add `config.include ActiveSupport::Testing::TimeHelpers` in `rails_helper.rb`, and many suites also add `config.after { travel_back }` to make the undo explicit.

  • Why can a test fail when comparing created_at with Time.now after travel_to?
    Usually it does not, because both read the stubbed `Time.now`. Failures come when one side passed through the database or was computed with real time: a column default from `CURRENT_TIMESTAMP`, or a time read before the stub. With `with_usec: true` there is also the database's fractional-second precision to consider.
  • Why does Rails raise when travel_to with a block is nested inside another travel_to block?
    Nested absolute jumps make it hard to see which time applies where, and restoring the outer time at the end of the inner block is confusing. Rails raises with a message recommending successive `travel` calls with relative durations instead.

travel_to is like setting every clock inside your house to the same chosen moment and stopping them; the clock tower outside, the database or the browser, still shows real time.

  • After travel_to, the clock keeps ticking forward from the new time
  • travel_to also changes the database server's NOW()
  • Time stubs leak into the next test unless travel_back is called
  • travel_to keeps microseconds by default
  • freeze_time stops only Date.today, not Time.now