jeudi 25 août 2016

How to test catching StandardError in Rails controller

I have a root controller in my rails api application something like:

   # app/controllers/api_controller.rb
   class ApiController < ApplicationController
       rescue_from StandardError, with: :handle_standard_error

       ##
       # For catching all unhandled errors that might be thrown
       ##
       def handle_standard_error(exc)
         # don't squash in test mode
         raise exc if ENV['RAILS_ENV'] == 'test'

         msg = 
           if ENV['RAILS_ENV'] == 'production'
             I18n.t('unhandled_error_occurred')
           else
             exc.message
           end

         render 'error', :internal_server_error
       end
   end

Essentially, this doesn't handle the exception in test mode, outputs a generic message in production and outputs the actual exception in development.

I'd like to be able to test the behaviour, with something like:

    # test/controllers/api_controller_test.rb
    test 'handle standard error' do
      ENV['RAILS_ENV'] = 'production'
      # call a function to throw an unexpected exception
      assert_equal expected_prod, response.body

      ENV['RAILS_ENV'] = 'development'
      # call said function again
      assert_equal expected_dev, response.body

      ENV['RAILS_ENV'] = 'test'
      assert_raises(StandardError) do
        # call said function a third time
      end
    end

My problem is that to test the function I have to deliberately leave a method and route in my code just for testing the error which seems a bit backwards.

Does anyone have ideas on how to test the error handling, or a way to manage it better?

Aucun commentaire:

Enregistrer un commentaire