Keep your testing database separate from development

Understanding how phpunit.xml works opens up many possibilities

Joel Clermont
Joel Clermont

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.

    <env name="DB_DATABASE" value="app_test"/>

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.

    <env name="STRIPE_KEY" value="do-not-use"/>
    <env name="STRIPE_SECRET" value="do-not-use"/>

Here to help,


P.S. Do you have any questions about testing? Hit reply and ask away!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.