0

I have a simple controller action which is used for checking that the app is running.

def check(id=1)
  Car.find(id)
  render nothing: true, status: 200
rescue
  render nothing: true, status: 500
end

How do I test the exception. Below is the test for the happy path.

RSpec.describe HealthController do

  describe "GET #check" do
    it "returns 200" do
    expect(response).to have_http_status(200)
  end
end
margo
  • 2,927
  • 1
  • 14
  • 31
  • Check for a status of 500? I don't see the issue. However a failed find will already raise a 404, which is more semantically meaningful. – Dave Newton Feb 02 '16 at 18:04
  • I appreciate your point. The purpose of the action is to check that the app and the database are not down. I can ping the controller action regularly and automatically get notified if there are issues with the app. Hence why I capture the exception with a 500 status. – margo Feb 02 '16 at 18:17
  • Unfortunately you capture *every* exception, not just "DB is down" exceptions. If the *app* is down you don't really need to capture an exception... from the app that's down. It's down. Your request will time out. – Dave Newton Feb 02 '16 at 18:26
  • Thats fine, thats what I want. I realise you may not see the point of what I'm doing but you haven't really addressed the question. – margo Feb 02 '16 at 18:39
  • Yes, I did. You check for the other status, with the caveat that Rails may raise and render its own exception before your `rescue` block can get executed. Is your question actually how to mock `find`? Same as anything else, and it depends what mocking library you're using, e.g., `Car.stubs(:find).raises(WhateveExceptionYouWant)` with Mocha. – Dave Newton Feb 02 '16 at 18:41
  • Thx. I ended up using a before block with allow(Preorder).to receive(:first) {Exception} then get :check and expect(response).to have http_status(200). (sorry for the pseudo code, may help someone else). Also changed my method to just get first record. If you want to create an answer, I'm happy to 'accept' it. – margo Feb 02 '16 at 19:10
  • The exceptional case shouldn't get a 200 back, though, no? If the purpose is to ensure the controller returns an HTTP 500 if the DB is down? – Dave Newton Feb 02 '16 at 19:12
  • Oops, copied in the wrong code - alllow(Car).to receive(:first).and_raise(Exception); get :check; expect(response).to have_http_status(500). Thx for your comments – margo Feb 02 '16 at 21:31

0 Answers0