如何获得 .save 失败的 rspec 覆盖率

How to get rspec coverage for the failure of .save

在我的控制器中,我有以下代码:

def create
    @post = Post.new(post_params)
    if @post.save
      flash[:notice] = "#{@post.title} was successfully created."
      redirect_to post_path
    else
      flash[:alert] = @post.errors.full_messages
      render :new
    end
end

我已经设法编写 rspec 代码来涵盖功能规范中的真实陈述,但是我正在为错误陈述而苦苦挣扎。到目前为止,这是我想出的 rspec 来解决我的问题(放在 posts_controller_spec.rb 中):

it 'should return false and render the new template' do 

    allow_any_instance_of(Post).to receive(:valid?).and_return(false)

    expect(response).to render_template(:new)

end

不幸的是,我遇到了以下错误:

Failures:

  1) PostsController create should return 
     Failure/Error: expect(response).to render_template(:new)
       expecting <"new"> but rendering with <[]>

我试过查看有关 Whosebug 的其他问题以及其他在线建议,但似乎无法弄明白。

任何帮助将不胜感激:)

在你的测试中,你从不调用控制器。

it 'renders the new template' do 
  allow_any_instance_of(Post).to receive(:valid?).and_return(false)

  post :create, params: {...}

  expect(response).to render_template(:new)
end

receive(:save).and_return(false).

会更直接

不过,这里不需要模拟。发送无效的 Post 个参数。

context 'when the Post params are invalid' do
  let(:params) do
    {
      post: { something: "invalid" }
    }
  end

  it 'does not make a Post, renders the new template, and flashes an error' do
    expect {
      post :create, params: params
    }.to change {
      Post.count
    }.by(0)

    expect(response).to render_template(:new)
    expect(flash[:alert]).not_to be_empty
  end
end