We've finished the Links CRUD feature but haven't actually tested it.
A common question I get is how to write automated tests and WHEN to write them. After all the project is done? Before the code, with TDD? The truth is somewhere in the middle.
I prefer to write tests immediately after the feature is finished. At that moment, the code is still fresh in your head or IDE, so it's easier to write the test cases.
In my experience, TDD forces you to guess the functionality before you know how it would work. On the other hand, when writing tests for the full project afterward, it will be hard to remember the functionality of the features created a long time ago.
So, we'll be working on the tests in this lesson.
Introducing Feature Branches
In the example of this course, we separated the Links CRUD feature and its automated tests in separate lessons. I did it to demonstrate the different approaches to branching:
- Links CRUD code is pushed to the
dev
branch - Links CRUD tests will be pushed to a new feature branch (which later will be merged into
dev
)
From here, we will use feature branches for the following lessons.
git checkout -b feature/links-tests
Notice: In real life, you should push Code and Tests in one commit. We separated them for educational purposes.
Writing Tests: CRUD, Validation and Multi-Tenancy
Let's discuss the question of WHAT to write tests for.
For this Links CRUD functionality, we will write three kinds of tests.
First, for a typical CRUD, we should simulate the situations for each Controller method: index()
, create()
, edit()
, etc. This is the so-called "happy path".
But, on top of that, we need to test the scenarios when something goes wrong. These are often overlooked by developers who focus only on the "shiny scenario". However, the majority of bugs happen precisely when someone enters unexpected data. So, our goal is to come up with those "bad scenarios" and ensure that our application deals with them properly, showing the errors.
Finally, we require that every user see only their links. This is the most simple definition of multi-tenancy, so we need to test whether this condition works well.
To illustrate these three concepts separately, we decided to generate three different test files:
php artisan make:test Links/LinksCrudTestphp artisan make:test Links/LinksValidationTestphp artisan make:test Links/TenancyTest
It's your preference; you may prefer to have one longer LinksTest
.
Also, you choose whether to use Pest (Laravel default now) or PHPUnit. I will use Pest in this course.
IMPORTANT: Separate Database for Testing
Our tests will create fake data in the database to simulate the scenarios. So, we must ensure it works on a separate testing database to avoid...