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.
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:
The runDatabaseMigrations()
method in this trait executes migrate:rollback
command after running tests. This command deletes all tables.
$this->artisan('migrate:rollback');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With