This past week I’ve been using Laravel at work and has been trying to apply
Test Driven Development. My first step was to learn how to test the models
which I’ll be demonstrating in this tutorial using Laravel 5.6. We’ll create a
new project which has an Article model with attributes title, content and
views.
Let’s start creating a new Laravel project with:
or
Setup the Article model and the database table
Make an Article model with a migration.
The generated file for Article model will be at app/Article.php.
The articles table should have columns title, content and views so we’ll
add those columns on our migration file at
database/migrations/create_articles_table.php.
Then run the migration for creating the table for articles.
Creating tests for the Article model
Our Article model is now ready for testing and we’ll be making integration tests
but before that let’s make a factory.
The generated factory for the model Article will be at
database/factories/ArticleFactory.php.
Create an integration test for the Article model at
tests/Integration/models/ArticleTest.php by running:
Modify its contents to look like this:
Our test creates 5 articles with 0 views, another article with 100 views and the
most viewed article with 200 views. It checks if the method
Articke::mostViewed() returns the same id as the most viewed article.
Running the test and adjusting the model based on the results
Now we run phpunit:
or
if the command above doesn’t work.
The test would fail because the Article::mostViewed() method hasn’t been
implemented. Let’s implement the Article::mostViewed() method by modifying the
Article model to look like this:
If you run phpunit now it would still fail because the data from the last test
persisted. We need to refresh the database everytime the test is executed. We
refresh it by using RefreshDatabase from “Illuminate\Foundation\Testing”.
ArticleTest should look like this: