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

freekmurze's avatar

How to use Session in phpspec

I'm trying to test a very simple class with phpspec.

Some methods of the class that should be tested

    /**
     * Set the current order id
     *
     * @param $orderId
     */
    public function setCurrentOrderId($orderId)
    {
        $this->session->set($this->sessionVariableName, $orderId);

        return $this;
    }

    /**
     * Get the current order id
     *
     * @return mixed
     */
    public function getCurrentOrderId()
    {
        return $this->session->get($this->sessionVariableName);
    }

and a piece of the test

use Illuminate\Session\Store;


class CheckoutSpec extends ObjectBehavior
{
    function let(Store $session)
    {
        $this->beConstructedWith($session);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Spatie\Checkout\Checkout');
    }

    function it_stores_an_orderId()
    {
        $this->setCurrentOrderId('testvalue');

        $this->getCurrentOrderId()->shouldReturn('testvalue');

    }
}

Unfortunately the test fails on it_stores_an_orderId with error expected "testvalue", but got null.

When the methods setCurrentOrderId and getCurrentOrderId are used in artisan's tinker they work just fine.

It seems that in my test environment there something wrong with the setup of the session.

How can this problem be solved?

0 likes
0 replies

Please or to participate in this conversation.