'Rspec: How to verify if a record has been deleted?
I have created a simple Rspec test to verfiy if a model created has been deleted. However, the test fails because the model still exists. Can anyone provide any assistance on how to determine if the record was actually deleted?
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
Solution 1:[1]
When you delete a record from a database, an object still persists in memory. That's why expect(person).to be_empty() fails.
RSpec has the change matcher. ActiveRecord has the persisted? method. It returns false if a record is not persisted in a database.
it "destroys associated relationships when rtu destroyed" do
expect { person.destroy }.to change(Person, :count).by(-1)
expect(person.persisted?).to be_falsey
end
destroy is a method of a framework. As far as I know, you don't need to test its methods.
Solution 2:[2]
I think the following is a nice way to test a specific record has been removed with one expectation, while ensuring your testing the result of the action and not just the state of your test subject.
it "removes the record from the database" do
expect { person.destroy }.to change { Person.exists?(person.id) }.to(false)
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | EdemaRuh |
