【问题标题】:How to test with rspec a returned exception?如何使用 rspec 测试返回的异常?
【发布时间】:2019-07-17 08:17:27
【问题描述】:
  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() 何时找不到购物车,我想测试该方法返回 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

你有一些迹象或解决方案吗? 我是 ruby​​ on rails 的菜鸟,如果您对我发布的代码有一些提示,我会接受。

谢谢你:)

【问题讨论】:

  • 你当前测试的输出是什么?
  • 输出为 Pundit::AuthorizationNotPerformedError: Api::V1::CartsController 0) Api::V1::CartsController GET #show 找不到购物车,返回 404 错误状态 Failure/Error: get :显示,参数:{id:123,格式:'json'}

标签: ruby-on-rails unit-testing rspec


【解决方案1】:

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

根据引发的异常,您似乎正在使用Pundit gem 处理授权。这个 gem 提供的授权规则肯定会在您的 show 方法开始之前运行。这可能是由于 before_filter 语句的结果,无论是在此控制器中还是在父控制器中。

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

【讨论】:

  • 我将 rescue_from 我的异常放入 ApplicationController 中,现在可以使用了。感谢您的帮助
猜你喜欢
  • 2016-03-20
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 2019-03-22
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多