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
You have two choices. You can test that:
A record was removed from the database
it "removes a record from the database" do
expect { person.destroy }.to change { Person.count }.by(-1)
end
But that doesn't tell you which record was removed.
Or that the exact record does not exist in the database anymore
it "removes the record from the database" do
person.destroy
expect { person.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
or
it "removes the record from the database" do
person.destroy
expect(Person.exists?(person.id)).to be false
end
But that does not make sure that the record existed before.
A combination of both could be:
it "removes a record from the database" do
expect { person.destroy }.to change { Person.count }.by(-1)
expect { person.reload }.to raise_error(ActiveRecord::RecordNotFound)
end