Rspec:如何验证记录是否已被删除?

tlo*_*art 25 ruby unit-testing rspec ruby-on-rails-5

我创建了一个简单的 Rspec 测试来验证创建的模型是否已被删除。但是,测试失败,因为模型仍然存在。任何人都可以提供有关如何确定记录是否确实被删除的任何帮助吗?

RSpec.describe Person, type: :model do

let(:person) {
    Person.create(
      name: "Adam",
      serial_number: "1"
    )
  }
  
  it "destroys associated relationships when person destroyed" do
  person.destroy
  expect(person).to be_empty()
  end
end
Run Code Online (Sandbox Code Playgroud)

spi*_*ann 38

你有两个选择。你可以测试一下:

\n
    \n
  1. 一条记录已从数据库中删除

    \n
    it "removes a record from the database" do\n  expect { person.destroy }.to change { Person.count }.by(-1)\nend\n
    Run Code Online (Sandbox Code Playgroud)\n

    但这并没有告诉您哪条记录被删除。

    \n
  2. \n
  3. 或者数据库中不再存在确切的记录

    \n
    it "removes the record from the database" do\n  person.destroy\n  expect {\xc2\xa0person.reload }.to raise_error(ActiveRecord::RecordNotFound)\nend\n
    Run Code Online (Sandbox Code Playgroud)\n

    或者

    \n
    it "removes the record from the database" do\n  person.destroy\n  expect(Person.exists?(person.id)).to be false\nend\n
    Run Code Online (Sandbox Code Playgroud)\n

    但这并不能确保该记录之前就存在。

    \n
  4. \n
\n

两者的组合可能是:

\n
    it "removes a record from the database" do\n      expect { person.destroy }.to change { Person.count }.by(-1)\n      expect { person.reload }.to raise_error(ActiveRecord::RecordNotFound)\n    end\n
Run Code Online (Sandbox Code Playgroud)\n

  • 请注意,正确的编写方式是 `expect { person.reload }.to raise_error(ActiveRecord::RecordNotFound)` 而不是 `expect(person.reload).to raise_error(ActiveRecord::RecordNotFound)` (2认同)

小智 8

我认为以下是一种很好的方法来测试特定记录是否已按预期删除,同时确保您测试操作的结果而不仅仅是测试对象的状态。

it "removes the record from the database" do
  expect { person.destroy }.to change { Person.exists?(person.id) }.to(false)
end
Run Code Online (Sandbox Code Playgroud)