Then the "username" XML element should contain "behat-user"

Submitted by Unifex on

Behat is really useful. I've recently been on a project where we are using it extensively and I don't see myself not including it in every project going forward from here.

I came across a situation that behat couldn't handle out of the box and had to write my first step. The scenario was checking an XML element for a given value. I found that the WebDriver we were using did not handle XML. Some do, some don't. The one we're using didn't.

In our Scenario we had hit a URL that was returning XML. The next step was the following;
Then the "username" XML element should contain "behat-user"

This Step allows checking a given XML element for a given value. The XML I need this for was very basic. If your XML is more complicated this will still be useful as a starting point.

/**
 * @Then the :arg1 XML element should contain :arg2
 */
public function theXmlElementShouldContain($arg1, $arg2)
  {
  $element_found = FALSE;
  $value_found = FALSE;

  // The actual driver does not handle XML. We need to fetch that ourselves.
  $raw_xml = file_get_contents($this->getSession()->getCurrentUrl());
  $xml = new \SimpleXMLElement($raw_xml);
  $data = [];
  foreach ($xml as $k => $v) {
    $data[$k] = (string) $v;
  }
  if (array_key_exists($arg1, $data)) {
    $element_found = TRUE;
    if ($data[$arg1] == $arg2) {
      $value_found = TRUE;
    }
  }

  if (!$element_found) {
    throw new \Exception(t("The XML element, @element, was not found.", [
      '@element' => $arg1,
    ]));
  }

  if (!$value_found) {
    throw new \Exception(t("The XML element, @element, did not contain the value @value.", [
      '@element' => $arg1,
      '@value' => $arg2,
    ]));
  }
}