Posted almost 10 years ago. Visible to the public. Linked content.

Mock the browser time or time zone in Selenium features

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

timemachine.js Archive allows you to mock the client's time by monkey-patching into Javascript core classes. We use timemachine.js in combination with the Timecop Archive 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" :javascript 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 Firefox, 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 Firefox has already launched.

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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Henning Koch
Last edit:
6 months ago
by Henning Koch
stub, firefox
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more