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.12k stars 319 forks source link

[3.x] Add a `test()->after()` helper to create test-specific teardown callbacks #1061

Closed caendesilva closed 5 months ago

caendesilva commented 6 months ago

Abstract

Adds a chainable helper to add a teardown closure specific to the test function, something that has gotten great response on Twitter so far. https://twitter.com/CodeWithCaen/status/1745752831385055626/photo/1

Targets v3, as requested by Nuno on Twitter.

What:

Description:

This feature makes it really easy to create teardown logic specific to a single test function, by chaining the new ->after() method to the test setup.

test('file parsing', function () {
    touch('example.txt');

    expect(Parser::parse('example.txt'))->toBe('foo');
})->after(function () {
    // This closure gets called regardless of the test outcome
    unlink('example.txt');
});

This is really useful for cleaning up after an impure test, or to clear a service container, but you only need it for a single test function. Of course these things could be done at the end of a test within its main function body, but if the test fails the cleanup wouldn't be executed. This solves that as the closure gets executed regardless of the test outcome. It also makes the code cleaner by keeping cleanup logic out of the actual test declaration.

Implementation:

As this is my first PR to Pest, I'm not fully familiar with the internals of the framework, so I opted for what I after looking through the related code found to be the simplest implementation and tried to match the coding style of the related code. Upon code review I'm more than happy to adjust the implementation to fit the codebase better, if necessary.

Future features:

This could of course be enhanced by allowing things like dependency injection for the after closure, but I wanted to keep the initial feature as light as possible. I could also see the use for adding a before helper for test setups, however I think the after helper has the broadest use case.

devajmeireles commented 6 months ago

LGTM. Thanks!

nunomaduro commented 5 months ago

This feature cannot be coded this way. I can see, even without testing, that this won't work with only or filtering. I will handle this one myself on the 3.x branch. Thanks tho!

caendesilva commented 5 months ago

This feature cannot be coded this way. I can see, even without testing, that this won't work with only or filtering. I will handle this one myself on the 3.x branch. Thanks tho!

Okay cool! Feel free to add me as a co-author of the PR if you are able to build upon this :)