Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cdvillard's avatar

A RedirectResponse session is persisting, causing other tests to fail.

I'm writing multiple test functions for a single method that includes two conditionals for a login. The first checks if user credentials are bad, and the second checks for an empty passport object. If either of these fails, they return the result of redirect()->back()->with()->('errorMessage', '...'), each with their own custom message.

For a reason I can't seem to grok (I'm new to phpUnit and PHP in general), I'm unable to get one of two tests on this method to pass because whichever conditional is tested first will have its error message persist to the next test.


    public function testCannotLogin_userCredentialsAreBad()
    {
        ...

        $actualResults = $this->controller->login($this->request);

        $this->assertInstanceOf(RedirectResponse::class, $actualResults);
        $this->assertEquals(
            "Yikes. That didn't seem to work. Give it another shot.",
            $actualResults->getSession()->get('errorMessage')
        );
    }

    public function testCannotLogin_passportIsEmpty()
    {
        ...

        $actualResults = $this->controller->login($this->request);

        $this->assertInstanceOf(RedirectResponse::class, $actualResults);
        $this->assertEquals(
            "Something went wrong on our end.",
            $actualResults->getSession()->get('errorMessage')
        );
    }

The subsequent error message always comes out:

PHPUnit 8.5.8 by Sebastian Bergmann and contributors.

.F........                                                        10 / 10 (100%)

Time: 1.5 seconds, Memory: 32.00 MB

There was 1 failure:

1) Tests\AuthControllerTest::testCannotLogin_passportIsEmpty
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-"Something went wrong on our end."
+"Yikes. That didn't seem to work. Give it another shot."

I've tried to run session()->flush() and session()->forget('errorMessage') in setUp() and tearDown() in a number of ways to no avail. The same error message keeps appearing. I've also tried a number of different ways to reassign the cookie, but no luck. I'd appreciate getting pointed in the right direction. Thanks.

0 likes
0 replies

Please or to participate in this conversation.