Rspec Rails:找不到具有id / No Route匹配的帖子

时间:2016-08-10 06:41:56

标签: ruby-on-rails ruby ruby-on-rails-4 rspec-rails

我正在使用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

制作行动:

 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

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

问题是你没有正确传递post_id。像这样传递并在find_post方法中调试,如何使用params。

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