【问题标题】:Rspec Rails: getting couldn't find Post with id / No Route matchesRspec Rails:无法找到带有 id / 无路由匹配的帖子
【发布时间】:2016-08-10 06:41:55
【问题描述】:

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

【问题讨论】:

  • 请分享一些堆栈跟踪和您的find_post 方法。

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


【解决方案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

【讨论】:

  • 测试通过,但Comment.count0 应该是1
  • 评论一定有一些验证失败。
  • 在你的控制器中用if @comment.save!替换这个if @comment.save,你会看到。
  • 另一件事,测试将通过,因为您没有检查 it 块内的任何内容。你应该在post :create, ... 声明之后做expect(Comment.count).to eq 1
  • comment: attributes_for(:comment, post_id: post1.id) 这里我认为不需要再次通过post_id
【解决方案2】:

问题是您没有正确传递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

【讨论】:

  • 和我的回答一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
  • 2017-06-06
  • 1970-01-01
相关资源
最近更新 更多