I'd like to create a function that makes Behat parse my HTML and tell me how many times he finds a specific text. I found countless ways to do so, but since I'd like to reuse the concept, I can't give him a specific div class where to find it since it could be outside of a div.
This is what I did so far
testfeature.feature
And I should see "CISIA - Arcueil" 2 times
FeatureContext.php
public function iShouldSeeTimes($text, $count) {
$element = $this->getSession()->getPage();
$result = $element->findAll('css', sprintf('div:contains("%s")', $text));
if(count($result) == $count && strpos(reset($result)->getText(), $text)) {
return;
}
else {
throw new ExpectationException('"' . $text . '" was supposed to appear ' . $count . ' times, got ' . count($result) . ' instead', $this->getSession());
}
}
This is a bit messy but I'll tidy all of this up once it works. So far, with this code, I get 19 elements, which are every text contained by every div inside the page I want to check. In a way, I have a possibility to get to my goal, but what I'd like is to directly get what I need (my two occurences) inside $result
. However, it looks like I'm doing something wrong with the sprintf()
function.
Is there a way to make Behat look for a specific text?
Thank you in advance
Use XPath
that matches any type of element with contains instead of css
.
For example:
$text = 'my text';
findAll('xpath', "//*[contains(text(), '$text')]");
The second alternative would be to use regular expressions. I recommend the first one.