Search code examples
htmlbehat

Fill data in input field whose parent div has class form in behat


I want to fill data input field whose is the child of the div whose class is form in behat

<div class="form">
    <form method="post" action="abc" class="redeem-form">
        <span></span>
        <input type="text" value="Voucher Code" id="voucher-code" name="vocuher_code">
    </form>
</div>

Feature file is :

And I filled in "voucher-code" with "7f2904204489727e" element

feature context file :

/**
 * @When /^(?:|I )filled in "(?P<field>(?:[^"]|\\")*)" with "(?P<value>(?:[^"]|\\")*)" element$/

 */
public function fillField($field, $values)
{
    $field = $this->fixStepArgument($field);
    $value = $this->fixStepArgument($value);
    $element = $this->getSession()->getPage()->find('xpath','//div[@class="form"]//input[@id="'.$field.'"]');
    $this->getSession()->getPage()->fillField($element, $value);
}

Solution

  • If you want to select based on parent then you need to use a css/xpath selector.

    Your css would be:

    div.form #voucher-code
    

    Or XPath

    //div[@class='form']//input[@id='voucher-code']
    

    You can remove fixStepArgument lines. Your method should be something like:

        /**
         * @When /^I fill "(?P[^"]*)" with "(?P[^"]*)"$/
         */
        public function fillWith($selector, $text)
        {
            $element = $this->getSession()->getPage()->find('css', $selector);
            if($element === null){
                throw new Exception("Element $selector not found");
            }else{
                $element->setValue($text);
            }
        }
    

    You should avoid using hard-coded values like //div[@class="form"]//input in your step implementation, this will reduce the usability to only elements that are from div with the class form.