Read more

Capybara: Preventing server errors from failing your test

Henning Koch
March 10, 2021Software engineer at makandra GmbH

When your Rails application server raises error, Capybara will fail your test when it clears the session after the last step. The effect is a test that passes all steps, but fails anyway.

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

Capybara's behavior will help you to detect and fix errors in your application code. However, sometimes your application will explode with an error outside your control. Two examples:

  • A JavaScript library references a source map in its build, but forgets to package the source map
  • CarrierWave cleans up an upload or cache file after the record was deleted / updated, and only then does the browser requests that image

Workaround

The code below patches Capybara to ignore errors with a given message. Adust the IGNORE_MESSAGE array for your application.

module IgnoreMissingStaticFiles

  # Adjust this list of regular expressions for your application
  IGNORE_MESSAGES = [
    # We have some JS libraries with missing source maps
    %r{No route matches .*"[^"]+\.map"}i,
    # CarrierWave may delete cache files before the browser tries to load them
    %r{No route matches .*"/uploads/test/\d+-[\d\-]+/[^"]+"}i,
  ].freeze

  def raise_server_error!
    super
  rescue StandardError => e
    # Ignore errors about missing source maps
    unless IGNORE_MESSAGES.any? { |ignore_message| e.message =~ ignore_message }
      raise e
    end
  end
end

Capybara::Session.class_eval do
  prepend IgnoreMissingStaticFiles
end
Posted by Henning Koch to makandra dev (2021-03-10 11:18)