Learn Laravel Β· 16/17

Testing: Shipping Code with Confidence

7 min read

Welcome, intrepid coder, to the world of testing in Laravel! This is where we transform from hopeful developers into confident engineers. Writing tests is like having a personal robot assistant who meticulously checks your work for any mistakes before you show it to the world. It's your safety net, allowing you to add new features or refactor existing code without the fear of breaking something.

The Problem: Imagine you've built a shiny new feature. You push it to production, and suddenly, your bug report channel starts smoking. A tiny change you made broke a completely unrelated part of the application. Now you're in damage control mode, frantically trying to fix the issue while users are getting frustrated.

The Solution: Automated tests! These are little scripts that run parts of your application and check if they behave as expected. With a good test suite, you can catch these issues before they ever reach your users.

In Laravel, testing is a first-class citizen. It comes with powerful tools right out of the box to make writing tests a breeze.

πŸ§ͺ Testing Fundamentals: PHPUnit vs Pest PHP

Laravel provides support for two popular testing frameworks: PHPUnit and Pest. Think of them as two different languages to instruct your testing robot. Both are built on the same powerful engine (PHPUnit), but they offer different ways of writing your tests.

PHPUnit: The Classic 🧐

PHPUnit has been the go-to testing framework for PHP for a long time. It uses a more traditional, class-based approach to writing tests.

A typical PHPUnit test looks like this:

php
<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     */
    public function test_that_true_is_true(): void
    {
        $this->assertTrue(true);
    }
}

Here, each test is a method within a class that extends PHPUnit\Framework\TestCase. The method name usually starts with test_ to indicate that it's a test.

Pest PHP: The New Kid on the Block 😎

Pest is a newer testing framework that's built on top of PHPUnit. It aims to provide a more elegant and readable syntax, making your tests easier to write and understand.

The same test in Pest looks like this:

php
<?php

test('that true is true', function () {
    expect(true)->toBeTrue();
});

Notice the difference? Pest uses a more functional approach with a focus on human-readability. Many developers find this syntax more expressive and enjoyable to work with.

Which one should you choose? It's largely a matter of personal preference.

  • PHPUnit is well-established and a great choice if you prefer a more structured, object-oriented style.
  • Pest is fantastic if you value a clean, expressive, and more concise syntax.

For the rest of this guide, we'll primarily use Pest for its modern and readable syntax. But don't worry, the underlying concepts are the same for both!

Getting Started:

When you create a new Laravel project, everything you need for testing is already set up. You can run your tests by executing one of these commands in your terminal:

bash
php artisan test
# or
./vendor/bin/pest
# or
./vendor/bin/phpunit

πŸš€ Feature Tests: Simulating User Interactions (HTTP Tests)

The Problem: How do you know if a user can actually register, log in, or create a post on your blog? You could manually test it in your browser every time you make a change, but that's slow and prone to human error.

The Solution: Feature tests! These tests simulate how a user would interact with your application through a web browser. You can make HTTP requests to your application's routes and then inspect the responses to ensure everything is working as expected.

Let's imagine we're building a simple blog and we want to test that a user can see a list of posts on the homepage.

First, we'll create a new feature test:

bash
php artisan make:test PostTest

This will create a new PostTest.php file in your tests/Feature directory.

Now, let's write a test to visit the homepage and check if it's successful:

php
// tests/Feature/PostTest.php

use function Pest\Laravel\get;

test('the home page is accessible', function () {
    get('/')->assertStatus(200);
});

What's happening here?

  • get('/') makes a simulated GET request to the homepage of our application.
  • assertStatus(200) checks that the response has an HTTP status code of 200, which means "OK".

A more complex example: Let's test creating a new post.

php
// tests/Feature/PostTest.php

use App\Models\User;
use function Pest\Laravel\{actingAs, post};

test('a user can create a post', function () {
    // 1. Arrange: Create a user to act as the logged-in user.
    $user = User::factory()->create();

    // 2. Act: Simulate the user submitting the new post form.
    actingAs($user)->post('/posts', [
        'title' => 'My Awesome Post',
        'body' => 'This is the body of my awesome post.',
    ]);

    // 3. Assert: Check that the post was saved to the database.
    $this->assertDatabaseHas('posts', [
        'title' => 'My Awesome Post',
    ]);
});

