Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
girardotcl opened this issue Feb 28, 2024 · 2 comments
Open
Labels

Comments

@girardotcl
Copy link

girardotcl commented Feb 28, 2024

🧑‍🏭 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

@girardotcl girardotcl added the bug label Feb 28, 2024
@rutek
Copy link

rutek commented Mar 8, 2024

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
Copy link
Author

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

May I still hope an "official" answer ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants