Search code examples
phpspecconstruct

How to make phpspec evaluate my constructor


public function __construct(RequestSchemaInterface $requestSchema)
{
    $this->schema = $requestSchema->getSchema();
}

When I run phpspec for Builder then $this->schema is always null. In normal call it sets schema. I got let implemented

function let(RequestSchema $requestSchema)
{
    $this->beConstructedWith($requestSchema);
}

How can I test methods of that class if they use $this->schema ?


Solution

  • Your let() method uses a stub to construct the object under test. While this is recommended, it is not required. You can create a real object of type RequestSchema and use it to construct the tested class:

    function let()
    {
        $requestSchema = new RequestSchema();
        $this->beConstructedWith($requestSchema);
    }
    

    Update:

    Regarding the title of your question "How to make phpspec evaluate my constructor": the constructor is executed but, because you use a stub for $requestSchema, the call $requestSchema->getSchema() inside the constructor returns NULL.

    You can prepare the stub to return something else when its method getSchema() is called.

    Try this:

    function let(RequestSchema $requestSchema)
    {
        // Prepare the stub
        $requestSchema->getSchema()->willReturn('something');
    
        // Construct the object under test using the prepare stub
        $this->beConstructedWith($requestSchema);
    
        // Verify the constructor initialized the object properties
        $this->schema->shouldBe('something');
    }