【问题标题】:how do I test controller method using rspec?如何使用 rspec 测试控制器方法?
【发布时间】:2012-04-20 13:20:06
【问题描述】:

我正在尝试学习 rspec。我似乎无法测试 rails 控制器方法。当我在测试中调用方法时,rspec 只是返回一个未定义的方法错误。这是我的测试示例

it 'should return 99 if large' do
  GamesController.testme(1000).should == 99
end

这是错误:

 Failure/Error: GamesController.testme(1000).should == 99
 NoMethodError:
   undefined method `testme' for GamesController:Class

我在 GamesController 中有一个 testme 方法。我不明白为什么测试代码看不到我的方法。

感谢任何帮助。

【问题讨论】:

    标签: ruby-on-rails testing methods rspec controller


    【解决方案1】:

    我认为正确的做法是这样的:

    describe GamesController do
      it 'should return 99 if large' do
        controller.testme(1000).should == 99
      end
    end
    

    在 Rails 控制器规范中,当您将控制器类放入 describe 时,您可以使用 controller 方法获取实例:P
    显然,如果testme方法是私有的,你还是得使用controller.send :testme

    【讨论】:

    • 非常感谢 - 这在文档中很难找到
    【解决方案2】:

    你尝试测试类方法,但控制器有实例方法

    你需要GamesController.new.testme(1000).should == 99

    甚至GamesController.new.send(:testme, 1000).should == 99,因为我认为这不是操作方法,而是私有或受保护的。

    动作方法测试this way

    【讨论】:

    • 好的。现在我明白了。类方法和实例方法之间的区别是一个让我无法理解的微妙之处。如您所知,我对 ruby​​ 和 rails 还是很陌生。顺便说一句,rspec-rails 文档的链接很好。我不知道该资源。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多