16

I'm working on getting a rails 3 application ready to use time zones. My development machine is in EDT and the servers I'm hosting on are in UTC. Is there a way in my rspec tests to change the system time zone ruby is using so that I'm running tests using the same system time zone without having to change the system clock on my computer? I've looked into Delorean and Timecop and they're not what I'm looking for. I'm looking for something like

Time.system_time_zone = "UTC"

...and then Time.now would return the UTC time instead of whatever my system time zone is set to.

Dan Caddigan
  • 1,578
  • 14
  • 25

2 Answers2

14
before {Time.stub(:now) {Time.now.utc}}

With this, anywhere Time.now is called in your tests, it will return your system's time in UTC.

Example:

describe Time do
  before {Time.stub(:now) {Time.now.utc}}

  it "returns utc as my system's time" do
    Time.now.utc?.should be_true
  end
end
Charles Caldwell
  • 16,649
  • 4
  • 40
  • 47
-1

Rails gives you precisely what you are looking for:

Time.zone = "UTC"

Look at http://api.rubyonrails.org/classes/Time.html#method-c-zone-3D for more information.

CubaLibre
  • 1,675
  • 13
  • 22
  • 1
    This doesn't do what I was asking. This tells rails that when you go through Time.zone to put things in the time zone specified by Time.zone. I'm looking to have times return in UTC when you use Time.now. – Dan Caddigan Apr 13 '13 at 15:29
  • 1
    Right, you would need to call `Time.zone.now` or `Time.current` instead of `Time.now` – CubaLibre Apr 15 '13 at 10:41
  • Right, but the whole idea of my question was to set the system time in my tests to UTC. What your solution is doing is telling rails to convert all times to UTC through 'Time.zone'. Doing 'Time.now' will still give you time in system-specified time zone. Charles' solution does just this. – Dan Caddigan Apr 16 '13 at 13:55