Given-When-Then Plugin for Pest
Published on by Paul Redmond
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.