How to run system specs headlessly or not headlessly at will

by Jason Swett,

I used to prefer seeing my system 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/system/create_customer_spec.rb

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

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

Let’s take a look at how to turn that dream into reality.

The implementation

The desired functionality can be implemented by adding the following to spec/rails_helper.rb:

# spec/rails_helper.rb

RSpec.configure do |config|
  config.before(:each, type: :system) do
    driven_by ENV['SHOW_BROWSER'] ? :selenium_chrome : :selenium_chrome_headless

Now, for all system specs, Capybara will use the :selenium_chrome_headless driver normally and the :selenium_chrome driver when SHOW_BROWSER=true is specified.

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

Leave a Reply

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