9

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?

cb7
  • 493
  • 4
  • 10
  • 1
    This is the correct behavior of `RefreshDatabase` traits. Think about to use a different database for the testing environment. Have a look at this [post](https://stackoverflow.com/questions/35227226/laravel-5-use-different-database-for-testing-and-local) – Roberto Ferro Jul 10 '19 at 16:42

2 Answers2

14

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);
    }
}
matticustard
  • 4,850
  • 1
  • 13
  • 18
1

Update your phpunit.xml and add these 2 lines

<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>
Jelly Bean
  • 1,161
  • 1
  • 11
  • 22