Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AlexG834's avatar

Is there a way to persist certain tables between tests?

I have a set of tables that hold information about things that will never change in my database such as country information. I'm currently re-seeding this data in setUp() before every test, which is making my tests incredibly slow.

I'm using MySQL for a test database, so I wouldn't mind manually seeding the data but the RefreshDatabase trait clears out all tables. Is there a way to keep data in some tables when using this trait?

I've tried to place all migrations that I don't want to be run in a sub-folder, but the RefreshDatabase trait calls php artisan migrate:fresh, so all tables are wiped out regardless, but not re-created.

Surely this is a common workflow. Am I missing something?

0 likes
5 replies
Talinon's avatar
Talinon
Best Answer
Level 51

@alexgodbehere You might want to consider using the DatabaseTransactions trait. You can seed your database once, and DatabaseTransactions will still roll back the test transactions at the end of the tests, but won't run the migrations; meaning your seeded data will persist thru the tests. The only thing you need to be mindful of, is you will need to manually run the migrations on your test database to bring them up-to-date when you make changes to your database structure.

If you don't want to use DatabaseTransactions, another option you can try is an in-memory sqlite database. It's very easy to set up, and is exponentially faster than using a mysql database for testing.

Just install sqlite, set up a connection in your config/database.php file, and alter your phpunit.xml file with these values:

config/database.php:

        'sqlite_testing' => [
            'driver' => 'sqlite',
            'database' => database_path('testing.sqlite'),
            'prefix' => '',
        ],

<env name="DB_CONNECTION" value="sqlite_testing"/>
<env name="DB_DATABASE" value=":memory:"/>

sqlite_testing = whatever you called it in your config/database.php Also, make sure you create the sqlite database file within database/testing.sqlite. It just needs to be an empty file. If using mac/linux, you can just run touch database/testing.sqlite

AlexG834's avatar

Perfect, thanks! Is there a way to migrate the test database using php artisan?

Please or to participate in this conversation.