I came across an issue when running unit tests in Laravel where my unit tests where altering my local SQLite database. I knew 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
One of the best parts about Laravel is being able to develop locally using SQLite. When I work with WordPress, my setup is quite cumbersome and setting up unit tests are a real pain. Anyways, 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 all sorts of issues when testing.
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. It also makes your tests a little faster.
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>