Capybara: Preventing server errors from failing your test

Posted . Visible to the public. Repeats.

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.

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
Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2021-03-10 10:18)