nathaniel bibler

Random thoughts, links, and code by Nathaniel Bibler

Functional test for 404s in Rails 2.x

The Ruby on Rails version 2.x ActionController::TestCase thankfully abstracts a lot of the setup of your functional tests. There is a hidden issue, however, a problem that lingers for fully testing your controllers. How do you test for those automatically generated FAIL pages (i.e. 404, 500, 403, etc.)?

Hidden in the TestCase code, there is an answer. By default, all @request calls are made using a localhost-like IP, namely 0.0.0.0. TestCase overrides the rescue_action_without_handler and checks for that specific IP. If 0.0.0.0 is found, it will just forward the raised error to you, bypassing those pretty error pages. So, here’s the secret: Change your @request.remote_addr to anything other than ‘0.0.0.0’.

class MyController < ApplicationController
  def show
    raise ActiveRecord::RecordNotFound
  end
end


class MyControllerTest < ActionController::TestCase
  def test_show_rescues_with_404
    @request.remote_addr = '1.2.3.4'
    get :show, :id => 1
    assert_response :not_found # PASS!
  end
end
Also, be sure you remove any lines in your functional test that look similar to:
class MyController; def rescue_action(e) raise e end; end