pest
pest copied to clipboard
To avoid Larastan errors : `test()` is it a correct replacement to `$this` ?
🧑🏭 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()
:
-
Before, with Larastan error
beforeEach(fn() => $this->category = Category::factory()->create());
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
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
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
Thanks for your advice @rutek , I'll make some improvements.
May I still hope an "official" answer ?