Starkers
Starkers

Reputation: 10541

Write a spec to assert that a certain record has been deleted

Counting the number of instances is one way to find out if something has been deleted:

it "should delete the mutual_friendship" do
    @friendship_1.delete_mutual_friendship!
    UserFriendship.count.should == 0
end

However, is it possible to test that a certain record has been deleted? In my case, @friendship_1? Can I test that @friendship_1's attributes no longer exist in the database?

Upvotes: 0

Views: 1004

Answers (3)

Damien
Damien

Reputation: 27473

Use destroyed?:

it "should delete the mutual_friendship" do
  @friendship_1.delete_mutual_friendship!
  @friendship_1.should be_destroyed
  # @friendship_2.should be_destroyed
end

Documentation: destroyed

Upvotes: 1

Peter Alfvin
Peter Alfvin

Reputation: 29399

The ActiveRecord#exists? method lets you test for the existence of a record in the database. You can test for any conditions you want, but assuming testing for the id is sufficient, you can use:

it "should delete the mutual_friendship" do
  @friendship_1.delete_mutual_friendship!
  expect(UserFriendship.exists?(@friendship.id)).to be_false
end

As an aside, all the documentation I've found for this method indicates it returns true or false, but it really should say truthy or 'falsy`, per this commit which, for reasons I can't figure out, isn't reflected in the master branch.

Upvotes: 0

AbM
AbM

Reputation: 7779

Maybe you could reload the record and test that it will raise an error:

it "should delete the mutual_friendship" do
    @friendship_1.delete_mutual_friendship!
    @friendship_1.reload.should raise_error
end

Upvotes: 0

Related Questions