Mocking Date.today in Ruby on Rails tests

Since for the last couple of months I’m all about test-driven development I wanted to test a couple of ActiveRecord callbacks that relied on Date.today method.

Here’s a quick hack for your test_helper.rb file that allows you to specify the date returned by Date.today.

class Date
  class << self
    @@mocked_today = nil

    alias :unmocked_today :today

    def today
      @@mocked_today || unmocked_today
    end

    def with_mocked_today(mocked_today)
      if block_given?
        @@mocked_today = mocked_today
        begin
          yield
        ensure
          @@mocked_today = nil
        end
      end
    end
  end
end

And a quick example how to use it:

Date.with_mocked_today Date.parse("2008-01-01") do
  // your code here...
end