Specs on ErrorsController in Rails

There are different approaches to respond to failed requests in Rails.
By default Rails handles exceptions serving static HTML documents stored in the public directory. In particular, 500 (server error) and 404 (not found) responses result in the application’s rendering 500.html and 404.html, respectively.

In our application usually we build custom 404 and 500 error pages served trough ErrorsController. Several guides illustrate how to move your error pages from static html to dynamic views, here some examples:

This article wants to be a simple reminder for execption pages testing. Remember to test expected error pages behaviour inside a inside a request spec.

The request spec provides a couple of nice things not available in a controller spec. First, it actually hits your application’s HTTP endpoints, as opposed to calling controller methods directly. Running this test insisde a request spec allow us to check the entire functionality specially the options that tells Rails to serve error pages from routes config.exceptions_app = self.routes.

For example if you want to test a simple ActiveRecord::RecordNotFound for a specific resource:

require 'rails_helper'

RSpec.describe 'Show Post', type: :request do
  context 'when post is not present' do
    get '/post/not_existing'
    it { expect(response).to have_http_status :not_found }

    it 'returns an error message' do
      expect(response).to have_content('This is not the page you are looking for.')


Leave a Reply

Please Login to comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.