如何检查复选框是否被选中 capybara Rspec

How to check whether the check box is checked or not capybara Rspec

检查

<div class="checkbox">
    <input id="yes_1212" class="check_uncheck" type="checkbox" value="true" name="yes" checked="checked">
    <label></label>
    </div>

取消勾选

 <div class="checkbox ">
    <input id="allow__100" class="check_uncheck" type="checkbox" value="false" name="Allow">
    <label></label>
    </div>

如何检查复选框是否被选中

有多种方法,具体取决于您要执行的操作 - 如果您已经找到该元素并且只想知道它是否经过检查,您可以执行类似

的操作
element = find('#yes_1212')
...
element.checked?

如果您试图断言该框在页面上并且 checked/unchecked 您可以这样做

expect(page).to have_field('yes_1212', checked: true) # checked: false or unchecked: true for not checked

expect(page).to have_checked_field('yes_1212')  # or have_unchecked_field

如果您想要一个布尔值响应并且还没有对元素的引用

page.has_field?('allow__100', unchecked: true)
page.has_unchecked_field?('allow_100')

在所有情况下,如果出于样式原因输入元素实际上是 non-visible,您可以传递 visible: false

<input id="allow__100" class="check_uncheck" type="checkbox" value="false" name="Allow">    

对于输入类型复选框

 page.find(:css,
                      "input#allow__100", visible: false
                    ).should_not be_checked

'expect' 语法:

expect(page.find("input#yes_1212")).to be_checked

expect(page.find("input#yes_1212")).not_to be_checked

有两种方法可以获取复选框的状态。 在代码中你可以看到 find(locator_strategy, locator_xpath 这里 locator_strategy 是如果你通过 :xpath:css 搜索定位器并且第二个参数是 locator_xpath 这是定位器写的在定义第一个参数的方式中。

所以这里的第一种方法是您可以分配找到的元素,然后使用 element.checked? 获取复选框的状态,无论是否选中。这将 return truefalse

def method_name
 element = find(locator strategy, locator_xpath)
 return element.checked?
end

或者,第二种方法,我认为这是更好的方法并且消耗更少的代码行。

def method_name
 return find(locator strategy, locator_xpath).checked?
end