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.07k stars 315 forks source link

To avoid Larastan errors : `test()` is it a correct replacement to `$this` ? #1104

Closed girardotcl closed 2 days ago

girardotcl commented 4 months ago

🧑‍🏭 Context

I have security and code quality needs, i can't simply avoid errors with an ignore line in phpstan.neon like this :

    ignoreErrors:
        -
            message: '#Undefined variable: \$this#'
            path: */Modules/*/Tests/Feature/*
        -
            message: '#Call to an undefined method#'
            path: */Modules/*/Tests/Feature/*

I find the way by replacing all $this with test() :

test('users can access categories edit route', function (User $user) { actingAs($user) ->get(route('admin.category.edit', ['category' => $this->category->id])) ->assertOk(); }) ->with('my user dataset');

// ... other tests


- #### After, without larastan error
```php
beforeEach(fn() => test()->category = Category::factory()->create());

test('users can access categories edit route', function (User $user) {
    actingAs($user)
        ->get(route('admin.category.edit', ['category' => test()->category->id]))
        ->assertOk();
})
->with('my user dataset');

// ... other tests

I made some dd() and check the content, it seems ok.

❓Question

But before review all my test suite, I need a confirmation :

⚠️ Is this a solid and sustainable solution from this package point of view ? ⚠️


Pest Version

2.8.1

PHP Version

8.2.13

Operation System

Windows & MacOS

rutek commented 4 months ago

I'm not Pest expert, but looking at Pest internals, more convinent way to get a current test case instance would be:

$test = TestSuite::getInstance()->test;

If you need this to be typed for PHPStan, you can go with assertion that will make PHPStan narrow $test type if you use phpstan-phpunit extension:

assert($test instanceof TestCase); // class of test case you expect to have
girardotcl commented 3 months ago

Thanks for your advice @rutek , I'll make some improvements.

May I still hope an "official" answer ?

girardotcl commented 2 days ago

pest-plugin-laravel :

/**
 * Set the currently logged in user for the application.
 *
 * @return TestCase
 */
function actingAs(Authenticatable $user, string $driver = null)
{
    return test()->actingAs(...func_get_args());
}

I have my anwser