Setting system time in rspec tests without changing system clock

Dan Caddigan picture Dan Caddigan · Apr 12, 2013 · Viewed 7.3k times · Source

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.

Answer

Charles Caldwell picture Charles Caldwell · Apr 12, 2013
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