如何用 rspec 测试返回的异常?

How to test with rspec a returned exception?

  def show
begin
  @cart = Cart.find(params[:id])
  authorize(@cart)
  @cart_entries = CartEntry.where(:cart_id => @cart.id)
  @products = {}
  @pr_references = {}
  @cart_entries.each do |cart_entry|
    @pr_references[cart_entry.id] = Reference.find(cart_entry.reference_id)
    @products[cart_entry.id] = Product.find(@pr_references[cart_entry.id].product_id)
  end
rescue ActiveRecord::RecordNotFound => e
  respond_to do |format|
    format.json {render json: {'error': e}, status: :not_found}
  end
end

我想测试 Cart.find() 何时找不到购物车,我想测试方法 return 404 HTTP 代码和下面的测试。

 it 'don\'t find cart, should return 404 error status' do
  delete :destroy, params: {id: 123, format: 'json'}

  expect(response).to have_http_status(404)
end

你有一些指示或解决方案吗? 我是 rails 上 ruby 的菜鸟,如果您对我发布的代码有一些建议,我会采纳。

谢谢:)

似乎在执行您的 Cart.find 语句之前,其他一些代码引发了异常。因此,ActiveRecord::RecordNotFound 异常永远不会出现,也不会被 rescue 块捕获。

根据引发的异常,您似乎正在使用 Pundit gem for dealing with authorization. The authorization rules offered by this gem are surely running before your show method starts. Probably this is happening as a consequence of a before_filter 语句,在此控制器或父控制器中。

您需要在应用程序中处理此类错误。在由所有其他控制器继承的基本控制器中使用 rescue_form 语句可能很方便,这样您就不必在每个控制器中处理此类错误。