Hiroki
Hiroki

Reputation: 4163

Laravel 5.5 : Testing with DatabaseMigrations deletes all tables

I've been teaching myself how to write test cases in Laravel 5.5.

I noticed that, when I run a test class which has DatabaseMigrations trait, all the DB tables relevant to the test class are deleted after running the test.

Does this happen by default? I haven't found any clue in the doc.

Any advice will be appreciated.

Upvotes: 13

Views: 6884

Answers (2)

Prince Lionel N'zi
Prince Lionel N'zi

Reputation: 2588

There is DatabaseTransactions and DatabaseMigrations.

With DatabaseTransactions when you run your test, it prepares the transactions, triggers the test and rolls everything back after execution

DatabaseMigrations triggers php artisan migrate command and before the application is destroyed, it rolls everything back.

There is also RefreshDatabase which came in Laravel 5.5, it kind of replaces DatabaseMigrations and DatabaseTransactions.

With RefreshDatabase, if you are using in-memory database, it will run php artisan migrate for you. If you are not using in-memory database, it will drop all your tables and do a fresh run of php artisan migrate.

I will suggest you to use an in-memory database, which can be defined as follow in the php tags of your phpunit.xml file.

...
<php>
    <env name="APP_ENV" value="testing"/>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value=":memory:"/>
    <env name="CACHE_DRIVER" value="array"/>
    <env name="SESSION_DRIVER" value="array"/>
    <env name="QUEUE_DRIVER" value="sync"/>
</php>

Some of the advantages of the in-memory database are the following:

  1. Runs really really fast
  2. Does not affect your actual database because everything happen in the memory

Upvotes: 35

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

The runDatabaseMigrations() method in this trait executes migrate:rollback command after running tests. This command deletes all tables.

$this->artisan('migrate:rollback');

Upvotes: 1

Related Questions