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一条记录已从数据库中删除
\nit "removes a record from the database" do\n expect { person.destroy }.to change { Person.count }.by(-1)\nend\nRun Code Online (Sandbox Code Playgroud)\n但这并没有告诉您哪条记录被删除。
\n或者数据库中不再存在确切的记录
\nit "removes the record from the database" do\n person.destroy\n expect {\xc2\xa0person.reload }.to raise_error(ActiveRecord::RecordNotFound)\nend\nRun Code Online (Sandbox Code Playgroud)\n或者
\nit "removes the record from the database" do\n person.destroy\n expect(Person.exists?(person.id)).to be false\nend\nRun Code Online (Sandbox Code Playgroud)\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\nRun Code Online (Sandbox Code Playgroud)\n
小智 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)
| 归档时间: |
|
| 查看次数: |
9670 次 |
| 最近记录: |