路由生成错误:在 Minitest 中创建操作

Route Generation error for :create action in Minitest

我目前正在为我的所有控制器编写功能测试。对于每一个,我都无法使创建操作起作用。当我 运行 rake 测试时,我不断收到以下错误:

 ActionController::UrlGenerationError: No route matches {:action=>"create", :comment=>{:content=>"I'm a comment.", :product_id=>"685617403"}, :controller=>comments}

这是我要测试的操作:

class CommentsController < ApplicationController
  before_action :authenticate_user!
  def create
    @product =Product.find(params[:product_id])
    @comment=Comment.create(params[:comment].permit(:content))
    @comment.user_id= current_user.id
    @comment.product_id= @product.id
    if @comment.save
      redirect_to product_path(@product)
    else
      render 'new'
    end
  end
end

这是路线:

POST     /products/:product_id/comments(.:format)          comments#create

以下是我的测试:

    def setup
    @user=users(:chris)
    @product=products(:banana)
  end

  test "should redirect destroy action if not signed in" do
    post :create, comment: { content: "I'm a comment.", product_id:@product.id}
    assert_redirected_to new_user_session_path
  end

我不知道我做错了什么。我相当确定我传递了正确的参数 in.I 我也尝试过使用和不使用 user_id: 参数,但它仍然会抛出相同的错误。它在应用程序上运行良好,我在发出请求时在 Web 控制台中调用了参数,它与我传递的内容相匹配。我唯一缺少的是 :id 但我假设在测试中创建评论时会分配它。此外,没有唯一的约束会阻止创建的评论有效。我的关联已经到位,当它在应用程序上运行时,它会使用 user_id 和 product_id 保存到数据库中。我错过了什么?

我认为您也需要将 product_id 作为其自己的一级参数,以便路由正确匹配。所以试试这个:

post :create, product_id: @product.id, comment: { content: "I'm a comment.", product_id: @product.id }

请注意,在您的控制器操作中,您已经直接引用 params[:product_id],而不是引用 params[:comment][:product_id]。然后,为了减少重复,您可以在控制器中创建评论作为该产品的子项:

@comment = @product.comments.create(other params...)

Rails' 路由错误可能非常模糊且毫无帮助。 90% 的错误归结为这种情况的一些变体:不匹配或错误命名的 ID、零值等。