由于数据库错误,RSpec 模拟健康端点失败

问题描述

我有一个健康端点来检查数据库连接是否正常工作:

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

我想在数据库连接失败时测试 503 状态,但我不确定如何在 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

解决方法

如果目标是测试提高 StandardError 是否被拯救为 service_unavailable,这样的事情怎么样?

# 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...