views:

239

answers:

2

I'm writing a plugin that adds a class method to ActionController::Base, so in my functional test I am creating a simple controller to test against. The example below is totally stripped down to basically do nothing. The test succeeds all the way up to assert_template, which fails.

require 'rubygems'
require 'test/unit'
require 'active_support'
require 'active_support/test_case'
require 'action_controller'
require 'action_controller/test_process'

class UnderTestController < ActionController::Base
  def index; end
end
ActionController::Routing::Routes.draw {|map| map.resources :under_test }

class MyPluginTest < ActionController::TestCase
  def setup
    @controller = UnderTestController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
  end

  test "should render the correct template" do
    get :index
    assert_template :index  # everything works except this assert
  end
end

Here are the results from running the above file:

Loaded suite /Users/jjulian/sandbox/vendor/plugins/my_plugin/test/my_plugin_test
Started
E 
Finished in 0.014567 seconds.

  1) Error:
test_should_render_the_correct_template(MyPluginTest):
NoMethodError: undefined method `[]' for nil:NilClass
method assert_template in response_assertions.rb at line 103
method clean_backtrace in test_case.rb at line 114
method assert_template in response_assertions.rb at line 100
method test_should_render_the_correct_template in so_test.rb at line 22
method __send__ in setup_and_teardown.rb at line 62
method run in setup_and_teardown.rb at line 62

1 tests, 0 assertions, 0 failures, 1 errors

My questions: what am I missing to allow assert_template to work? Am I requiring the correct libraries? Extending the correct TestCase class?

A: 

Try replacing the setup method in the test with just tests UnderTestController. Rails takes care of setting up the test controller, request and response for you automatically.

pjb3
Thanks, Paul. That moves me forward to a more concrete error: `Missing template under_test/index.erb in view path` This makes sense. How should I stub the view template?
Jonathan Julian
I think "missing template" is to be expected as a result of get :index. Not sure though.
pjb3
+1  A: 

I figured it out. First, the missing template is because the view_path needs to be explicitly set in the controller under test:

before_filter {|c| c.prepend_view_path(File.join(File.dirname(__FILE__), 'fixtures')) }

I created a dummy erb file in test/fixtures/under_test/index.erb. That brings me back to the nil error in response_assertions.rb. Well, it looks like I need to include another test class:

require 'action_view/test_case'

Now it works.

One additional note: assert_template uses match to determine success, so in this case, assert_template 'ind' would succeed, as would assert_template 'x'.

Jonathan Julian