Behat(+ Mink)检查一些文本后跟一些文本(兄弟元素)

时间:2018-03-01 13:22:01

标签: behat mink

I should see...函数是Behat的基本功能,但我经常发现自己想要在我的场景中编写类似的内容:

Then I should see "Session ID" followed by "3"

这是我在人们可解析的方式中描述内容中彼此相邻的两段文字。也就是说第一个字符串是任何元素的内容,第二个字符串是它的下一个直接兄弟的内容。

这对于检查 label - value 类型布局非常有用:

Screenshot of layout with sibling content

或者,如果我想在列表数据中检查标题 - 单元格值类型布局:

Screenshot of tabulated layout with sibling content

甚至定义标题 - 定义。

显然我可以添加' id'我希望测试的每个元素的属性,但在一个复杂的页面中,内容的许多部分需要测试,这开始感觉我用一次性属性膨胀标记。

1 个答案:

答案 0 :(得分:1)

能够使用......

Then I should see "Session ID" followed by "3"

将以下方法添加到FeatureContext.php文件中:

/**
 * @Then I should see :textA followed by :textB
 */
public function iShouldSeeFollowedBy($textA, $textB)
{
    $content = $this->getSession()->getPage()->getContent();

    // Get rid of stuff between script tags
    $content = $this->removeContentBetweenTags('script', $content);

    // ...and stuff between style tags
    $content = $this->removeContentBetweenTags('style', $content);

    $content = preg_replace('/<[^>]+>/', ' ',$content);

    // Replace line breaks and tabs with a single space character
    $content = preg_replace('/[\n\r\t]+/', ' ',$content);

    $content = preg_replace('/ {2,}/', ' ',$content);

    if (strpos($content,$textA) === false) {
        throw new Exception(sprintf('"%s" was not found in the page', $textA));
    }

    $seeking = $textA . ' ' . $textB;
    if (strpos($content,$textA . ' ' . $textB) === false) {
        // Be helpful by finding the 10 characters that did follow $textA
        preg_match('/' . $textA . ' [^ ]+/',$content,$matches);
        throw new Exception(sprintf('"%s" was not found, found "%s" instead', $seeking, $matches[0]));
    }
}


/**
 * @param string $tagName - The name of the tag, eg. 'script', 'style'
 * @param string $content
 *
 * @return string
 */
private function removeContentBetweenTags($tagName,$content)
{
    $parts = explode('<' . $tagName, $content);

    $keepers = [];

    // We always want to keep the first part
    $keepers[] = $parts[0];

    foreach ($parts as $part) {
        $subparts = explode('</' . $tagName . '>', $part);
        if (count($subparts) > 1) {
            $keepers[] = $subparts[1];
        }
    }

    return implode('', $keepers);
}