PHPackages                             wolfpack-it/laravel-gwt-plugin - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. wolfpack-it/laravel-gwt-plugin

ActiveLibrary[Testing &amp; Quality](/categories/testing)

wolfpack-it/laravel-gwt-plugin
==============================

A Behavior Driven Testing (GWT) plugin for your Laravel Tests

2.0.0(2y ago)02.2kMITPHPPHP ^8.2.0

Since Nov 21Pushed 2y ago3 watchersCompare

[ Source](https://github.com/wolfpack-it/laravel-gwt-plugin)[ Packagist](https://packagist.org/packages/wolfpack-it/laravel-gwt-plugin)[ RSS](/packages/wolfpack-it-laravel-gwt-plugin/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (3)Versions (7)Used By (0)

Laravel Given-When-Then plugin
==============================

[](#laravel-given-when-then-plugin)

> A Behavior Driven Testing (GWT) plugin for your Laravel Tests

### Install

[](#install)

```
composer require wolfpack-it/laravel-gwt-plugin --dev
```

### Usage / Example

[](#usage--example)

Basically you extend your Test with the TestCase provided by this package, which allows you to use the package methods. See an example below:

```
use App\Mails\ConfirmationMail;
use App\Models\Language;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Mail;
use Illuminate\Testing\TestResponse;
use WolfpackIT\LaravelGWTPlugin\TestCase;

// Extend the Laravel GWT Plugin TestCase
class StorePostTest extends TestCase
{
    public function test_user_can_store_post(): void
    {
        $this
            // Act as a random User
            ->as(User::factory()->create())
            // Fake sending the email
            ->fake(Mail::class)
            // Given is the post data, stored in a param called `post`
            ->given(fn (): array => [
                'title' => 'My first post',
                'content' => 'Lorem ipsum dolor amet sum it',
            ], 'post')
            // Given is the current language
            ->given(fn(): Language => Language::current())
            // The $post and $language are automatically injected based on the results of the `given` methods
            ->when(fn (array $post, Language $language): TestResponse =>
                $this->postJson(route('api.posts.store'), $post)
            )
            // Instead of using a closure you can call a protected method as a callable with `(...)`
            ->then($this->responseContainsPostId(...))
            // Add as much `then` methods as needed
            ->then($this->confirmationMailIsSent(...));
    }

    // The $response is automatically injected based on the TestResponse result of the `when` method
    protected function responseContainsPostId(TestResponse $response): void
    {
        $response
            ->assertCreated() // Status code 201
            ->assertJson(fn (AssertableJson $json) =>
                $json->has('id')
                // .. add other assertions
            );
    }

    protected function confirmationMailIsSent(Authenticatable $user): void
    {
        Mail::assertSent(ConfirmationMail::class, function (Mailable $mail) use ($user) {
            return $mail->hasTo($user->email);
            // .. add other assertions
        });
    }
}
```

### Methods

[](#methods)

#### The `as` method

[](#the-as-method)

While testing, the Sanctum::actingAs or Passport::actingAs method may be used to authenticate a user. To use this Authenticated user in the Given-When-Then methods you can use the `as(Authenticatable $user, ?string $injectAs = null)` method. This Authenticatable is then added to the auto injection for the other methods.

```
$this->as(User::factory()->create());
$this->as(Admin::factory()->create(), 'admin');
```

In order to change the default Auth Provider (Sanctum), you can use the following static methods to change these settings. As long as the guard is defined in the `config/auth.php` and the Auth Provider class implements the `actingAs` method:

```
TestScenario::setAuthGuard('admin');
TestScenario::setAuthProvider(TestScenario::PASSPORT_AUTH_PROVIDER);
```

#### The `fake` method

[](#the-fake-method)

While testing, you might need to mock some services like Mails or Events. In order to do this within the plugins syntax you can use the `fake(string $facade)` method. Any facade which contains the `fake` method can be used.

```
$this->fake(Mail::class);
```

#### The `throws` method

[](#the-throws-method)

The throws method indicates that you're expecting a when action to throw an exception. The methods expect an exception class name (string) and optionally a exception message.

#### The `given` method

[](#the-given-method)

Given describes the preconditions and initial state before the start of a test and allows for any pre-test setup that may occur. The method expects a Closure / Callable as first parameter and uses the outcome (Return Type) to populate the pre-conditions in the scenarios parameters. The callable can use conditions from previous given methods in a chain via auto injection. The second argument is to help define as which key the param can be retrieved by the auto-injection. When using two of the same types, this `as` params can be very useful. Example

```
    $this
        ->given(fn(): User => User::factory()->student()->create(), 'student')
        ->given(fn(): User => User::factory()->teacher()->create(), 'teacher');
```

#### The `when` method

[](#the-when-method)

When describes actions taken during a test. This method expects the same arguments as the given method. Where the second param has a default value of `'response'`. The callable can use all conditions from the previous given methods as needed.

```
$this->when(fn(array $postData): TestResponse => $this->postJson('/posts', $postData));
```

#### The `then` method

[](#the-then-method)

Then describes the outcome resulting from actions taken in the when clause. This method only expects a Closure / Callable which can make the assertions necessary. Via auto-injection the method can use both the result of the previous when methods and the previous conditions of the given methods. This might be useful when trying to compare given data to the given response.

```
$this->then(fn(TestResponse $response) => $response->assertOk());
```

### Good to know

[](#good-to-know)

> Make sure your closures / callables implement return types, so that the auto-injection is able to identify which condition or response to map to which argument.

This package was created by Pascal van Gemert @ **[WolfpackIT](https://wolfpackit.com)**. It got open-sourced and is now licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~100 days

Total

4

Last Release

972d ago

Major Versions

1.1.1 → 2.0.02023-09-19

PHP version history (2 changes)1.0.0PHP ^8.1.0

2.0.0PHP ^8.2.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/609e8d7caaa1dacc8b03bcc8347b5732e5a91399bb843e5b44fec66be256f35a?d=identicon)[pascalvgemert](/maintainers/pascalvgemert)

---

Top Contributors

[![pascalvgemert](https://avatars.githubusercontent.com/u/1567379?v=4)](https://github.com/pascalvgemert "pascalvgemert (3 commits)")

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/wolfpack-it-laravel-gwt-plugin/health.svg)

```
[![Health](https://phpackages.com/badges/wolfpack-it-laravel-gwt-plugin/health.svg)](https://phpackages.com/packages/wolfpack-it-laravel-gwt-plugin)
```

###  Alternatives

[orchestra/testbench

Laravel Testing Helper for Packages Development

2.2k39.1M32.1k](/packages/orchestra-testbench)[hotmeteor/spectator

Testing helpers for your OpenAPI spec

3021.4M1](/packages/hotmeteor-spectator)[orchestra/workbench

Workbench Companion for Laravel Packages Development

8217.0M43](/packages/orchestra-workbench)[botble/git-commit-checker

Check coding standard &amp; code syntax with Git pre-commit hook.

47186.4k1](/packages/botble-git-commit-checker)[guanguans/laravel-soar

SQL optimizer and rewriter for laravel. - laravel 的 SQL 优化器和重写器。

2227.8k](/packages/guanguans-laravel-soar)[spurwork/spectator

Testing helpers for your OpenAPI spec

3021.5k](/packages/spurwork-spectator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
