如何使用 RSpec 测试 Mongo 连接错误处理

How to test Mongo connection error handling with RSpec

我需要解决我的应用程序测试。 Coverage 抱怨一行代码评估与 MongoDB (rescue Mongo::Error::NoServerAvailable => _e) 的连接并呈现错误。

你认为我应该用什么来测试这个:

def index
  render json: Complex.all.to_json
rescue Mongo::Error::NoServerAvailable => _e
  render json: { error_description: 'no database available' }, status: 503
end

我正在尝试用类似的东西进行测试:

it 'should return an exception' do
  get :index
  expect(response).to raise_exception
end

我发现我应该使用

.and_raise(IOError)

但是我不知道用在哪里才能让它掉线。 实际上,如果我停止 Mongo,我可以让它落入异常,但那不是我的想法。

感谢您的宝贵时间。

要到达处理异常的代码行,存根 Complex.all.to_json 以引发异常。由于 Complex.all.json 是链式的,因此需要一些额外的努力来存根它。此外,由于异常已被处理,您无法测试它是否已引发;相反,测试处理它的结果。

it 'should handle the exception' do
  all = double
  allow(all).to receive(:to_json).and_raise Mongo::Error::NoServerAvailable
  allow(Complex).to receive(:all).and_return all
  get :index
  expect(response.status).to eq(503)
  expect(response.body).to include('no database available')
  # you could test the JSON more thoroughly, but you get the idea
end

您可以使用 receive_message_chain 以更少的代码存根 Complex.all.to_json。我使用了长版本,因为它更容易理解发生了什么。