23-05-2022

Laravel testing Model with SoftDelete

What could go wrong, you would suggest, with the following assertion, after you delete the record in a test?

 $this->assertDatabaseMissing('files', [ 
    'id' => $fileId, 
    'created_by_id' => $this->user->id, 
    ]);

Error message:

  Failed asserting that a row in the table [files] does not match the attributes {
      "id": 1,
      "created_by_id": 2
  }.

But come on, why?

The answer is really simple:

Because the row really exists on the database, it has just a filled deleted_at column.

Solution is easy after you know this:

 $this->assertDatabaseMissing('files', [ 
  'id' => $fileId, 
  'created_by_id' => $this->user->id, 
  'deleted_at' => null, 
  ]);

Add deleted_at to the assertion also and it will pass!

© 2022 PappZ. All rights reserved.