With Behat/Mink, how to match an exact number?

276 views Asked by At

I'm trying to match an exact number for a page element with Behat/Mink.

My test looks like this:

Then the "td.points" element should contain "1"

This matches if td.points is 1 (good), but it also matches if td.points is 10 or 21 (bad).

I tried using a regex like this:

Then the "td.views-field-field-int-repetitions" element should contain "\b1\b"

But the regex wasn't picked up.

I tried to dig through the code and I see that MinkContext has assertElementContains, but I couldn't find anything like AssertElementIs.

What I want is something like

Then the "td.points" element should be exactly "1"

How can I implement this?

EDIT: This is the element contains feature from MinkContext.php:

/**
 * Checks, that element with specified CSS contains specified HTML
 * Example: Then the "body" element should contain "style=\"color:black;\""
 * Example: And the "body" element should contain "style=\"color:black;\""
 *
 * @Then /^the "(?P<element>[^"]*)" element should contain "(?P<value>(?:[^"]|\\")*)"$/
 */
public function assertElementContains($element, $value)
{
    $this->assertSession()->elementContains('css', $element, $this->fixStepArgument($value));
}
2

There are 2 answers

0
lauda On BEST ANSWER

For extracting the number from the step you could use for a number:

the "(.*)" element should contain (\d+)

or for string

the "(.*)" element should contain "(.*)"

or other example for string

the "(.*)" element should contain (.*)

and for asserting depends on how your code is organized, use what you have or you could just do:

if($someActual != $expected)
{
  throw new \Exception("something meaningful");
}
0
Patrick Kenny On

Thanks to @lauda, I was able to write the code I wanted:

  /**
   * @Then the :element element should be exactly :value
   *
   * Checks that the element with the specified CSS is the exact value.
   */
  public function theElementShouldBeExactly($element, $value) {
    $page = $this->getSession()->getPage();
    $element_text = $page->find('css', "$element")->getText();
    if ($element_text === NULL || strlen($element_text < 1)) {
      throw new Exception("The element $element had a NULL value.");
    }
    if ($element_text !== $value) {
      throw new Exception("Element $element_text did not match value $value.");
    }
  }