Using PEST in Laravel

Using PEST in Laravel

In case you didn't notice, recently I have been working in a secret project called Pest: a delightful PHP Testing Framework with a focus on simplicity.

Pest is under works, and it will be out soon! I've put together a website where you can subscribe to the @pestphp newsletter. Join now, and be the first to get news about this project: pestphp.com.

In this article, we are going to use PEST in a fresh Laravel application.

To get started, let's require Pest using composer:

composer require pestphp/pest --dev


In case you don't remember, here is how the Laravel default test suite looks like:

PEST is a progressive testing framework, so Laravel default test suite written in PHPUnit will just work, even if you run it under the pest command:

Remember: Pest is built on top of PHPUnit. It's just a different API for creating tests.

Next, let's head over to tests/Unit/ExampleTest.php and see the content:

<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;

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

Now, let's rewrite the basic unit test using Pest:

<?php

test('basic', function () {
    $this->assertTrue(true);
});

Assertions are globally accessibly with PEST, so we can remove the $this variable:

<?php

test('basic', function () {
    assertTrue(true);
});

Finally, because Pest supports higher-order messages, we can make it one-liner:

<?php

test('basic')->assertTrue(true);

Great! Now let's move to the tests/Feature/ExampleTest.php:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

We can rewrite this test in PEST like this:

<?php

uses(Tests\TestCase::class);

it('has welcome page', function () {
    $response = $this->get('/');

    $response->assertStatus(200);
});

Note that, the it function is an alias for test, and it adds the prefix "it" to the description of the test:

As Pest supports higher order messages, we can make the test even more simple:

<?php

uses(Tests\TestCase::class);

it('has welcome page')->get('/')->assertStatus(200);

In addition, we may want to use this Tests\TestCase::class to all tests within the Feature folder. So let's create a Pest.php file within the root of our tests folder with the content:

<?php

uses(Tests\TestCase::class)->in('Feature');

And now we can remove the uses from our feature test:

<?php

it('has welcome page')->get('/')->assertStatus(200);

Finally, and as expected, the final result is very similar to the original one:

Hope you like this article. Stay tuned: the early beta version will be out soon: pestphp.com.

Show Comments