简体   繁体   English

在RSpec请求规范中存根控制器动作

[英]Stubbing controller actions in RSpec request specs

I am writing an API test case for server errors. 我正在为服务器错误编写API测试用例。 I want to stub a controller action to raise an error to simulate the server error (500). 我想对控制器操作进行存根以引发错误以模拟服务器错误(500)。 In the requests spec, the controller variable is not set. 在请求规范中,未设置controller变量。

it "Should return 500 upon server error" do
  controller.stub(:index).and_raise(ArgumentError) 
  get "/users.json"
  response.code.should eq("500")
end

I ended up stubbing the controller method using any_instance . 我最终使用any_instance对控制器方法进行了存根any_instance

it "Should return 500 upon server error" do
  UsersController.any_instance.stub(:index).and_raise(ArgumentError)
  get "/users.json"
  response.code.should eq("500")
  response.body.should have_json_path("error")
end

Note: 注意:

Stubbing controller methods in a request spec doesn't make sense. 在请求规范中存根控制器方法没有任何意义。 But... In this case I am using the request spec suite as the acceptance criteria. 但是...在这种情况下,我使用请求规范套件作为接受标准。 One of the requirement was to ensure, all the error codes and messages match the API design.I was able to induce the server to raise all the HTTP error codes specified in the API design. 要求之一是确保所有错误代码和消息均与API设计匹配。我能够诱使服务器引发API设计中指定的所有HTTP错误代码。 Only edge case was the internal server error(ie 500) . 唯一的例外是internal server error(ie 500) I had no means of inducing the controller to raise this error. 我没有办法诱导控制器引发此错误。 Since, I am testing error reply and since this reply is independent of the location and source of the exception I decided to stub it. 由于我正在测试错误回复,并且由于此回复与异常的位置和来源无关,所以我决定将其存根。

它实际上是一个实例变量: @controller

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM