Laravel 5.4 #25 : Tests

Today we are going to create some tests with Laravel, and we’ll see how they work and what they are.

A test is a code that checks that a piece of our code works correctly and does what it should do. In Laravel there are two types, the Unit tests that check the functionality of small parts of our code (methods) and there are also the Feature tests that will be the ones we will use in this post and that check a larger part of our code (things with database, HTTP requests, etc.).

To create the file for our test, as usually, artisan provide us a command to do it:

Ok, now we have the file created, but before adding the code, we are going to do a few necessary configurations.


First of all, open the  phpunit.xml  file (it’s in the project root) and add these lines to the end of the file:

With these lines we indicate that we will use an SQLite database to perform the tests.

Now, we will have to install a package to be able to use this type of database, otherwise will give us an error:

Update the packages:


Now we are going to add the code to the previously created test file ( PostTest.php ):

There are two functions in this file:

  • The first one (test_posts_can_be_created) checks that the posts can be created by one user. Once created the test post, checks if exists in the database.
  • The second one (post_cant_be_created_by_unlogged_user) checks that a unlogged user can’t access to the creation posts route. To ensure that it is working properly, we will have to comment on the auth middleware of the store method in the PostsController.php , because otherwise it returns another HTTP error.

To execute these tests, we simply go to the root of the project and execute:

And if we want to execute a specific file, in my case it would be:

And we will see in the console that the tests are positive:


This is simply an example, the tests that can be done can be infinite. You can find more information about the tests in the documentation of Laravel.