My Laravel TDD 101 Experience: How to set up a database for local testing?

Nithisa.L
Nithisa’s Dev Blog
2 min readFeb 14, 2020

Recently, I have learned Let’s Build A Forum with Laravel course from Laracast, This is my first time learning TDD and this blog may like my summary note that I have learned from this course.

When we testing program with PHPUnit on Laravel, at some point we have to test the database transactions to make sure that everything works correctly.

But sometimes it will make a change to your local development database each time we run the test suit.

What can we do to solve this problem?

When we goto the config/database.php file and check the database connection’s name its shown the default database config.

'default' => env('DB_CONNECTION', 'mysql'),

It tells you that this project uses MySQL database as the default database and the configuration placed in the .env file like this.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tdd
DB_USERNAME=root
DB_PASSWORD=root

So, how can we create the testing environment for database testing?

How to

The first step is we have to tell Laravel that we want to use the testing database instead of the default in the testing environment.

Goto phpunit.xml and find these lines of code.

<php>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="MAIL_DRIVER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
</php>

Second, add the DB_CONNECTION and DB_DATABASE config.

<php>
<server name="APP_ENV" value="testing"/>
<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>

<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="MAIL_DRIVER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
</php>

We will use the SQLite database for our testing environment and defined the parameter :memory: for DB_DATABASE, because we will use a memory version SQLite database.

The in-memory version of the SQLite database will perform when we run our test suit only. Its will create and store on the memory after that its will ceases to exist as soon as the database connection is closed.

When we have a lot of tests cases it may perform the test slower when we use the database that reading and writing on the disk. The benefit of the in-memory database is speed because memory can perform faster than disk.

References:

https://www.sqlite.org/inmemorydb.html

https://en.wikipedia.org/wiki/In-memory_database

--

--

Nithisa.L
Nithisa’s Dev Blog

A (sleepy) Full Stack developer | Coffeeholic | Big eater | Cat lover ლ(●ↀωↀ●)ლ