Mock the browser time or time zone in Selenium features

Updated . Posted . Visible to the public.

In Selenium features the server and client are running in separate processes. Therefore, when mocking time with a tool like Timecop Show snapshot , the browser controlled by Selenium will still see the unmocked system time.

timemachine.js Show snapshot allows you to mock the client's time by monkey-patching into Javascript core classes. We use timemachine.js in combination with the Timecop Show snapshot gem to synchronize the local browser time to the time currently mocked with Timecop.

To integrate those two, we include and activate timemachine.js in our Rails layout whenever we see that Timecop is mocking the time:

- if defined?(Timecop) && Timecop.top_stack_item
  = javascript_include_tag "timemachine.js"
    timemachine.config({ dateString: #{}, tick: true })


timemachine.js will mock the time as soon as it is loaded. It does not wait for timemachine.config().

Now you can simply mock time using or its respective Spreewald steps and the browser will return the same time in new Date().

If you would like to stop the time from ticking after setting it to Timecop's time, pass a { tick: false } option to the timemachine.config() call.

Note that this will not change the browser's time zone. If you mock the time to 5 PM CET and the browser is in the PDT time zone, the browser time will be 5 PM PDT. Which brings us to ...

Mocking the time zone

You can't really change the local time zone of the Selenium-controlled browser. What you can do is change the time zone of the process running your tests by setting a TZ=CET (or TZ=PDT or TZ=UTC etc.) environment variable.

This way, when the test process spawns another process to run a browser, it will inherit the environment and also believe it lives in that zone.

To do so, run the following code before your test suite (e. g. in env.rb, spec_helper.rb or test_helper.rb):

ENV['TZ'] = 'CET'

Avoid setting this from an individual test, since you don't know whether or not the Selenium-controlled browser has already launched.

Note that we have only tested this with a Selenium-controlled Firefox, not with Chrome.

Henning Koch
Last edit
Henning Koch
stub, firefox
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2012-08-17 15:34)