How to run feature specs headlessly or not headlessly at will

by Jason Swett,

I used to prefer seeing my feature specs run in the browser but lately I’ve been preferring to run them headlessly. It’s a little faster that way and I find it a little less disruptive.

Sometimes I still find myself wanting to see a certain test in the browser though. Seeing the test run in the browser can make diagnosis of any problems much easier.

The dream

What would be ideal is if I could do something like the following. To run a spec headlessly, I could do this:

$ rspec spec/features/create_customer_spec.rb

To see the same spec run in the browser, I could do this:

$ SHOW_BROWSER=true rspec spec/features/create_customer_spec.rb

To my surprise and delight, I was able to code something up that turned my dream into reality.

The implementation

Turns out the desired functionality can be implemented by creating a file called `spec/support/webdriver.rb`:

# spec/support/webdriver.rb
Capybara.javascript_driver = ENV['SHOW_BROWSER'] ? :selenium_chrome : :selenium_chrome_headless

Now, for any feature spec where `js: true` is specified, Capybara will use the `:selenium_chrome_headless` JavaScript driver normally and the `:selenium_chrome` driver when `SHOW_BROWSER=true` is specified.

Thanks to Reddit user jrochkind for helping me improve this solution.

  •  
  •  
  •  
  • 19

Leave a Reply

Your email address will not be published. Required fields are marked *