Laravel Packages

Given-When-Then Plugin for Pest

Published
Given-When-Then Plugin for Pest image

Given-When-Then (GWT) is a plugin that brings behavioral style testing to Pest:

GWT is a simple API that allows you to structure your tests focused on the behavior. Given-When-Then separation makes the test easier to understand at a glance.

Behavior-driven testing using GWT can help clarify three distinct steps while testing code, which includes 1) arranging the application state (given), 2) the "act" phase (when), and 3) the outcome phase (then) which asserts the expected outcome of the previous steps:

use App\Exceptions\BlockedUserException;
use App\Models\User;
use function Pest\Gwt\scenario;
use function Pest\Laravel\assertDatabaseHas;
 
scenario('activate user')
->given(fn() => User::factory()->create())
->when(fn(User $user) => $user->activate())
->then(fn(User $user) => assertDatabaseHas('users', [
'id' => $user->id,
'activated' => true,
]));
 
scenario('activate blocked user')
->given(fn() => User::factory()->blocked()->create())
->when(fn(User $user) => $user->activate())
->throws(BlockedUserException::class);

The repo includes more examples of GWT-style tests for Pest to help you get started. You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article