RSpec:我如何正确模拟#destroy失败

时间:2016-03-23 12:23:24

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

我很难在我的控制器中模拟destroy方法的失败。

我的控制器的破坏看起来像这样:

def destroy
   project = Project.find(params[:id])
   project.destroy

  if project.destroyed?
    render json: {
      project: nil,
      message: "The project was successfully deleted"
    }
  else
    render json: {
      message: "Could not delete project",
    }, status: :unprocessable_entity
  end
end

我试图在我的测试中在else块中渲染json,但是无法完成它。到目前为止,特定测试看起来像这样:

describe "DELETE #destroy" do

 let!(:project) { create(:project, :open) }

  context "when invalid" do

   it "returns an error if the project was not deleted" do
     expect(Project).to receive(:find).with(project.id.to_s).and_call_original
     expect(project).to receive(:destroy).and_return(false)
     delete :destroy, id: project
   end

 end
end

测试要么返回“快乐路径”。或者给我错误。目前:

 Failure/Error: expect(project).to receive(:destroy).and_return(false)

       (#<Project:0x007f87cf5d46a8>).destroy(*(any args))
           expected: 1 time with any arguments
           received: 0 times with any arguments

如果有人能指出我正确的方向,并解释我如何模拟422,我将非常感激!

1 个答案:

答案 0 :(得分:0)

你想在开始时允许,而不是期望。期待是断言部分。

it "returns an error if the project was not deleted" do
  allow(Project).to receive(:find).with(project.id.to_s).and_call_original
  allow(project).to receive(:destroy).and_return(false)

  delete :destroy, id: project

  expect(Project).to have_received(:find)
  expect(project).to have_received(:destroy)
end

我假设你是<= p>

allow(Project).to receive(:find).with(project.id.to_s).and_call_original

但我之前从未见过,我通常会这样做

allow(Project).to receive(:find).with(project.id.to_s).and_return(project)