1

我正在编写一个向 中添加类方法的插件ActionController::Base,因此在我的功能测试中,我正在创建一个简单的控制器来进行测试。下面的示例完全被剥离,基本上什么都不做。测试一直成功,直到assert_template失败。

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

以下是运行上述文件的结果:

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

我的问题:我缺少什么让assert_template工作?我需要正确的库吗?扩展正确的 TestCase 类?

4

2 回答 2

3

我想到了。首先,缺少模板是因为view_path需要在被测控制器中显式设置:

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

我在test/fixtures/under_test/index.erb. 这让我回到了response_assertions.rb. 好吧,看来我需要包含另一个测试类:

require 'action_view/test_case'

现在它起作用了。

另一个注意事项:assert_template用于match确定成功,因此在这种情况下,assert_template 'ind'会成功,就像assert_template 'x'.

于 2009-11-27T17:27:35.280 回答
1

尝试用 just 替换测试中的 setup 方法tests UnderTestController。Rails 会自动为您设置测试控制器、请求和响应。

于 2009-11-23T18:51:25.940 回答