Posted about 7 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 allows you to mock the client's time by monkey-patching into Javascript core classes. We use timemachine.js in combination with the Timecop 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:

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

Now you can simply mock time using Timecop.travel 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):

Copy
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.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Henning Koch
Last edit:
over 1 year ago
by Henning Koch
Keywords:
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 cookies to improve usability and analyze traffic.
Accept or learn more