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.

Serdar Cevher
1 min readApr 8, 2022

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.

That’s all!

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)
]

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Serdar Cevher
Serdar Cevher

Written by Serdar Cevher

Developer of web & mobile apps | Co-founder: Off2Class, Auglinn | Founder: SmarDish, tarifmotoru.com, valizim.com | Ex columnist @PCnetDergisi

No responses yet

Write a response