RecordNotFound is raised when using find_by_id to get a nonexistent record in RSpec

I wrote this specification in products_controller_spec.rb, which is designed to test redirection when destroy is called on a nonexistent entry:

it "deleting a non-existent product should redirect to the user 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 

Here is 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 did not expect the specification to go through for the first time, but I do not understand why this fails:

 Failure/Error: delete :destroy, {:id => 9999} ActiveRecord::RecordNotFound: Couldn't find Product with id=9999 

I had the impression that #find_by_id would not return a RecordNotFound error for a non-existent record. So why am I getting it? Thanks in advance!

+6
source share
1 answer

Error RecordNotFound is triggered by CanCan. This does not save the controller from the action (apparently, this happens before the action is performed). There were two ways to solve it -

  • Specification change for:

     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 

or, 2. CanCan patches like this .

I did not like the fix route, so I went for option 1.

+16
source

Source: https://habr.com/ru/post/913407/


All Articles