A test that asserts on a query count

An N+1 does not fail a test — the page renders correctly, just slowly — so the regression ships and is found by a customer three releases later.

public function testIndexDoesNotNPlusOne(): void
{
    factory(Order::class, 20)->create();

    $count = 0;
    DB::listen(function () use (&$count) { $count++; });

    $this->get('/orders')->assertOk();

    $this->assertLessThan(8, $count, "query count regressed to {$count}");
}

An upper bound rather than an exact number is what makes it maintainable: an exact assertion fails on every unrelated change and gets deleted within a month. Twenty rows in the factory is the part that makes it meaningful, since an N+1 with three rows is four queries and looks fine. The message including the actual count is worth the extra characters — the failure otherwise says only that a number was too large.