Search code examples
phpbehatmink

How to check for disabled attribute using behat mink extention?


I have one scenario in my functionality, where i wanted to write script if checkbox has disabled property then return true.

<input type="checkbox" class="checkbox-click" id="#checkbox-2" name="testcheck" value="where to go" disabled="disabled">

Following is the custom one which i was trying but not succeed:

    /**
     * check for is disabled or not
     *
     * @Then /^I check for is disabled "([^"]*)"$/
     */
    public function isDisabled($selector)
    {
        $session = $this->getSession();
        $element = $session->getPage()->find(
            'xpath',
            $session->getSelectorsHandler()->selectorToXpath('css', $selector) // just changed xpath to css
        );

        $return = $element->getAttribute('disabled');    
    }

I was getting Fatal error : getAttribute calling on nonobject. This is not perfect code but i just given here for reference.


Solution

  • This happens because you don't handle the error. Find method returns the object if the element is found, else it will return null and using getAttribute on null results in fatal exception since is not an object.

    You should check if null and if yes then throw an exception.

    You don't need to use selector to xpath. Also you don't throw any error if the attribute is not found.

    As a validation you could use the method hasAttribute() on the element and throw exception by case. You don't Another thing you could do is to use a conditional wait.