Debugging Capybara Specs via Page Screenshots

How to debug front-end JavaScript feature specs using Capybara, Poltergeist and full-page screenshots.

Failing feature specs are difficult to debug, especially in CI. On an recent eCommerce project, our team opted to use Vue.js for several important app components and to made heavy use of feature specs to ensure everything worked as expected. Our testing stack consisted of Rspec 3, Capybara, and Poltergeist.

To avoid having to debug specs by manually taking screenshots or having to go onto the Circle CI server, we came up with a simple script that automatically takes a screenshot with some useful meta data for every feature spec failure.

# rails_helper.rb
RSpec.configure do |config|

 config.after(:each, js: true) do |example|
    if example.exception
      meta = example.metadata
      name = "test-failure-#{File.basename(meta[:file_path])}-#{meta[:line_number]}.png"

      # Save screenshots in CI
      screenshot_root_path = ENV["CIRCLE_ARTIFACTS"] || Rails.root.join("tmp", "capybara")

      screenshot_path = [screenshot_root_path, name].join("/")

      page.save_screenshot(screenshot_path, full: true)
      $stdout << "\nScreenshot Taken: #{screenshot_path}\n"
    end
  end

One of the important bits for integrating with Circle CI is below. If on a Circle server, add this to the build artifacts path, otherwise put it in tmp. If you're using something other than Circle CI, you'll probably need to adjust this configuration.

screenshot_root_path = ENV["CIRCLE_ARTIFACTS"] || Rails.root.join("tmp", "capybara")

Cheers!