使用Behat选中单选按钮

3

我被这个问题困扰了1个小时。实际上,使用Mink选中单选按钮并不难。我已经找到了如何做到这一点。但是,只有当单选按钮在表单标签内时才有效。如果我有

<table>
    <tr>
        <td>
            <input id="payone" type="radio" name="payment[method]" value="payone_today">
            <label for="payone">Vorkasse</label>
        </td>
    </tr>
</table>

无法选中单选按钮,或者我找不到它。有任何想法吗?

4个回答

11

我发现“当我从“名称”选择“值””表单可以用于选择单选按钮。也许你的代码可以使用:“当我从“支付方式[method]”选择“payone_today””。


这个答案对我很有帮助,而且比增加整个额外方法来处理已经存在的东西要简单得多。 - DanielM
1
也适用于我,但如果输入元素带有"display:none"属性,则无法正常工作。 - Reshma

6
我曾经遇到类似的问题并使用了类似的解决方案,但我的具体需求有一个小变化,我认为这可能会有所帮助。
如果你有两个具有相同标签文本的单选按钮会发生什么?当你有多个单选按钮组时,这是完全可能的,上面的解决方案只会在DOM中找到具有该标签的第一个按钮,而您可能希望它是第二个或第三个。
只要每个单选按钮组都在容器内,那么您可以从该容器开始,而不是通过整个DOM进行操作。
我对原始问题和稍微扩展的版本的解决方案都如下所示。
/**
 * @When /^I check the "([^"]*)" radio button$/
 */
public function iCheckTheRadioButton($labelText) {
    $page = $this->getMainContext()->getSession()->getPage();
    foreach ($page->findAll('css', 'label') as $label) {
        if ( $labelText === $label->getText() ) {
            $radioButton = $page->find('css', '#'.$label->getAttribute('for'));
            $radioButton->click();
            return;
        }
    }
    throw new \Exception("Radio button with label {$labelText} not found");
}

/**
 * @When /^I check the "([^"]*)" radio button in "([^"]*)" button group$/
 */
public function iCheckButtonInGroup($labelText, $groupSelector){
    $page = $this->getMainContext()->getSession()->getPage();
    $group = $page->find('css',$groupSelector);
    foreach ($group->findAll('css', 'label') as $label) {
        if ( $labelText === $label->getText() ) {
            $radioButton = $page->find('css', '#'.$label->getAttribute('for'));
            $radioButton->click();
            return;
        }
    }
    throw new \Exception("Radio button with label {$labelText} not found in group {$groupSelector}");
}

我正在尝试在组中检查第二个示例的按钮。 我将父ID设置为groupselector,但它会抛出错误“调用成员函数FindAll”。 - Reshma
我猜测你的组选择器不起作用。你能否发布更多关于选择器是什么,标记看起来像什么的细节? - PCaligari
这很有帮助,因为我有几个页面,每个页面上都有多个“是”和“否”的设置。 - zkent

1
如果您的单选按钮有一个

-1
我发现最简单的代码解决方案是这样的。
/**
 * @Given /^I check the "([^"]*)" radio button with "([^"]*)" value$/
 */
public function iCheckTheRadioButtonWithValue($element, $value)
{
  foreach ($this->getMainContext()->getSession()->getPage()->findAll('css', 'input[type="radio"][name="'. $element .'"]') as $radio) {
    if ($radio->getAttribute('value') == $value) {
      $radio->check();
      return true;
    }
  }
  return false;
}

在这里调用 check() 函数是问题所在。这段代码会抛出错误 cannot tick as it is not a checkbox (radio) - Greg
谢谢您的回答,但我得到的是“您无法选中“条件”,因为它不是复选框(单选框)。” - Bhargav Nanekalva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接