我在 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 错误。那么为什么我会得到一个呢?提前致谢!
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. 修补 CanCan像这样 https://github.com/ryanb/cancan/issues/43.
我不喜欢修补途径,所以我选择了选项 1。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)