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.

3 comments:

  1. Nice tip. If you use test/spec and test_spec_on_rails you get this for free with "use_controller ControllerName".

    ReplyDelete
  2. eval "__FILE__", block.binding

    Yum!

    ReplyDelete
  3. We keep getting this error:

    ./test/functional/text_controller_test.rb:5:in `test': unknown command ?i (ArgumentError)
    from ./test/functional/text_controller_test.rb:5
    from ./test/functional/../test_helper.rb:56:in `class_eval'
    from ./test/functional/../test_helper.rb:56:in `controller_tests'
    from ./test/functional/text_controller_test.rb:4

    Can't figure out why, maybe you could help? It's Rails 2.1.2

    ReplyDelete

Note: Only a member of this blog may post a comment.