Posts Tagged ‘tdd’

Timecop: Freeze Time in Ruby for Better Testing

Wednesday, November 19th, 2008 by John Trupiano
The API mentioned in this blog post is specific to v0.1.0. The latest version is v0.2.0. See the blog post announcement, the documentation, or the github home page.

This past weekend I released v0.1.0 of the Timecop gem. Timecop makes it dead simple to travel through or freeze time for the sake of creating a predictable and ultimately testable scenario.

The gem is derived from a plugin I wrote a while back to achieve more or less the same functionality for an extremely time-sensitive application. My goals for the gem included:

  1. Drop-in-ability: The primary goal is to allow your app to continue to use Time.now, Date.today and DateTime.now as normal within your application. No overloading of functions with optional arguments (a la today=Date.today) just so you can write test cases.
  2. Environment independence: I wanted the gem to work (a) w/ rails (ActiveSupport actually), (b) w/ plain ruby when the ‘date’ library has been loaded, and (c) w/ plain ruby when the ‘date’ library had not been loaded.
  3. Library independence: I could have utilized mocha to achieve the mocking functionality found under the hood, but because I wanted this to work with plain vanilla ruby, libraries like mocha are out.
  4. Short-term time travel: I wanted to expose the ability to temporarily change the concept of “now.” This is particularly helpful when writing tests where time needs to pass.
  5. Long-range time travel: I wanted to expose the ability to change the concept of “now” for an indeterminate period of time. This is particularly helpful when setting up a rails test environment along with the test data.
  6. Nested time travel: I wanted to provide the ability to nest traveling, allowing the state to be kept within each block (we’ll see an example later).

The gem is hosted on RubyForge and can be installed by simply running:

sudo gem install timecop

(more…)