简体   繁体   中英

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

I'm testing create action with rspec, It's giving me:

ActiveRecord::RecordNotFound: Couldn't find Post with '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.

The problem is you are not passing post_id properly. pass like this and debug in find_post method, how params coming there.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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