This test follows the "Arrange, Act, Assert" pattern, a common best practice in testing.

πŸ—„οΈ Database Testing: The RefreshDatabase Trait

The Problem: When you run tests that interact with the database, you need to make sure that each test starts with a clean slate. If one test adds a user to the database, you don't want that user to still be there for the next test, as it could lead to unexpected results.

The Solution: The RefreshDatabase trait. This magical trait handles resetting your database between each test.

Here's how you use it in a Pest test file:

php
// tests/Feature/YourTestFile.php

use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

// Your tests go here...

Under the Hood: When you use RefreshDatabase, Laravel will run all your database migrations at the beginning of the test suite. Then, for each individual test, it will wrap the test in a database transaction and roll it back when the test is finished. This is super fast because it doesn't have to re-migrate the database for every single test.

Imagine you're building a complex sandcastle. After you're done admiring your work (running a test), a magical wave comes and perfectly smooths out the sand (rolls back the transaction), so you can start fresh on your next masterpiece. That's RefreshDatabase for you!

🧩 Unit Testing Models and Custom Classes

The Problem: Feature tests are great for testing the big picture, but what about the smaller, individual pieces of your code? How do you test a specific method in a model or a custom service class in isolation?

The Solution: Unit tests! These tests focus on a very small, isolated portion of your code. For example, you might have a User model with a method to get the user's full name. A unit test would ensure that this one method works correctly.

Let's say our User model has this method:

php
// app/Models/User.php

public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

We can write a unit test for it like this. First, create the test file:

bash
php artisan make:test UserTest --unit

This will create UserTest.php inside tests/Unit.

php
// tests/Unit/UserTest.php

use App\Models\User;

test('a user can get their full name', function () {
    // Arrange
    $user = User::factory()->make([
        'first_name' => 'John',
        'last_name' => 'Doe',
    ]);

    // Act & Assert
    expect($user->full_name)->toBe('John Doe');
});

Key things to notice:

  • We're in the tests/Unit directory.
  • We're using User::factory()->make() instead of create(). The make() method creates a new model instance in memory without saving it to the database. This keeps our unit test isolated from the database.

Testing Custom Classes

The same principle applies to any custom class you create. Let's say you have a CurrencyConverter class:

php
// app/Services/CurrencyConverter.php

class CurrencyConverter
{
    public function convert(float $amount, string $from, string $to): float
    {
        // In a real app, this would be more complex!
        return $amount * 1.1;
    }
}

Your unit test would look something like this:

php
// tests/Unit/CurrencyConverterTest.php

use App\Services\CurrencyConverter;

test('it can convert currency', function () {
    // Arrange
    $converter = new CurrencyConverter();

    // Act
    $convertedAmount = $converter->convert(100, 'USD', 'EUR');

    // Assert
    expect($convertedAmount)->toBe(110.0);
});

By testing these small units of code, you can be confident that each individual part of your application is working correctly. When you combine this with feature tests, you get a very robust and reliable application.

Happy testing! πŸš€

πŸ“š Extra Reading:

Challenge

You are tasked with writing a feature test for a new blog post creation functionality in a Laravel application.

Your goal is to ensure that an authenticated user can successfully submit a form to create a new blog post.

Requirements:

  1. You will be working within a Pest PHP test function.
  2. Use the RefreshDatabase trait to ensure a clean database state for your test.
  3. Follow the "Arrange, Act, Assert" pattern.
  4. Arrange: Create a new user using the User factory and persist it to the database.
  5. Act:
    • Simulate that the newly created user is authenticated.
    • Make a POST request to the /posts endpoint.
    • The request payload should contain a title and a body for the new post.
  6. Assert:
    • Assert that the response is a redirect.
    • Assert that the posts table in the database now contains a record matching the title you sent.

Expected result

Your code should correctly implement the full "Arrange, Act, Assert" testing pattern within the provided Pest test function.

The final implementation should first create a user with the User::factory()->create() method. Then, it should chain the actingAs() method to simulate authentication before making a post() request to the /posts endpoint with title and body data. Finally, it should use assertRedirect() on the response and assertDatabaseHas() to verify that the new post data exists in the posts table.

php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.