简体   繁体   English

Rspec Rails:找不到ID为ID /没有路线匹配的帖子

[英]Rspec Rails: getting couldn't find Post with id / No Route matches

I'm testing create action with rspec, It's giving me: 我正在用rspec测试create action,它给了我:

ActiveRecord::RecordNotFound: Couldn't find Post with 'id'=:post_id ActiveRecord :: RecordNotFound:找不到带有'id'=:post_id的帖子

not sure, why this is happening, any suggestion? 不知道为什么会这样,有什么建议吗?

spec: 规格:

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: 行动前:

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

Routes: 路线:

  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

Try this: 尝试这个:

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

I guess the problem is you are not sending post_id in the params. 我想问题是您没有在参数中发送post_id

The problem is you are not passing post_id properly. 问题是您没有正确传递post_id pass like this and debug in find_post method, how params coming there. 这样传递并在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM