2009-11-21 21 views
1

我正在寫一個插件,將類方法添加到ActionController::Base,所以在我的功能測試中,我創建了一個簡單的控制器來測試。下面的例子完全被剝奪,基本上什麼都不做。該測試成功完成,直至assert_template,失敗。Rails插件的功能測試,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類?

回答

3

我想通了。首先,缺少的模板是因爲view_path需要在控制器中明確設置下測試:

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

test/fixtures/under_test/index.erb創建一個虛擬的ERB文件。這使我回到response_assertions.rb的零錯誤。好吧,它看起來像我需要包括另一個測試類:

require 'action_view/test_case' 

現在它的工作。

一個附加說明:assert_template使用match來確定成功,所以在這種情況下,assert_template 'ind'將會成功,如assert_template 'x'

1

嘗試用tests UnderTestController替換測試中的設置方法。 Rails會自動爲您設置測試控制器,請求和響應。

+0

謝謝,保羅。這讓我轉向更具體的錯誤:'在視圖路徑中缺少模板under_test/index.erb'這是有道理的。我應該如何存根視圖模板? – 2009-11-23 19:40:14

+0

我認爲「缺少模板」是get:index的結果。但不知道。 – pjb3 2009-11-23 21:45:08