6

我在 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 错误。那我为什么要买一个?提前致谢!

4

1 回答 1

16

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.像这样修补CanCan 。

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

于 2012-04-17T21:09:49.177 回答