cb7
cb7

Reputation: 523

`RefreshDatabase` drops all tables

In a Laravel/PHPunit test class I added use RefreshDatabase to the class, I understand this should make it so that changes to the database during a test get reverted when the test finishes.

But whenever I run the tests in the class, all tables in the database get dropped, and the tests fail (because the tables don't exist!).

The docs suggest that getting the db to revert after a test is as simple as adding the one line as I did, am I missing something?

Upvotes: 12

Views: 5008

Answers (3)

Brandon Aaskov
Brandon Aaskov

Reputation: 352

TL;DR you want to use a different database for testing. The right way to do this is to have a .env.testing file that duplicates all your env variables from your existing .env file. Make sure to create a new local database, and then update the DB_DATABASE env var in your new file.

The RefreshDatabase trait is probably the most commonly used trait in testing. It runs migrations before each test run, and it wraps each individual test method in a transaction so that it gets rolled back when the test completes.

When you run a test, Laravel automatically sets the app environment to "testing" (equivalent of app()->environment('testing')), which is why it will look for env vars in the .env.testing file. It's also likely you don't need to copy over all your env vars, but you'll at least need the APP_KEY duplicated to the .env.testing file if you are running Jetstream-provided tests.

Upvotes: 0

Jelly Bean
Jelly Bean

Reputation: 1219

Update your phpunit.xml and add these 2 lines

<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>

Upvotes: 0

matticustard
matticustard

Reputation: 5149

If you don't want to wipe and rebuild the database with RefreshDatabase, you can simply use the DatabaseTransactions trait. This will roll back any changes made during testing.

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    use DatabaseTransactions;

    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $this->assertTrue(true);
    }
}

Upvotes: 19

Related Questions