Testing Rails exception handling
I recently found a good article by Neeraj on rescue_action_in_public that saved a good amount of time for me while testing/modifying the rescue behaviour in ApplicationController.
But, testing it was not so trivial. Typicaly, the test.rb will be configuring all test requests to be considered local by through config.action_controller.consider_all_requests_local = true
Now, we need to override this setting only for a few test cases. Also, local_request? must be made to return false.
The former is quite straight forward, done by adding the following line of code to your test case.
@controller.consider_all_requests_local = false
For local_request? to return false, we must set @request.remote_addr to something other than 0.0.0.0 for the test framework to consider the request to be not local.
Rails provides a cleaner way to do this. Calling rescue_action_in_public! will do the job for us. So, putting the pieces together, here is a sample test code to get started
class DummyController < ApplicationController
# Add actions for triggering different error cases (404 - Not Found, 403 - Forbidden, etc.,). Or have a single action and stub it.
# Some dummy action throwing an exception
def some_action
raise "Some error"
end
end
class ErrorHandlingTest < ActionController::TestCase
tests DummyController
def setup
super
@controller.consider_all_requests_local = false
rescue_action_in_public!
end
def test_rescue_exception
get :some_action
# Assert the expected behaviour as follows
# assert_template "#{RAILS_ROOT}/app/views/common/500.html"
end
end
Good post