【问题标题】:Route Generation error for :create action in Minitest路由生成错误:在 Minitest 中创建操作
【发布时间】:2015-06-09 23:07:18
【问题描述】:

我目前正在为我的所有控制器编写功能测试。对于每一个,我都无法让创建操作起作用。运行 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

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

【问题讨论】:

    标签: ruby-on-rails routes params minitest


    【解决方案1】:

    我认为您也需要将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 的子项:

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

    Rails 的路由错误可能非常模糊且无济于事。 90% 的错误归结为这种情况的某种变体:不匹配或错误命名的 ID、nil 值等。

    【讨论】:

    • 你是对的!结果我不得不将 :product_id 移到哈希之外。
    猜你喜欢
    • 2016-08-06
    • 2014-08-22
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2020-03-27
    • 2018-04-13
    • 1970-01-01
    相关资源
    最近更新 更多