Skip to content

Instantly share code, notes, and snippets.

@flanger001
Last active October 14, 2015 13:00
Show Gist options
  • Save flanger001/44ccdadafe678dc72857 to your computer and use it in GitHub Desktop.
Save flanger001/44ccdadafe678dc72857 to your computer and use it in GitHub Desktop.
Dynamic error pages in Rails with testing
# in configure block
config.exceptions_app = self.routes
h1 Error #{response.status}
p The resource you are trying to reach cannot be found.
p= link_to 'Click here to go back', :back
require 'test_helper'
# Assuming capybara and capybara-webkit are installed
class ErrorPagesTest < ActionDispatch::IntegrationTest
# This controller needs to think the app is in production mode, or else the errors get swallowed.
# But we don't want the rest of the test suite to behave as such?
# This is hacky but I'm at a loss as to how to test it otherwise
Rails.application.configure do
config.consider_all_requests_local = false
config.action_dispatch.show_exceptions = true
end
test 'should get 404 if visiting nonexistent page' do
visit '/nonexistent-page'
assert page.status_code == 404
assert page.has_content?('The resource you are trying to reach cannot be found.')
end
test 'should get 500 if error' do
visit '/makes_500_error'
assert page.status_code == 500
assert page.has_content?('The resource you are trying to reach cannot be found.')
end
test 'should get 403 if forbidden' do
visit '/no_u_cannot_haz'
assert page.status_code == 403
end
end
class ErrorsController < ApplicationController
def render(*args, &block)
super 'error', *args, &block
end
def forbidden
render status: 403
end
def not_found
render status: 404
end
def internal_server_error
render status: 500
end
end
class PagesController < ApplicationController
# ...
def no_u_cannot_haz
redirect_to '/403'
end
# ..
end
# ...
get '/403', to: 'errors#forbidden'
get '/404', to: 'errors#not_found'
get '/500', to: 'errors#internal_server_error'
get '/makes_500_error', to: 'pages#template_with_error'
get '/no_u_cannot_haz', to: 'pages#no_u_cannot_haz'
# ...
@flanger001
Copy link
Author

Original concept is from https://mattbrictson.com/dynamic-rails-error-pages

I wanted to figure out how to test it.

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