assertDatabaseHas not working as expected

Published 1 week ago by fureszk

Hello Everyone,

I'm having an issue with testing Laravel 5.5.

I have modified phpunit.xml to use DB_CONNECTION "testing", which is a mysql database. I have overridden assertDatabaseHas to use the same connection and using DatabaseTransactions, so my TestCase class looks like this:

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication, DatabaseTransactions;
    //...
    public function assertDatabaseHas($table, array $data, $connection = 'testing')
    {
        return parent::assertDatabaseHas($table, $data, $connection);
    }
}

My other tests work great, but assertDatabaseHas doesnt seem to work. I created an example:

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testExample()
    {
        $details = [
            'email' => sha1('[email protected]'),
            'token' => str_random(10),
        ];

        \DB::table('tokens')->insert($details);

        $this->assertDatabaseHas('tokens', $details);
    }
}

Fails with the following message:

Failed asserting that a row in the table [tokens] matches the attributes {
    "email": "16a6ce8524fcf78c938b8b98e97525c8b20c9fb3",
    "token": "xlCqvCD1Np"
}.

The table is empty.

One of my tests which works:

    /**
     * @test
     */
    public function it_has_purchases()
    {
        $this->user->purchases()->saveMany(factory(\App\Purchase::class, 3)->create());
        $this->assertContainsOnlyInstancesOf(\App\Purchase::class, $this->user->purchases);
    }

So the "testing" connection works, I can persist models in the database and fetch them.

Best Answer (As Selected By fureszk)
fureszk

All I had to do is show PHPStorm what configuration file to use (phpunit.xml). Solved.

fureszk
fureszk
1 week ago (12,470 XP)

All I had to do is show PHPStorm what configuration file to use (phpunit.xml). Solved.

Sign In or create a forum account to participate in this discussion.