laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Assert database has count #2538

Closed epixian closed 3 years ago

epixian commented 3 years ago

When testing the result of a database transaction, we currently have built-in assertions assertDatabaseHas for the existence of a match (i.e. get matching records and assert count > 0), and assertDatabaseCount to count all records on a given table.

There is no built-in assertion to count only matching records.

This would be especially useful if a test database comes pre-seeded and RefreshDatabase is not used. assertDatabaseHas could return true regardless of the test, and assertDatabaseCount would be pointless without getting the existing count beforehand.

Implementing an assertDatabaseHasCount would provide the abilities of both assertions in a singular call, counting only the matching records.

$result = User::where($data)->get();

$this->assertCount(1, $result);

becomes

$this->assertDatabaseHasCount('users', $data, 1);