2013-03-18 127 views
2

如何避免這個錯誤:Rails的測試/單元測試的輔助方法,NoMethodError:未定義的方法

Error: test_update_location(LocationControllerTest) 
NoMethodError: undefined method `show_previous_version' for test_update_location(LocationControllerTest):LocationControllerTest/usr/local/rvm/gems/ruby-1.9.3-p327/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing' 

我想測試中app/helpers/description_helper.rb定義的helper方法show_previous_version

def show_previous_version(obj) 
    ... 
    return html 
end 

app/helpers/application _helper.rb

module ApplicationHelper 
    ..... 
    require_dependency 'description_helper' 
    ... 
end 

test/functional/location_controller_test.rb

def test_update_location 
    ... 
    loc = Location.find(loc.id) 
    html = show_previous_version(loc) 
    ... 
end 

當我運行測試,我得到:

Error: test_update_location(LocationControllerTest) 
NoMethodError: undefined method `show_previous_version' for test_update_location(LocationControllerTest):LocationControllerTest/usr/local/rvm/gems/ruby-1.9.3-p327/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing' 

回答

-1

助手方法可用來控制器實例,而不是測試本身。要麼直接在測試中包含助手(凌亂),要麼使用控制器(或包含助手的其他對象)來調用該方法。

爲了測試使用控制器,你可以使用@Controller實例變量的ActionController::TestCase內:

class LocationControllerTest < ActionController::TestCase 

    def test_update_location 
    ... 
    loc = Location.find(loc.id) 
    html = @controller.show_previous_version(loc) 
    ... 
    end 
end 
+0

感謝很多有關輔助方法在測試不可用直接的信息。爲了跟進你的建議,你能給出一個簡單的例子,使用控制器 - 在一個測試中 - 調用一個控制器輔助方法? – user2069311 2013-03-19 00:41:28

+0

@ user2069311:爲此更新。 – PinnyM 2013-03-20 14:02:05

+0

默認情況下,控制器實例不能使用輔助方法。 – Speakus 2016-01-16 20:00:04

相關問題