Write Laravel Tests to Assert Query Count

Want to write a Laravel test to assert that a request or action is not running too many DB queries?


This can be useful to ensure that some change won't bombard your database for larger datasets.

The reason that I've set it up, is that recently we discovered that one of our endpoints would quickly scale to 300-2000 DB queries depending on entries loaded.


<?php namespace Tests\Feature\Api\Products;

use Tests\TestCase;

class ProductApiTest extends TestCase
    /** @test */
    function query_count_for_products_is_below_30()
        // Seed your database
        factory( App\Product::class, 300 )->create();

        // Start logging queries

        // Do some action, such as send a request.
        $response = $this->json('GET', '/products');
        // Stop logging queries

        // Assert that the number of queries are below a certain point.
        $this->assertLessThanOrEqual( 30, \count( \DB::getQueryLog() ) );


Show Comments