FriendsOfBehat/SymfonyExtension

Getting different service injected into context

Chrisissorry opened this issue · 2 comments

Hey, thanks for providing this great extension!

One problem I run into is the following:

  • I send SMS to clients using a custom SmsSender service.
  • In my test environment, these are decorated in order to trace which messages are being sent. (TraceableSmsSender)
  • Now, the problem is: The TraceableSmsSender which is used to actually send the mails, is different from the one I get injected into my context. Thus, the messages which were send are not accessible to me in the version I get injected into my context.

Here's my behat.yml.dist:

default:
    suites:
        default:
            contexts:
                - Behat\MinkExtension\Context\MinkContext
                - Behatch\Context\RestContext
                - Behatch\Context\JsonContext
                - App\Tests\Behat\ApiAuthenticationContext
                - App\Tests\Behat\ChargerContext
                - App\Tests\Behat\FixtureContext
                - App\Tests\Behat\MessageContext
                - App\Tests\Behat\SharingContext

    extensions:
        FriendsOfBehat\SymfonyExtension: ~
        Behatch\Extension: ~
        Behat\MinkExtension:
            base_url: "http://example.com/"
            sessions:
                default:
                    symfony: ~

Here is my MessageContext:

<?php
declare(strict_types=1);

namespace App\Tests\Behat;

use App\Service\TraceableSmsSender;
use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\PyStringNode;
use PHPUnit\Framework\TestCase;

class MessageContext implements Context
{
    /**
     * @var TraceableSmsSender
     */
    private $smsSender;
    
    public function __construct(TraceableSmsSender $smsSender)
    {
        $this->smsSender = $smsSender;
    }

    /**
     * @Then a SMS is sent with text:
     */
    public function aSmsIsSentWithText(PyStringNode $text)
    {
        $smsMessages = $this->smsSender->getSentMessages(); // this will be empty

        // assertions
    }
}

My services_test.yaml:

services:
    _defaults:
        autowire: true
        autoconfigure: true

    App\Tests\Behat\:
        resource: '../tests/Behat/*'

    App\Service\TraceableSmsSender:
        decorates: App\Service\SmsSender
        public: true
        shared: true
        # pass the old service as an argument
        arguments: ['@App\Service\TraceableSmsSender.inner']

I determine that they are different like this:

  • dump the spl_object_hash right in the service where it sends the mail (inside TraceableSmsSender)
  • dump the spl_object_hash of the injected service in the message context
    --> They don't match

I would expect the same service to be injected as the service is shared: true.

I think this issue is also related to #86.

pamil commented

I've released v2.1.0-BETA.2 with #116 that should help with it.