【问题标题】:RecordNotFound raised when using find_by_id to get non-existent record in RSpec使用 find_by_id 获取 RSpec 中不存在的记录时引发 RecordNotFound
【发布时间】:2012-04-17 09:55:59
【问题描述】:

我在 products_controller_spec.rb 中编写了这个规范,目的是在对不存在的记录调用 destroy 时测试重定向:

it "deleting a non-existent product should redirect to the user's profile page with a flash error" do           
    delete :destroy, {:id => 9999}
    response.should redirect_to "/profile"
    flash[:error].should == I18n.t(:slideshow_was_not_deleted)
end

这是 products_controller.rb 中的控制器操作:

def destroy
  product = Product.find_by_id(params[:id])
  redirect_to "profile" if !product
  if product.destroy
    flash[:notice] = t(:slideshow_was_deleted)
    if current_user.admin? and product.user != current_user
      redirect_to :products, :notice => t(:slideshow_was_deleted)
    else
      redirect_to "/profile"
    end
  else
    if current_user.admin?
      redirect_to :products, :error => t(:slideshow_was_not_deleted)
    else
      redirect_to "/profile"
    end
  end
end

现在,我没想到规范会第一次通过,但我不明白为什么它会失败:

Failure/Error: delete :destroy, {:id => 9999}
 ActiveRecord::RecordNotFound:
   Couldn't find Product with id=9999

我的印象是#find_by_id 不会在不存在的记录上返回 RecordNotFound 错误。那我为什么要买一个?提前致谢!

【问题讨论】:

  • 您使用哪个版本的 Rails?这个find_by_id 在 Rails 3.2.3 中可以正常工作。 (返回 nil 而不是引发 RecordNotFound)
  • 3.2.2 在这里。我应该添加 find_by_id 在浏览器中工作。我只在规范结果中得到 RecordNotFound。
  • - 实际上,只是在浏览器中尝试对不存在的记录执行显示操作并得到 RecordNotFound。当我在控制器中注释掉 CanCan 身份验证时离开了。看起来 CanCan 正在扔 RnF
  • 我目前没有足够的代表来回答这个问题,但简而言之,CanCan 在动作运行之前抛出了错误。它可以被修补,或者更简单地说,可以重写规范以期望 RnF。稍后我会将其作为正式答案发布。

标签: ruby-on-rails activerecord rspec cancan


【解决方案1】:

CanCan 引发了 RecordNotFound 错误。它不能从控制器动作中救援(大概它发生在动作运行之前)。有两种解决方法-

  1. 将规范更改为:

    it "deleting a non-existent product should result in a RecordNotFound Error" do         
      product_id = 9999
      expect { delete :destroy, {:id => product_id}}.to raise_error ActiveRecord::RecordNotFound
    end
    

或者, 2. 修补CanCanlike this.

我不喜欢补丁路线,所以我选择了选项 1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 2020-07-01
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多