How to run feature tests in Laravel 9 in memory using SQLite
Default settings in Laravel 9 make automated tests wipe your local MySQL database. Learn how to fix this.
One of the advantages you get by using Laravel’s JetStream package is having built-in feature tests to check your authentication pages: Registration, profile information update, email verification, etc.
Simply running the php artisan test command will execute a bunch of tests (placed in tests/Feature folder) to make you ensure that you didn’t break main functionality while customizing the templates coming with Jetstream installation.
However, directly running these tests without a configuration will cause your local MySQL database to be reset. Thankfully, it’s easy to fix this behavior. Let’s fix it together.
First thing to do is to edit your phpunit.xml file (located in the project root) and uncomment two lines (line 24 and 25) as following:
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
Second, edit the “tests/TestCase.php” file and create initDatabase & resetDatabase methods:
Now when you call the php artisan test command, PHPUnit will run all the tests in memory and won’t touch your local database.
Warning: Your config/database.php file should include an ‘sqlite’ entry in the connections. It should be there by default in Laravel 9. In case you have deleted it before, add it back:
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE',database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true)