Skip to content
This repository was archived by the owner on Jul 16, 2021. It is now read-only.
This repository was archived by the owner on Jul 16, 2021. It is now read-only.

[Proposal] Add SQL Assertions for Tests #1553

Closed
@DarkGhostHunter

Description

@DarkGhostHunter

For what I could gather, there is no easy database assertions in Laravel testing suite.

It would be very handy to have assertions to count what queries where executed, and if a particular query was executed with bindings. Take for example these hypothetical test methods:

public function testQueryExecuted()
{
    $queries = DB::connection('sqlite')->capture(function() {
    
        User::create(['name' => 'John', 'email' => '[email protected]']);
        $user = User::find(1);
        $user->name = 'Mike';
        $user->save();
        $user->delete();
    
    });
    
    $queries->assertQueryExecutedOn('users');
    $queries->assertQueryNotExecutedOn('users');
    
    $queries->assertInsertQueryExecutedOn('users', ['name' => 'Jhon'], false);
    $queries->assertSelectQueryExecutedOn('users', ['id' => '1'], false);
    $queries->assertUpdateQueryExecutedOn('users', ['name' => 'Mike']);
    $queries->assertDeleteQueryExecutedOn('users', ['id' => '1']);
    $queries->assertSoftDeleteQueryExecutedOn(User::class, ['id' => '1']);
    
    $queries->assertInsertQueryNotExecutedOn('users', ['name' => 'Jhon'], false);
    $queries->assertSelectQueryNotExecutedOn('users', ['id' => '1'], false);
    $queries->assertUpdateQueryNotExecutedOn('users', ['name' => 'Mike']);
    $queries->assertDeleteQueryNotExecutedOn('users', ['id' => '1']);
    $queries->assertSoftDeleteQueryNotExecutedOn(User::class, ['id' => '1']);

    $queries->assertNumberOfQueriesExecuted(4);
    $queries->assertNumberOfInsertQueriesExecuted(1);
    $queries->assertNumberOfSelectQueriesExecuted(1);
    $queries->assertNumberOfUpdateQueriesExecuted(1);
    $queries->assertNumberOfDeleteQueriesExecuted(1);
    $queries->assertNumberOfSoftDeleteQueriesExecuted(0);
    
    $queries->assertSqlQueryExecuted('select * from "user" where "id" = ?', [1]);
    $queries->assertSqlQueryNotExecuted('select * from "user" where "name" = ?', ['John']);
}

Unless there is already a package to allows these test.

There is an already DB::connection()->enableQueryLog() method that saves every query into an array, so including these kind of assertions shouldn't be hacky. Also, It would help immensely to internal Laravel Database testing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions