{ claus.conrad }

Pest Driven Laravel

https://laracasts.com/series/pest-driven-laravel

Course notes for Pest Driven Laravel

01 - Welcome

  • Throughout the course, we will practice TDD, writing tests before writing the code that makes them pass.

02 - Prepare our Todos

  • Let’s set up a new Laravel application for this course (I am using Ubuntu 20.04 on [WSL2](…/Microsoft Windows/)) and start it with Sail (Docker):====
sudo apt install php8.1-curl php8.1-xml unzip
curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php
HASH=`curl -sS https://composer.github.io/installer.sig`
php -r "if (hash_file('SHA384', '/tmp/composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
sudo php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer
cd
composer create-project laravel/laravel pest-driven-laravel
cd pest-driven-laravel
php artisan sail:add
alias sail='[ -f sail ] && sh sail || sh vendor/bin/sail'
sail up

03 - Testing Setup

  • Install Pest:
sail composer require pestphp/pest --dev --with-all-dependencies
sail composer require pestphp/pest-plugin-laravel --dev
sail pest --init
  • Tests can be run with php artisan test or sail pest.
  • Pest also runs PHPUnit tests.
  • Pest test runner plugins for:
  • Since Pest is based on it, PHPUnit’s configuration in ./phpunit.xml still applies.
    • Here we can e.g. set environment variables to configure Laravel “drivers”.
    • Recommended configuration:
<env name="DB_CONNECTION" value="sqlite" />
<env name="DB_DATABASE" value=":memory:" />

04 - Write Your First PEST Test

  • assertOk() is a shortcut for checking that the HTTP status code is 200.
  • The structure of each test should be:
    1. Arrange - set up required data
    2. Act - invoke the tested method/view/etc.
    3. Assert - ensure that the test passes

05 - Show Course Overview - Part 1

  • Pest’s uses() method allows running a trait before a test.
  • The Illuminate\Foundation\Testing\RefreshDatabase trait refreshes the database before a test.
  • assertSeeText() checks that some text is visible in the response body.
  • Tests are documentation for other developers, so individual tests should not be too specific.

06 - Show Course Overview - Part 2

  • assertSeeTextInOrder() checks that some texts are visible in the response body in the given order.
  • Since some databases by default return rows in the order they were created, when we want to see results in a certain order in the response body, it is a good idea to switch the order when we arrange (create) the test data (so rows are created in the opposite order of how we want them ordered in the view). Otherwise even unordered results would incorrectly pass the test.