Using In-Memory SQLite Database During Unit Tests In Laravel

I came across an issue when running unit tests in Laravel where my unit tests where altering my local SQLite database. I discovered the issue was due to the sharing of .env files. It turns out the solution is as simple as adding a single environment variable to your phpunit.xml file.

The problem

One of the best parts about Laravel is being able to develop locally using SQLite. When I work with WordPress, setup can be quite cumbersome and setting up unit tests are a pain. If you use SQLite while developing Laravel locally, you may have ran into the issue where your tests use the same local SQLite database causing issues when testing.

The solution

Luckily, the solution is incredible easy as PHPUnit allows you to specify php environment variables during run-time. By simply adding a :memory: value to the DB_DATABASE variable, the unit tests will now use an in-memory SQLite instance instead of your local SQLite database. In-memory tests will also be a little quicker.

Here is what my phpunit.xml file looks like with the added environment variable.

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="bootstrap/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Feature Tests">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>

        <testsuite name="Unit Tests">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="DB_DATABASE" value=":memory:"/>
    </php>
</phpunit>

Author: rfmeier

Product developer at WPEngine and runner from Schaumburg, Illinois. I work with php and Python; Spending most of my time digging into source code to see how it all works.