Skip to content

Error when using immutable method on dependency, then using beConstructedWith() in spec #1448

Open
@toby-griffiths

Description

I am configuring Symfony's immutable HttpClient in the constructor of a service. I have the spec set up to return a new instance of the client in the let() method, which works fine in spec that don't reconfigure the constructor.

However, if I attempt to reconfigure the constructor in an example then I get an error about the return type…

class ApiClientSpec extends ObjectBehavior
{
    public function let(
        HttpClientInterface $initialHttpClient,
        HttpClientInterface $httpClient,
        ResponseInterface $response,
    ): void {
        $this->beConstructedWith('https://api.co', $initialHttpClient);

        $initialHttpClient->withOptions(Argument::type('array'))->willReturn($httpClient);

        $initialHttpClient->request(Argument::in(['GET']), Argument::type('string'))->willReturn($response);

        $response->getContent()->willReturn('[]');
    }


    public function it_is_initializable(): void
    {
        $this->shouldHaveType(ApiClient::class);
    }


    public function it_should_provide_the_base_url_length(HttpClientInterface $initialHttpClient): void
    {
        $this->beConstructedWith('https://api.co', $initialHttpClient);

        $this
            ->getBaseUrlLength()
            ->shouldReturn(14);
    }
}

… results in …

[err:TypeError("Double\HttpClientInterface\HttpClientInterface\P3::withOptions(): Return value must be of type Double\HttpClientInterface\HttpClientInterface\P3, Double\HttpClientInterface\P1 returned")] has been thrown.

… however, if I inject the resulting client into the example, even if it's not used, it works just fine…

    // …

    public function it_should_provide_the_base_url_length(
        HttpClientInterface $initialHttpClient,
        // Keep this here, as without it the example fails with a return type error
        // @see https://github.com/phpspec/phpspec/issues/1448
        HttpClientInterface $httpClient,
    ): void {
        $this->beConstructedWith('https://api.co', $initialHttpClient);

        $this
            ->getBaseUrlLength()
            ->shouldReturn(14);
    }

Is this a known limitation?

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions