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