使用find_by_id时得到RSpec中不存在的记录RecordNotFound上调 [英] RecordNotFound raised when using find_by_id to get non-existent record in RSpec
问题描述
我已经写了这个天赋在products_controller_spec.rb,这是为了测试重定向时破坏被称为一个不存在的记录:
I've written this spec in products_controller_spec.rb, that is intended to test a redirect when destroy is called on a non-existent record:
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控制器动作:
Here's the controller action in 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
现在,我没想到的规范通过第一次,但我不明白为什么它这个失败的:
Now, I didn't expect the spec to pass first time but I don't understand why it's failing with this:
Failure/Error: delete :destroy, {:id => 9999}
ActiveRecord::RecordNotFound:
Couldn't find Product with id=9999
我下的是IM pression的#find_by_id不会对一个不存在的记录返回RecordNotFound错误。那么,为什么我得到一个?在此先感谢!
I was under the impression that #find_by_id would not return RecordNotFound error on a non-existent record. So why am I getting one? Thanks in advance!
推荐答案
该RecordNotFound错误被抛出惨惨。这不是救市,能够从控制器动作(presumably发生的操作运行前)之内。有解决这两种方式 -
The RecordNotFound error was being thrown by CanCan. It's not rescue-able from within the controller action (presumably it occurs before the action runs). There were two ways of resolving it -
-
更改规格为:
Changing the spec to:
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。
I didn't fancy the patching route, so I went for option 1.
这篇关于使用find_by_id时得到RSpec中不存在的记录RecordNotFound上调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!