Rspec 导轨:找不到带有 id 的帖子/无路由匹配项



我正在用rspec测试create的动作,它给了我:

ActiveRecord:: RecordNotFound:找不到"id"=:post_id的邮件

不确定,为什么会发生这种情况,有什么建议吗?

规范:

describe CommentsController  do
  it "#create" do
    post1 = create(:post)
    post :create, comment: attributes_for(:comment, post_id: post1.id)
    p Comment.count
  end
end

create action:

 def create
    @comment = @post.comments.build(comment_params)
    @comment.user_id = current_user.id
    respond_to do |format|
      if @comment.save
        format.json { render json: @comment }
      end
    end
  end
行动前

:

  before_action :authenticate_user!
  before_action :find_post, only: [:index, :create, :destroy]

路线:

  post_comments GET /posts/:post_id/comments(.:format)        comments#index
                POST   /posts/:post_id/comments(.:format)     comments#create
  post_comment  DELETE /posts/:post_id/comments/:id(.:format) comments#destroy

试试这个:

describe CommentsController  do
  it "#create" do
    post1 = create(:post)
    post :create, { post_id: post1.id, comment: attributes_for(:comment, post_id: post1.id) }
    p Comment.count
  end
end

我猜问题是你没有在参数中发送post_id

问题是你没有正确通过post_id。像这样传递并调试find_post方法,参数是如何出现的。

describe CommentsController  do
  it "#create" do
    post1 = create(:post)
    post :create, { post_id: post1.id, comment: { comment_attributes_here } }
    p Comment.count
  end
end

相关内容

  • 没有找到相关文章

最新更新