如何让 Behat 查找特定文本的出现?

How to make Behat look for occurences of a specific text?

我想创建一个函数,让 Behat 解析我的 HTML 并告诉我他找到特定文本的次数。我找到了无数种方法,但由于我想重用这个概念,我不能给他一个具体的 div class 在哪里可以找到它,因为它可能在 div.

这是我目前所做的

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());
  }
}

这有点乱,但我会在它工作后整理所有这些。到目前为止,使用这段代码,我得到了 19 个元素,它们是我要检查的页面内每个 div 包含的每个文本。在某种程度上,我有可能实现我的目标,但我想要的是直接在 $result 内获得我需要的东西(我的两次出现)。但是,看起来我在 sprintf() 函数上做错了什么。

有没有办法让 Behat 查找特定文本?

提前致谢

使用 XPath 匹配包含任何类型的元素而不是 css

例如:

$text = 'my text';
findAll('xpath', "//*[contains(text(), '$text')]");

第二种选择是使用正则表达式。我推荐第一个。