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.48k stars 343 forks source link

[Improvement] Scoped helper functions #1064

Closed jakubtobiasz closed 8 months ago

jakubtobiasz commented 8 months ago

Note: I've looked for a way how to achieve the expected result, but it seems to not be possible or I am missing something.

Description

My idea is to allow creating helper functions (just like you do it in the Pest.php file) inside *Test.php, but scoped. What I mean:

// SomeTest.php
<?php

test('example', function () {
    expect(true)->toBeTrue();
});

function random(): void
{
    echo "test1";
}

// AnotherTest.php
<?php

test('example', function () {
    expect(true)->toBeTrue();
});

function random(): void
{
    echo "test1";
}

Result: ERROR Fatal error: Cannot redeclare random() (previously declared in /app/tests/Feature/ExampleTest.php:9) in /app/tests/Unit/ExampleTest.php on line 9.

Expected result: No error thrown. Each file uses the function declared in it.

Motivation

I personally do like to create createTestSubject methods inside regular PHPUnit tests. In Pest it's harder to achieve it, as I had to create functions with different names, and I could by accident use a function from another test file.

fabio-ivona commented 8 months ago

Wouldn't using a namespace solve your issue?

jakubtobiasz commented 8 months ago

Hi @fabio-ivona 👋🏼,

Considering I want to declare createTestSubject function in every test file, it wouldn't as multiple classes under the same namespace will have that function. Maybe my problem is not common, but I miss more ways to create scoped functions/helpers/custom expectations.

nunomaduro commented 8 months ago

You can simply namespace your test file.