Created
January 3, 2022 15:15
-
-
Save ohnotnow/8791a8063936695fe5497408b8bb0817 to your computer and use it in GitHub Desktop.
Little Laravel testing trait to help monitor DB queries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And to use :