As developers, we often need to test our applications to ensure that they are functioning properly and free of bugs. However, it is a good practice to set aside a database environment dedicated to testing the application.
Some might be wondering, "why would one need a different database for testing"? Well, the default behaviour of tests in Laravel ensures that your database is "Refreshed" each time you perform a test. This means that the data in database is wiped off each time you run a php artisan test command. But this can be frustrating even while in a development environment because there are some times you would need some data retained in the development database; maybe for also doing manual test or getting a personal feel of what you are building, or whatever the case may be. To stop this behaviour, we have to set up a database dedicated to testing the application.
In this article, I will guide you through the step-by-step process, so you can test your code without affecting your development or production data.
Prerequisites
This article assumes that you already have a Laravel application installed and performed your migrations and that the testing is working fine.
Also, we are going to be using sqlite database for the purpose of this tutorial
Create a .env.testing file
First of all, create a .env.testing file in the root directory and copy the contents of your .env
file into it
Modify the Database configuration
Next, modify your DB_CONNECTION
variable to use sqlite
driver for connections and set the DB_DATABASE
to any name you like and append .sqlite
to the end. Example in the screenshot below
Leave the DB_PORT
as is, it doesn't really matter
Run Migrations for the testing database
Next, let's run our database migrations for the new testing database we created. Running your migrations for testing is quite different from the normal way we know. If you run your migrations using the php artisan migrate
command, your migrations will be run using your .env
settings which is not what we want.
Use the command php artisan migrate --env=testing
to run your migrations. This will make sure that your tables will be migrated to the sqlite
database we created specifically for testing.
To test that it worked, run your tests again and your development/production database will still be intact.
If you made it to this point, thank you for your time, and I hope you found it helpful. If you have any suggestions or questions kindly use the comments. Peace!