简体   繁体   English

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

[英]RSpec: how do I correctly simulate #destroy failure

I'm having a very hard time simulating the failure of a destroy method in my controller. 我很难在控制器中模拟destroy方法的失败。

My controller's destroy looks like this: 我的控制器的销毁看起来像这样:

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

I'm trying to render the json in the else block in my test, but can't get it done. 我正在尝试在测试中的else块中呈现json,但无法完成。 So far the particular test looks like this: 到目前为止,特定测试如下所示:

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

The test either returns the 'happy path' or gives me errors. 测试要么返回“幸福的道路”,要么给我错误。 At the moment: 在这一刻:

 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

If anyone could point me in the right direction, and explain how I can simulate a 422, I'd be very grateful! 如果有人能指出正确的方向并说明如何模拟422,我将不胜感激!

You want allow at the start, not expect. 您希望一开始就允许,而不是期望。 Expect is the assertion part. 期望是断言的一部分。

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

I'm assuming you're right with 我假设你是对的

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

but I've never seen that before, I would normally do 但我从未见过,我通常会

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM