Search code examples
symfonybehat

Behat issue with testing response


I'm really stuck with testing a response with Behat. The rule like 'Then the response should be equal to' is not triggered, while it's present in vendor/behatch/contexts/src/Context/RestContext.php. Also, we can see other definitions like Behatch\Context\RestContext::theHeaderShouldBeEqualTo() are detected and working automatically just fine. What is the issue with response then?

Feature: Ping feature

  Scenario: Testing ping                                           # features/ping.feature:2
    When I add "Content-Type" header equal to "application/json"        # Behatch\Context\RestContext::iAddHeaderEqualTo()
    And I add "Accept" header equal to "application/json"               # Behatch\Context\RestContext::iAddHeaderEqualTo()
    And I send a "GET" request to "/ping"                               # Behatch\Context\RestContext::iSendARequestTo()
    Then the response status code should be 200                         # Behat\MinkExtension\Context\MinkContext::assertResponseStatus()
    And the response should be in JSON                                  # Behatch\Context\JsonContext::theResponseShouldBeInJson()
    And the header "Content-Type" should be equal to "application/json" # Behatch\Context\RestContext::theHeaderShouldBeEqualTo()
    Then the response should be equal to "pong"

1 scenario (1 undefined)
7 steps (6 passed, 1 undefined)

Behatch\Context\RestContext::theResponseShouldBeEqualTo()

/**
 * Checks, whether the response content is equal to given text
 *
 * @Then the response should be equal to
 * @Then the response should be equal to:
 */
public function theResponseShouldBeEqualTo(PyStringNode $expected)
{
    $expected = str_replace('\\"', '"', $expected);
    $actual   = $this->request->getContent();
    $message = "Actual response is '$actual', but expected '$expected'";
    $this->assertEquals($expected, $actual, $message);
}

Solution

  • Try providing the response data as a text block like this:

    Then the response should be equal to:
        """
        pong
        """
    

    The triple quotes mark a text block, aka PyStringNode. You provide your data as scalar string. Seems odd, but that's how Behat parses this input. It is similar to how Behat will handle markdown tables as TableNode.