LARAVEL BLOG TDD SETUP #30DAYSOFLARAVEL DAY 1
July 27th, 2019 by Kevin Pimentel
Laravel is my go-to framework because of how easy it is to use. Laravel is a large framework with a big learning curve. For smaller applications it can feel like overkill, but for most mid-large scale applications, the Laravel framework is perfect.
Laravel Blog Using Test Driven Development
Testing has become a part of my workflow. At first it felt clunky and unnatural to write tests. This year (2019) I attended php[tek] in Atlanta Georgia and finally achieved some level of clarity on Test Driven Development. At php[tek], the @grmpyprogrammer was the instructor for the testing track. He recommended the book Extreme Programming Explained which I bought.
Let’s Build a Blog!
Building a blog is a great way to practice a laravel TDD workflow. After reading Extreme Programming Explained and building a few small applications, it all started to flow. I don’t know why I ever wrote code without tests before. The level of confidence you gain is freeing.
If you’ve never setup laravel before you can learn how to install laravel through the documentation.
Install new Laravel Project
Assuming you have the laravel installer in composer global, you can create the new laravel project by running this command:
$ laravel new larablog
This will get all of the laravel packages into your vendor folder.
For a simple local server we can run the command:
php artisan serve
There are many options, including Homestead and Valet. I have a xampp setup on my machine and I’ll be adding an entry into my hosts and vhost files. For that sort of setup you can search on Google for a solution similar to this one.
Configure PHPUnit to use SQLite
I don’t want my tests running on my main database. I’d like to avoid the possibility of manipulating my real data. To do this, I will configure phpunit to use sqlite, an in memory database.
The following lines need to be added in our phpunit.xml file inside of the php tag.
<php> ... <server name="DB_CONNECTION" value="sqlite"/> <server name="DB_DATABASE" value=":memory:"/> … </php>
I use terminal for php artisan and running my PHPUnit tests. In order to cut down the amount of typing for the commands, here are the aliases I use:
alias pa='php artisan' alias pu='./vendor/bin/phpunit' alias pf='pu --filter='
When I run pu:
$ pu PHPUnit 7.5.14 by Sebastian Bergmann and contributors. .. 2 / 2 (100%) Time: 2.15 seconds, Memory: 14.00 MB OK (2 tests, 2 assertions)
I haven’t written any tests yet but Laravel comes with a couple of example tests out of the box. It’s cleanly configured to support a TDD workflow.
There are two types of people in the world: those that code, and those that don’t. I said that! Quote me. My name is Kevin and I’m one of the ones that codes.