pestphp / pest

Pest is an elegant PHP testing Framework with a focus on simplicity, meticulously designed to bring back the joy of testing in PHP.
https://pestphp.com
MIT License
9.06k stars 313 forks source link

[2.x] Add `act` higher order method #1144

Open hafezdivandari opened 2 months ago

hafezdivandari commented 2 months ago

What:

Description:

This PR adds new act higher order method, to be able to use higher order assertion with datasets.

Example usage:

it('creates new user')
    ->with(['Nuno Maduro', 'Hafez Divandari'])
    ->act(fn ($name) => $this->postJson('/api/user', ['name' => $name]))
    ->assertStatus(201)
    ->assertJson([
        'created' => true,
    ]);
it('serves for guest user')
    ->with(['/home', '/login'])
    ->act(fn ($uri) => $this->get($uri))
    ->assertGuest('web')
    ->assertSessionHas('message', 'Welcome!')

Even better:

it('restricts access for unauthenticated user')
    ->with('endpoints')
    ->act(jsonAsGuest(...))
    ->assertUnauthorized()
    ->assertExactJson(['message' => 'Unauthenticated.']);

// dataset
dataset('endpoints', [
    'index'   => ['GET', '/api/projects'],
    'store'   => ['POST', '/api/projects'],
    'show'    => ['GET', '/api/projects/1'],
    'update'  => ['PUT', '/api/projects/1'],
    'destroy' => ['DELETE', '/api/projects/1'],
]);

// tests/Pest.php
function jsonAsGuest(...$args): TestResponse
{
    return test()->json(...$args);
}

Naming:

I chose act because of Arrange-Act-Assert Pattern. Please let me know if you have any better suggestion. e.g value, does, exec, for, after?