代码之家  ›  专栏  ›  技术社区  ›  Jaeger

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

  •  0
  • Jaeger  · 技术社区  · 7 年前

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

    这就是我目前所做的

    测试功能。特色

    And I should see "CISIA - Arcueil" 2 times
    

    功能上下文。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查找特定的文本?

    提前谢谢你

    1 回复  |  直到 7 年前
        1
  •  3
  •   lauda    7 年前

    使用 XPath 将任何类型的元素与contains而不是 css .

    例如:

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

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