In reply to last week's tip on having Laravel automatically run seeders in your tests, someone asked "How do you set up the test so it doesn't blow out your real database?"
The answer is to configure your tests to use a different database than you use for local development. But how do you accomplish that?
First, think about how we tell Laravel which database to use at all? We use environment variables like DB_HOST
and DB_DATABASE
. So what we really want is for DB_DATABASE
to have a different value inside our tests than in a normal application request.
Laravel will look for an .env.testing
file, and use those values during a test run, but I prefer to use the phpunit.xml
for all testing-related configuration.
By default, Laravel sets some values in our phpunit.xml
for testing configuration. For example, it sets APP_ENV
to testing
and it drops BCRYPT_ROUNDS
to 4 to make our tests a little faster.
We can use this same file to change our DB_DATABASE
value. If my development database is called app
, then I'd have DB_DATABASE
set to app_test
in the phpunit.xml
.
<php>
<env name="DB_DATABASE" value="app_test"/>
</php>
Related to this, we'll also forcibly set any env values used by third party services (AWS, Stripe, etc) to purposely-invalid values. This prevents our tests from ever accidentally hitting a third-party service.
<php>
<env name="STRIPE_KEY" value="do-not-use"/>
<env name="STRIPE_SECRET" value="do-not-use"/>
</php>
Here to help,
Joel
P.S. Do you have any questions about testing? Hit reply and ask away!