A bit of Behat: clicking on text

So, I’ve been messing about with Behat recently to try some tests of our site. I was given the challenge of testing the ‘Refine By’ functionality of our directory search. I thought it would be easy (it turned out to be, but not until I’d wrapped my head around XPath). Anyway, the refine by options are just bits of text in a label, or even a span in a label:

<ul>
	<li><label><span>Refine Heading</span></label>
		<ul>
			<li><label>Refine criteria</label></li>
		</ul>
	</li>
</ul>

Not great HTML you’ll probably agree, but clicking on the ‘Refine Heading’ or ‘Refine Criteria’ shows and selects criteria with javascript. However, there isn’t an out-of-the-box assertion for this with Behat, so after some fumbling around, I made (most of (some help from General Grecki)) this:


/**
    * Click some text
    *
    * @When /^I click on the text "([^"]*)"$/
    */
    public function iClickOnTheText($text)
    {
        $session = $this->getSession();
        $element = $session->getPage()->find(
            'xpath',
            $session->getSelectorsHandler()->selectorToXpath('xpath', '*//*[text()="'. $text .'"]')
        );
        if (null === $element) {
            throw new \InvalidArgumentException(sprintf('Cannot find text: "%s"', $text));
        }

        $element->click();

    }
Advertisements

One thought on “A bit of Behat: clicking on text

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s