16/01/2015 - BEHAT
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.
Make sure you installed "coduo/php-matcher": "1.1.6"
with composer.
/**
* @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));
}
}
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@
"""
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.");
}
}
}
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