A Journey On Rails

Testing Rails exception handling

Posted in Rails, Testing by Vikram Venkatesan on December 23, 2009

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 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"

class ErrorHandlingTest < ActionController::TestCase
  tests DummyController

  def setup
    @controller.consider_all_requests_local = false

  def test_rescue_exception
    get :some_action
    # Assert the expected behaviour as follows
    #   assert_template "#{RAILS_ROOT}/app/views/common/500.html"

One Response

Subscribe to comments with RSS.

  1. Arun Kumar said, on January 27, 2010 at 8:14 am

    Good post 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: