Skip to content

Instantly share code, notes, and snippets.

@bricker
Last active August 29, 2015 14:12
Show Gist options
  • Save bricker/35574d6acc5fde4f62be to your computer and use it in GitHub Desktop.
Save bricker/35574d6acc5fde4f62be to your computer and use it in GitHub Desktop.
require 'rails_helper'
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :not_found
rescue_from Pundit::NotAuthorizedError, with: :permission_denied
rescue_from ActionController::UnknownFormat, with: :unknown_format
private
def permission_denied
flash[:danger] = I18n.t 'pundit.permission_denied'
redirect_after_rescue
end
def unknown_format
flash[:danger] = I18n.t 'errors.unknown_format'
redirect_after_rescue
end
def not_found
flash[:danger] = I18n.t 'errors.error_404'
redirect_after_rescue
end
def redirect_after_rescue
self.response_body = nil
redirect_to(request.referrer || user_signed_in? ? authenticated_root_path : unauthenticated_root_path)
end
end
RSpec.describe "rescues" do
controller(ApplicationController) do
def error_not_found
raise ActiveRecord::RecordNotFound
end
def error_not_authorized
raise Pundit::NotAuthorizedError
end
def error_unknown_format
raise ActionController::UnknownFormat
end
end
describe 'handling ActiveRecord::RecordNotFound exceptions' do
it 'redirects to the root path' do
get :error_not_found
expect(response).to redirect_to('/')
expect(flash[:danger]).to eql 'We kunnen de pagina die je zoekt niet vinden'
end
it 'shows the appropriate flash message' do
get :error_not_found
expect(flash[:danger]).to eql 'We kunnen de pagina die je zoekt niet vinden'
end
end
describe 'handling Pundit::NotAuthorizedError exceptions' do
it 'redirects to the root path' do
get :error_not_authorized
expect(response).to redirect_to('/')
end
it 'shows the appropriate flash message' do
get :error_not_authorized
expect(flash[:danger]).to eql 'Je hebt geen toegang tot deze actie'
end
end
describe 'handling ActionController::UnknownFormat exceptions' do
it 'redirects to the root path' do
get :error_unknown_format
expect(response).to redirect_to('/')
end
it 'shows the appropriate flash message' do
get :error_unknown_format
expect(flash[:danger]).to eql 'We kunnen de pagina die je zoekt niet vinden'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment