Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 使用find_by_id获取RSpec中不存在的记录时引发RecordNotFound_Ruby On Rails_Activerecord_Rspec_Cancan - Fatal编程技术网

Ruby on rails 使用find_by_id获取RSpec中不存在的记录时引发RecordNotFound

Ruby on rails 使用find_by_id获取RSpec中不存在的记录时引发RecordNotFound,ruby-on-rails,activerecord,rspec,cancan,Ruby On Rails,Activerecord,Rspec,Cancan,我在products\u controller\u 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

我在products\u controller\u 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

我的印象是,“按id查找”不会在不存在的记录上返回RecordNotFound错误。那为什么我会得到一个呢?提前谢谢

CanCan正在抛出RecordNotFound错误。无法从控制器操作中进行营救(可能发生在操作运行之前)。有两种解决方法-

  • 将等级库更改为:

    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.修补坎坎


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

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