Skip to content

Instantly share code, notes, and snippets.

@mcmire
Last active October 16, 2021 11:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mcmire/68cd9c74ba765a2d5dfb14abf58409aa to your computer and use it in GitHub Desktop.
Save mcmire/68cd9c74ba765a2d5dfb14abf58409aa to your computer and use it in GitHub Desktop.
Ignore requests for broken images in Capybara tests
# Instructions
# ------------
#
# * Save this as app/middlewares/bypass_broken_images_middleware.rb
# * Add the following inside of the Rails.application.configure block
# in config/environments/test.rb:
#
# config.middleware.insert_before(
#  ActionDispatch::DebugExceptions,
#  BypassBrokenImagesMiddleware,
# )
class BypassBrokenImagesMiddleware
def initialize(app)
@app = app
end
def call(env)
@app.(env)
rescue => error
if unknown_path?(error) && request_for_image?(env)
# nothing to see here, move along
[404, {}, ""]
else
raise error
end
end
private
def unknown_path?(error)
error.is_a?(ActionController::RoutingError)
end
def request_for_image?(env)
env["PATH_INFO"] =~ %r{\A/(assets|images)/} ||
env["PATH_INFO"] =~ /\.(jpg|jpeg|png)\Z/
end
end
@keoghpe
Copy link

keoghpe commented Aug 31, 2018

Thanks for creating this awesome gist!

I'm getting the following error in my specs - Read error: #<NoMethodError: undefined method 'each' for "":String>.

Changing line 23 to [404, {}, []] fixed it for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment