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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)