Home > Mobile >  Testing Rails 404 and 500 JSON reponse
Testing Rails 404 and 500 JSON reponse

Time:01-08

I am building a JSON backend API with Rails, and I can't seem to figure this out: How can one test using RSpec the Rails default error responses? For example, for a generic 404 request, I currently have the following request spec:

require 'rails_helper'

RSpec.describe '404 errors' do
  let(:json) { JSON.parse(response.body) }

  before { get '/noexistent', headers: headers }

  # examples
end

Rails, however, refuses to render the 404 response that it would normally yield, instead simply raising:

ActionController::RoutingError:
  No route matches [GET] "/404"

I've tried removing config.consider_all_request_local = true from config/environments/test.rb, with no results.

Note that I've seen this question (it's where I got the idea for consider_all_requests_local), but it applies to development, not testing.


EDIT: I am using config.exceptions_app = self.routes to redirect errors to an ErrorsController. This works fine in development or production, but not while testing. When testing, I still get the above error. Any ideas?

CodePudding user response:

It turns out the answer was rather simple. I had to change this line in config/environments/test.rb:

  # Raise exceptions instead of rendering exception templates.
  config.action_dispatch.show_exceptions = false

to:

  # Do not raise exceptions instead of rendering exception templates.
  config.action_dispatch.show_exceptions = true
  •  Tags:  
  • Related