0

I have a health endpoint that will check if the database connection is working:

class HealthController < ApplicationController
  def health
    User.any? # Force a DB connection to see if the database is healthy
    head :ok
  rescue StandardError
    service_unavailable # Defined in ApplicationController
  end
end

And I want to test the 503 status when there is a database connection failure, but I'm not sure how to mock the database failing within RSpec:

require 'swagger_helper'

RSpec.describe 'Health' do
  path '/health' do
    get 'Returns API health status' do
      security []

      response '200', 'API is healthy' do
        run_test!
      end

      response '503', 'API is currently unavailable' do
        # Test setup to mock database failure goes here

        run_test!
      end
    end
  end
end
Athix
  • 37
  • 1
  • 9

1 Answers1

2

If the goal is to test that raising StandardError is rescued into service_unavailable, how about something like this?

# RSwag
response '503', 'API is currently unavailable' do
  before do
    allow(User).to receive(:any?).and_raise StandardError
  end

  run_test!
end
# RSpec
specify 'API is currently unavailable' do
  allow(User).to receive(:any?).and_raise StandardError

  get :health
  
  expect(response).to have_http_status(:service_unavailable)
end
Jake Worth
  • 5,490
  • 1
  • 25
  • 35
  • This works, and can be adapted to use whatever your checking method is, as well as whatever error you're expecting if you use something more specific than StandardError. – Athix Jul 13 '21 at 20:13