[英]how do I test controller method using rspec?
I'm trying to learn rspec. I can't seem to test a rails controller method.我正在尝试学习 rspec。我似乎无法测试 Rails controller 方法。 When I call the method in the test, rspec just returns an undefined method error.当我在测试中调用该方法时,rspec 只是返回一个未定义的方法错误。 Here is my test example这是我的测试示例
it 'should return 99 if large' do
GamesController.testme(1000).should == 99
end
and here is the error:这是错误:
Failure/Error: GamesController.testme(1000).should == 99
NoMethodError:
undefined method `testme' for GamesController:Class
I do have a testme method in the GamesController.我在 GamesController 中确实有一个 testme 方法。 I don't understand why the test code cannot see my methods.我不明白为什么测试代码看不到我的方法。
Any help is appreciated.任何帮助表示赞赏。
I think the correct way is this:我认为正确的方法是这样的:
describe GamesController do
it 'should return 99 if large' do
controller.testme(1000).should == 99
end
end
In a rails controller spec, when you put the controller class in describe
, you can use controller
method to get an instance:P在 rails controller 规范中,当您将 controller class 放入describe
时,您可以使用controller
方法获取实例:P
Obviously, if testme
method is private, you still have to use controller.send:testme
显然,如果testme
方法是私有的,你仍然必须使用controller.send:testme
You try to test class method, but controller has instance method你尝试测试 class 方法,但是 controller 有实例方法
You need GamesController.new.testme(1000).should == 99
你需要GamesController.new.testme(1000).should == 99
Or even GamesController.new.send(:testme, 1000).should == 99
, because, as I think, this is not action method, but private or protected.甚至GamesController.new.send(:testme, 1000).should == 99
,因为我认为这不是操作方法,而是私有的或受保护的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.