如何使用rspec测试控制器方法?

时间:2012-04-07 04:15:56

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

我正在努力学习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方法。我不明白为什么测试代码看不到我的方法。

感谢任何帮助。

2 个答案:

答案 0 :(得分:30)

我认为正确的方法是:

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

答案 1 :(得分:4)

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

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

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

对行动方法进行了测试this way

相关问题