Skip to content

Instantly share code, notes, and snippets.

@ohnotnow
Created January 3, 2022 15:15
Show Gist options
  • Save ohnotnow/8791a8063936695fe5497408b8bb0817 to your computer and use it in GitHub Desktop.
Save ohnotnow/8791a8063936695fe5497408b8bb0817 to your computer and use it in GitHub Desktop.
Little Laravel testing trait to help monitor DB queries
<?php
namespace Tests;
trait CountsDatabaseQueries
{
protected $recordedDatabaseQueries = [];
protected function countDatabaseQueries()
{
$this->recordedDatabaseQueries = [];
\DB::listen(function ($query) {
$this->recordedDatabaseQueries[] = [
'sql' => $query->sql,
'bindings' => $query->bindings,
'time' => $query->time,
];
});
}
protected function assertQueryCountEquals($expectedCount)
{
$this->assertCount($expectedCount, $this->recordedDatabaseQueries);
}
protected function assertQueryCountGreaterThan($expectedCount)
{
$this->assertGreaterThan($expectedCount, count($this->recordedDatabaseQueries));
}
protected function assertQueryCountLessThan($expectedCount)
{
$this->assertLessThan($expectedCount, count($this->recordedDatabaseQueries));
}
protected function assertQueryCountBetween($min, $max)
{
$this->assertGreaterThanOrEqual($min, count($this->recordedDatabaseQueries));
$this->assertLessThanOrEqual($max, count($this->recordedDatabaseQueries));
}
}
@ohnotnow
Copy link
Author

ohnotnow commented Jan 3, 2022

And to use :

use Tests\CountsDatabaseQueries;

class MyAmazingTest extends TestCase
{
    use RefreshDatabase;
    use CountsDatabaseQueries;

    /** @test */
    public function we_can_see_the_webpage()
    {
        $user = User::factory()->create();
        $stuff = Stuff::factory()->count(3)->create();
        $this->countDatabaseQueries();

        $response = $this->actingAs($user)->get('/stuff');

        $response->assertOk();
        $response->assertSee('Stuff');
        $this->assertQueryCountEquals(6);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment