@rubys
Following through the book but using Rails 7.1.2.
When trying to run the test on page 118 I get -
`
Error:
ProductsControllerTest#test_can't_delete_product_in_cart:
ActiveRecord::RecordNotDestroyed: Failed to destroy Product with id=298486374
app/controllers/products_controller.rb:52:in `destroy'
test/controllers/products_controller_test.rb:58:in `block (2 levels) in <class:ProductsControllerTest>'
test/controllers/products_controller_test.rb:57:in `block in <class:ProductsControllerTest>'
bin/rails test test/controllers/products_controller_test.rb:56
Finished in 0.706042s, 39.6577 runs/s, 86.3971 assertions/s.
28 runs, 61 assertions, 0 failures, 1 errors, 0 skips
Is this because of the different Rails version, or is this test not meant to pass?
1 Like
Got the same error also using Rails 7.1.2 with Ruby 3.3.0. Patched it using rescue, but would like to know the correct way to handle this.
test “can’t delete product in cart” do
assert_difference(“Product.count”, 0) do
delete product_url(products(:two))
rescue ActiveRecord::RecordNotDestroyed
assert true
end
end
@rubys
I decided to write my test like this
test "can't delete product in cart" do
assert_raises(ActiveRecord::RecordNotDestroyed) do
delete product_url(products(:two))
end
assert Product.exists?(products(:two).id)
end
If you look in your scaffold generated ProductsController, you’ll notice that the destroy action now calls the strict @product.destroy!
method. This change was introduced here: Use safer 'destroy!' in controller scaffolds · rails/rails@e87608e · GitHub