I've been tasked with creating custom error pages that fall in line with our application. I found https://wearestac.com/blog/dynamic-error-pages-in-rails which works perfectly fine. I don't get any routing errors and manually testing shows that each page renders correctly.
However, when creating controller specs for the controller used to delegate the routes to the views, I am running into an issue. My views are named 404.html.erb, 500.html.erb, 422.html.erb. They are located in app/views. My code is almost exactly the same as what is listed in the link above, however for posterity and clarity, the relevant code is shown below as well as the error message is shown below:
Error message: ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"errors", :params=>{:code=>"404"}}
app/controllers/errors_controller.rb:
# frozen_string_literal: true
class ErrorsController < ApplicationController
def show
render status_code.to_s, status: status_code
end
protected
# get status code from params, default 500 in cases where no error code
def status_code
params[:code] || 500
end
end
spec/controllers/errors_controller_spec.rb:
require 'rails_helper'
describe ErrorsController, type: :controller do
describe '#show' do
it 'renders the 404 error page when it receives a 404 status code' do
get :show, params: { code: '404' }
# ive also tried changing the param passed to redirect_to to error_404 to no effect
expect(response).to redirect_to(error_404_path)
end
it 'renders the 422 error page when it receives a 422 status code' do
get :show, params: { code: '422' }
expect(response).to redirect_to(error_422_path)
end
it 'renders the 500 error page when it receives a 500 status code' do
get :show, params: { code: '500' }
expect(response).to redirect_to(error_500_path)
end
end
end
config/routes.rb (only the relevant route, our full routes file is gigantic)
%w(404 422 500).each do |code|
get code, to: "errors#show", code: code, as: 'error_' + code
end
config/application.rb (only the relevant line, everything else is standard):
config.exceptions_app = self.routes
I have tried expanding the routes so that each was explicitly defined, as well as reverting to the first non-DRY form in the link. I've also tried changing the redirect_to call to a render_template call, to no effect.
I've scratched my head for days hoping to figure it out but I've had no luck. Again, the route works perfectly fine in development, but when I try to test that these routes work in rspec, it can't find any route.
The error message is the same for each spec in the file, aside from the status code. Any help would be appreciated!