Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 643
Hiroki Avatar asked Jan 29 '18 21:01

Hiroki


2 Answers

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
like image 73
Prince Lionel N'zi Avatar answered Nov 16 '22 01:11

Prince Lionel N'zi


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

$this->artisan('migrate:rollback');
like image 41
Alexey Mezenin Avatar answered Nov 16 '22 03:11

Alexey Mezenin