【问题标题】:Rails test/unit testing helper method, NoMethodError: undefined methodRails 测试/单元测试辅助方法,NoMethodError: undefined method
【发布时间】:2013-03-06 22:25:15
【问题描述】:

如何避免这个错误:

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中定义的辅助方法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'

【问题讨论】:

    标签: ruby-on-rails module helper testunit


    【解决方案1】:

    Helper 方法可用于控制器实例,而不是测试本身。要么直接在测试中包含助手(混乱),要么使用控制器(或包含助手的其他对象)来调用该方法。

    要使用控制器进行测试,您可以在ActionController::TestCase 中使用@controller 实例变量:

    class LocationControllerTest < ActionController::TestCase
    
      def test_update_location
        ...
        loc = Location.find(loc.id)
        html = @controller.show_previous_version(loc)
        ...
      end
    end
    

    【讨论】:

    • 非常感谢有关在测试中直接不可用的辅助方法的信息。为了跟进您的建议,您能否举一个简单的例子来说明使用控制器(在测试中)来调用控制器辅助方法?
    • Helper 方法默认对控制器实例不可用。
    • @Speakus ApplicationHelper 默认包含在 Rails 3 中,所以我不确定你在说什么。
    • @PinnyM 这里关于控制器和助手:stackoverflow.com/a/2388943/751932
    猜你喜欢
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多