jtrupiano / timecop

A gem providing “time travel” and “time freezing” capabilities, making it dead simple to test time-dependent code. It provides a unified method to mock Time.now, Date.today, and DateTime.now in a single call.

This URL has Read+Write access

README.textile

timecop

  • http://github.com/jtrupiano/timecop

DESCRIPTION

A gem providing simple ways to mock Time.now, Date.today, and DateTime.now. It provides “time travel” and “time freezing” capabilities, making it dead simple to test time-dependent code.

FEATURES

  • Temporarily (or permanently if you prefer) change the concept of Time.now, DateTime.now, and Date.today
  • Timecop api allows arguments to be passed into #freeze and #travel as one of the following:
  • Time instance
  • DateTime instance
  • Date instance
  • individual arguments (year, month, day, hour, minute, second)
  • a single integer argument that is interpreted as an offset in seconds from Time.now
  • Nested calls to Timecop#travel and Timecop#freeze are supported — each block will maintain it’s interpretation of now.

SHORTCOMINGS

  • Only fully tested on the 1.8.6 Ruby implementations. 1.8.7 and 1.9.1 should be tested, as well as other flavors (jruby, etc.)

SYNOPSIS

Run a time-sensitive test


  joe = User.find(1)
  joe.purchase_home()
  assert !joe.mortgage_due?
  # move ahead a month and assert that the mortgage is due
  Timecop.freeze(Date.today + 30) do
    assert joe.mortgage_due?
  end

Set the time for the test environment of a rails app — this is particularly helpful if your whole application is time-sensitive. It allows you to build your test data at a single point in time, and to move in/out of that time as appropriate (within your tests)

in config/environments/test.rb


  config.after_initialize do
    # Set Time.now to September 1, 2008 10:05:00 AM
    t = Time.local(2008, 9, 1, 10, 5, 0)
    Timecop.travel(t)
  end

REQUIREMENTS

  • None

INSTALL

  • sudo gem install timecop (latest stable version from rubyforge)
  • sudo gem install jtrupiano-timecop (HEAD of the repo from github)

REFERENCES