在 behat 的父级 div 具有 class 表单的输入字段中填写数据

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

我想填写 div 的 class 是 form 的子项的数据输入字段

<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>

功能文件是:

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

功能上下文文件:

/**
 * @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);
}

如果你想 select 基于 parent 那么你需要使用 css/xpath select 或者

您的 css 将是:

div.form #voucher-code

或 XPath

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

您可以删除 fixStepArgument 行。 你的方法应该是这样的:

    /**
     * @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);
        }
    }

您应该避免在步骤实施中使用 hard-coded 值,例如 //div[@class="form"]//input,这将降低仅来自 div 和 class form.