【问题标题】:Comments conrtoller test ActionController::UrlGenerationError评论 conrtoller 测试 ActionController::UrlGenerationError
【发布时间】:2015-01-13 09:19:53
【问题描述】:

运行 rake test 时,出现此错误:ActionController::UrlGenerationError

我的路线.rb

  resources :posts do
    resources :comments, only: [ :create,:destroy ]
  end

cmets.yml

one:
  body: "comment one"
  user: users(:paul)
  post: posts(:one)

cmets_controller_test.rb

  def setup
    @comment = comments(:one)
  end

  test "should redierct create when not signed in" do 
    assert_no_difference "Comment.count" do
      post :create, comment: @comment.attributes
    end
    assert_redirected_to signin_url
  end

cmets_controller.rb

  def create
    @comment = @post.comments.build(comment_params.merge(user: current_user))
    @comment.save
    @comments = @post.comments.all
    respond_to do |format|
      format.html { redirect_to @post }
      format.js 
    end
  end

完整的错误信息

错误["test_should_redierct_create_when_not_signed_in", 评论控制器测试,0.444971] test_should_redierct_create_when_not_signed_in#CommentsControllerTest (0.44s) ActionController::UrlGenerationError:
ActionController::UrlGenerationError:没有路由匹配 {:action=>"create", :comment=>{"id"=>"980190962", "body"=>"comment one", "post_id"=>"849819558", "user_id"=>"293831562", "created_at"=>"2014-11-16 10:45:03 UTC", "updated_at"=>"2014-11-16 10:45:03 UTC"}, :controller=>"cmets"}

我应该如何修改我的测试代码?

【问题讨论】:

  • 不确定,但请尝试将 cmets_controller 中的 redirect_to @post 替换为 redirect_to [@post,@comments]
  • 它不起作用,我认为post :create, comment: @comment.attributes可能是错误的主要原因。

标签: ruby-on-rails ruby unit-testing


【解决方案1】:

我认为您需要明确告知父记录 id (post_id),以便 rails 可以形成正确的发布路径,请尝试以下操作:

post :create, comment: @comment.attributes, post_id: @comment.post_id

【讨论】:

  • 谢谢,它有效!但是我还是有疑问,为什么@comment.attributes不包含post_id
  • 它确实包含它(如在错误消息哈希输出中)但是当要求形成一个发布请求时,Rails 无法计算正确的路径 >> post_cmets_url 没有传递 post_id 作为参数。尝试阅读有关嵌套资源路由的更多信息。希望对您有所帮助!
  • 知道了,谢谢你的解释。
猜你喜欢
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
  • 2015-10-26
  • 1970-01-01
相关资源
最近更新 更多