One of my Rails projects makes heavy use of time zones. I’ve run into some issues writing good tests for this type of thing. In particular, I’ve needed my tests to run within a time zone outside my own. But I don’t want to permanently change the time zone within the scope of the entire test run. I ended up coding this handler:
module ZoneWarp def pretend_zone_is(zone) original_zone = Time.zone begin Time.zone = zone yield ensure Time.zone = original_zone end end end Test::Unit::TestCase.send(:include, ZoneWarp)
Simply stick this code in a file inside your config/initializers
directory (or include it from test_helper.rb or spec_helper.rb if you insist on doing it the right way) and you’re all set to write tests like this:
test "code works in other time zones" do pretend_zone_is "Mountain Time (US & Canada)" do # assertions go here end end