mrvncaragay
mrvncaragay

Reputation: 1260

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

Upvotes: 0

Views: 965

Answers (2)

Narasimha Reddy - Geeker
Narasimha Reddy - Geeker

Reputation: 3860

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

Upvotes: 0

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

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.

Upvotes: 1

Related Questions