我对 Rails 还比较陌生,我正在学习教程。其中一个单元测试(使用rails Minitest)已经指出了这个问题。
这里
test/controllers/carts_controller_test.rb
我断言调用delete后购物车数量减少了1。
test "should destroy cart" do
post line_items_url, params: { product_id: products(:ruby).id }
@cart = Cart.find(session[:cart_id])
assert_difference("Cart.count", -1) do
delete cart_url(@cart)
end
assert_redirected_to store_index_url
end
这映射到我在
controllers/carts/controller.rb
中的破坏行动,如下所示
def destroy
@cart.destroy! if @cart.id == session[:cart_id]
@cart.save
session[:cart_id] = nil
respond_to do |format|
format.html { redirect_to store_index_url,
notice: 'Your cart is currently empty' }
format.json { head :no_content }
end
end
但是,当我运行
bundle exec rails test
时,我得到以下输出:
# Running:
.............F
Failure:
CartsControllerTest#test_should_destroy_cart [...test/controllers/carts_controller_test.rb:46]:
"Cart.count" didn't change by -1.
Expected: 2
Actual: 3
rails test test/controllers/carts_controller_test.rb:42
................
Finished in 0.651308s, 46.0612 runs/s, 98.2638 assertions/s.
30 runs, 64 assertions, 1 failures, 0 errors, 0 skips
当我尝试使用 ERB 模板中呈现的按钮进行删除时
<%= button_to 'Empty Cart', cart, method: :delete,
class: "ml-4 rounded-lg py-1 px-2 text-white bg-green-600" %>
我可以看到以下错误:
ActionController::RoutingError (No route matches [DELETE] "/carts"):
但是,当我通过运行 bundle exec rails routes
进行交叉检查时,我可以确认该路线确实存在:
DELETE /carts/:id(.:format) carts#destroy
我不确定什么在这里不起作用,并且很想得到一些建议。我尝试搜索其他帖子,并与巴德合作,但未能找到有效的解决方案。预先感谢!