Method: Timecop.freeze

Defined in:
lib/timecop/timecop.rb

.freeze(*args, &block) ⇒ Object

Allows you to run a block of code and “fake” a time throughout the execution of that block. This is particularly useful for writing test methods where the passage of time is critical to the business logic being tested. For example:

joe = User.find(1)
joe.purchase_home()
assert !joe.mortgage_due?
Timecop.freeze(2008, 10, 5) do
  assert joe.mortgage_due?
end

freeze and travel will respond to several different arguments:

  1. Timecop.freeze(time_inst)

  2. Timecop.freeze(datetime_inst)

  3. Timecop.freeze(date_inst)

  4. Timecop.freeze(offset_in_seconds)

  5. Timecop.freeze(year, month, day, hour=0, minute=0, second=0)

  6. Timecop.freeze() # Defaults to Time.now

When a block is also passed, Time.now, DateTime.now and Date.today are all reset to their previous values after the block has finished executing. This allows us to nest multiple calls to Timecop.travel and have each block maintain it’s concept of “now.”

The Process.clock_gettime call mocks both CLOCK::MONOTIC and CLOCK::REALTIME

CLOCK::MONOTONIC works slightly differently than other clocks. This clock cannot move to a particular date/time. So the only option that changes this clock is #4 which will move the clock the requested offset. Otherwise the clock is frozen to the current tick.

  • Note: Timecop.freeze will actually freeze time. This can cause unanticipated problems if benchmark or other timing calls are executed, which implicitly expect Time to actually move forward.

  • Rails Users: Be especially careful when setting this in your development environment in a rails project. Generators will load your environment, including the migration generator, which will lead to files being generated with the timestamp set by the Timecop.freeze call in your dev environment

Returns the value of the block if one is given, or the mocked time.



57
58
59
# File 'lib/timecop/timecop.rb', line 57

def freeze(*args, &block)
  send_travel(:freeze, *args, &block)
end