user3385054
user3385054

Reputation: 43

Find content in specific DIV with Behat/Selenium

I am creating a Behat/Selenium automated test script. I want to create a statement that says:

Given I am on "/"
Then I should see <CONTENT> in <SPECIFIC DIV>

I want to create a function in my FeatureContext.php file that will allow me to verify content (text) exists only within a specified DIV tag. Can someone please point me in the right direction?

Upvotes: 3

Views: 3025

Answers (1)

Ian Bytchek
Ian Bytchek

Reputation: 9085

If you want to be pointed in the right direction, then you should avoid doing things as such – they contradict with Behat ideology. Your scenario describes actions the user performs and assertions that he makes to verify the result as a user who looks at the page, not as a developer who looks into the code. The logic of the last must be done by you behind the scenes. In other words, your step should read more like this:

Given I am on the homepage
Then the page title should read "hello world"
And the user list should contain "john doe"
And the dialogue title should be "foo bar"

If you want the answer to the initial question, then you can do it as such:

/**
 * @Then /^(?:|I )should see "(?P<text>.+)" in the "(?P<selector>\w+)" element$/
 */
public function assertElementText($text, $selector) {
    $page    = $this->getSession()->getPage();
    $element = $page->findAll('css', $selector);

    foreach($this->getSession()->getPage()->findAll() as $element) {
        if (strpos(strtolower($text), strtolower($element->getText()) !== false) {
            return;
        }
    }

    throw Exception("Text '{$text}' is not found in the '{$selector}' element.");
}

And use it like this:

Then I should see "hello world" in the "div#title" element
Then I should see "john doe" in the "ul#users > li" element

Upvotes: 2

Related Questions