Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

Sometimes expected result in a scenario can be dynamic so if we use a static value then the tests would fail. To avoid this problem, we can use PHP Matcher.


Composer.json


Make sure you installed "coduo/php-matcher": "1.1.6" with composer.


Controller


/**
* @Route("user")
*/
class UserController extends Controller
{
/**
* @param Request $request
*
* @Route("")
* @Method({"GET"})
*
* @return Response
*/
public function listAction(Request $request)
{
$countries = [
'GB' => 'Great Britain',
'DE' => 'Germany',
'TR' => 'Turkey'
];

return $this->createJsonResponse(array_rand($countries));
}
}

Feature example


For more place holders like @string@, visit link above.


Feature: Handling dynamic results

Scenario: I can handle dynamic response content
Given I am on "/user"
Then the response status code should be 200
And the response should contain dynamic json:
"""
@string@
"""

FeatureContext.php


You can check anything like plain string, json etc. You can use $this->getBrowser()->getLastResponse()->getContent() to get last response as another option.


namespace Application\BackendBundle\Features\Context;

use Behat\Gherkin\Node\PyStringNode;
use Behat\MinkExtension\Context\MinkContext;
use Coduo\PHPMatcher\Factory\SimpleFactory;

class FeatureContext extends MinkContext
{
/**
* Checks that response body contains JSON from PyString.
*
* @param PyStringNode $jsonString
*
* @Then /^(?:the )?response should contain dynamic json:$/
*/
public function theResponseShouldContainDynamicJson(PyStringNode $jsonString)
{
$expectedJson = $jsonString->getRaw();
$responseJson = $this->getSession()->getPage()->getContent();

if (null === $expectedJson) {
throw new \RuntimeException("Can not convert given JSON string to valid JSON format.");
}

$factory = new SimpleFactory();
$matcher = $factory->createMatcher();
$match = $matcher->match($responseJson, $expectedJson);

if ($match !== true) {
throw new \RuntimeException("Expected JSON doesn't match response JSON.");
}
}
}

Result


Inanzzz-MBP:football inanzzz$ bin/behat
Feature: Handling dynamic results

Scenario: I can handle dynamic response content
Given I am on "/user"
Then the response status code should be 200
And the response should contain dynamic json:
"""
@string@
"""

1 scenario (1 passed)
3 steps (3 passed)
0m5.87s