Search code examples
htmlformsseleniumattributesbehat

Select form option by data-name attribute with Behat/Selenium


I have a scenario I am creating for testing a web site using Behat / Selenium. The form elements on the web site use a unique "data-name" attribute. Behat does not recognize that attribute. Any one have a custom step definition I can place in my FeatureContext.php that will allow me to use the "data-name" html attribute with Behat / Selenium?

<select name="select" data-name="state">
        <option value="AL">AL</option>
        ...
        <option value="WY">WY</option>
</select>

The Behat error:

When I select "MD" from "state" FeatureContext::selectOption() Form field with id|name|label|value "state" not found.


Solution

  • The following should work with When I select "MD" in the "state" select.

    /**
     * @When /^(?:|I )select "(?P<option>\w+)" in the "(?P<name>\w+)" select$/
     */
    public function selectState($option, $name) {
        $page          = $this->getSession()->getPage();
        $selectElement = $page->find('xpath', '//select[@data-name = "' . $name . '"]');
    
        $selectElement->selectOption($option);
    }