My Coding Blog

Hacking on everyday programming annoyances

Stop Selenium Loading Firefox in the Foreground

In my day job, an important part of our testing suite involves driving Firefox via RSpec feature specs. Which is realised through the use of the Capybara and Selenium Webdriver gems.

As all testing suites grow, we eventually introduced the awesome Parallel Tests gem, cutting run-times dramatically. An unfortunate side effect however, multiple instances of Firefox randomly opening in the foreground and stealing focus.

Some digging into the selenium-webdriver codebase found the culprit in the Selenium::WebDriver::FireFox::Launcher class:

[selenium-webdriver]/lib/selenium/webdriver/firefox/launcher.rb:64
1
2
3
4
def start
  assert_profile
  @binary.start_with @profile, @profile_dir, "-foreground"
end

Removing the -foreground parameter has the desired effect of loading Firefox behind the terminal, and not stealing focus. But since the selenium-webdriver codebase is hosted in google code a pull request was out of the question, time for some monkey patching.

The following code goes at the base of spec_helper:

[your-project]/spec/spec_helper.rb
1
2
3
4
5
6
7
8
9
10
if ENV.fetch('SELENIUM_WEBDRIVER_FIREFOX_NO_FOREGROUND', '').downcase == 'true'
  module Selenium::WebDriver::Firefox
    class Launcher
      def start
        assert_profile
        @binary.start_with @profile, @profile_dir, ''
      end
    end
  end
end

The patch is disabled by default, to opt-in set the environment variable as part of your testing command:

1
SELENIUM_WEBDRIVER_FIREFOX_NO_FOREGROUND=true rake parallel:spec

Happy testing folks!

Comments