简体   繁体   中英

Stubbing controller actions in RSpec request specs

I am writing an API test case for server errors. I want to stub a controller action to raise an error to simulate the server error (500). In the requests spec, the controller variable is not set.

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 .

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. Only edge case was the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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