Replies: 2 comments 3 replies
-
|
This is a genuinely useful addition! The use case is very common in feature tests, verifying both the content and uniqueness of a record in one assertion. A small concern with the current implementation, the subquery approach works, but it runs two logical checks in one SQL query, which can be harder to debug when the assertion fails. You won't know why it failed, was it the data mismatch or the count? A slightly more debuggable implementation: public function assertDatabaseHasOnly(string $table, array $data, string $connection = null): void
{
$this->assertDatabaseCount($table, 1);
$this->assertDatabaseHas($table, $data);
}This approach:
Regarding framework worthiness, I'd say yes, with one naming consideration. assertDatabaseHasExactlyOne(string $table, array $data)
assertDatabaseHasSingleRow(string $table, array $data)But |
Beta Was this translation helpful? Give feedback.
-
|
Maybe, this should be wrapped in a broader method: public function assertDatabaseHasCount(string $table, array $data, int $count = 1, string $connection = null): void
{
$this->assertDatabaseCount($table, $count);
$this->assertDatabaseHas($table, $data);
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
In my unit tests, I frequently invoke some functionality which results in a record being created, which I then verify has been stored and that it was the only record stored in the given table.
I have ample test functions with assertion pairs like these:
This works fine, although it results in 2 queries (where it could be achieved with just 1) and I have to remember to include the assertEquals 1 count call every time (which I sometimes forget).
So, I wrote a convenience function: assertDatabaseHasOnly
This function asserts that "the table contains exactly one row total, and that row matches these attributes".
Usage:
My current implementation extends the HasInDatabase, and changes the matches function to be:
Producing a query that looks like this:
My question to the audience is: Is this at all a useful idea for a convenience function or just fluff and not framework worthy?
Thanks
Beta Was this translation helpful? Give feedback.
All reactions