Thursday, March 08, 2007

Rails: Clean up Controller Tests

Traditional Rails Controller tests begin with code very similar to the following code.
require File.dirname(__FILE__) + '/../test_helper'

# Re-raise errors caught by the controller.
class SomeController; def rescue_action(e) raise e end; end

class SomeControllerTest < Test::Unit::TestCase

def setup
@controller = SomeController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
If you use generators you may not notice or care about all this boiler plate code; however, if you generally create your files from scratch you may be interested in the following method that I add to Object (in my test_helper.rb).
class Object
def controller_tests(&block)
full_path_file_name = eval "__FILE__", block.binding
test_name = File.basename(full_path_file_name, ".rb")
controller_name = test_name.chomp("_test")
require controller_name

controller = controller_name.camelize.constantize
controller.class_eval do
def rescue_action(e)
raise e
end
end

test_class = eval "module Functionals; class #{test_name.camelize} < Test::Unit::TestCase; self; end; end"
test_class.class_eval do
define_method :setup do
@controller = controller.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
end
test_class.class_eval &block
end
end
The above code does basically the same thing, but it allows me to define my controller tests in a much cleaner way.
require File.dirname(__FILE__) + '/../test_helper'

controller_tests do
test "should display order number index" do
get :index
...
end

test "should create new order on new" do
get :new
...
end
end
This change also provides the benefit of automatic test class renames when the test file name changes.
Post a Comment