Summer Sale! All accounts are 50% off this week.

Sinnbeck's avatar
Level 102

Phpunit to pest

I am playing around with pest on a non-laravel project. It currently have a protected property defining the site type. This is then used inside the setUp() method to prepare the site

On the the test class

protected $site_name = 'some_site';

On the extended TestCase.

protected function setUp(): void
    {
        $_SESSION = [];

        if (empty($this->site_name)) {
            throw new Exception('Site property not set in test class');
        }

        $this->site = new Site($this->site);

        setupSite($this->site);
    }

Now in pest I cannot figure out how to set that protected variable.. Has anyone had any success with it? I have tried binding it in beforeEach, but that seems to run after setUp

0 likes
4 replies
wingly's avatar

Maybe something like

// tests/Pest.php
uses()->beforeAll(fn () => $this->site_name = 'some_site')

and then on the TestCase

beforeEach(function () {
		$_SESSION = [];

        if (empty($this->site_name)) {
            throw new Exception('Site property not set in test class');
        }

        $this->site = new Site($this->site_name);

        setupSite($this->site);
});
Sinnbeck's avatar
Level 102

@wingly Sadly beforeAll is called before the class is instantiated, meaning that I will just get and error about using $this outside of object context.

mikenewbuild's avatar
Level 22

I believe you could achieve it by creating a Trait and using that instead?

SetSiteName.php

trait SetSiteName
{
    protected $site_name = 'site name';
}

Pest.php

uses(SetSiteName::class)->in(__DIR__);

Then you can access the property in your tests:

beforeEach(function () {
    echo $this->site_name;
});
Sinnbeck's avatar
Level 102

@mikenewbuild I will give this a try, but it sees that I will need to make a trait for every possible combination of properties then.

Please or to participate in this conversation.