jerrytom
jerrytom

Reputation: 363

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

CHECK

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

UNCHECK

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

how to check whether the check box is checked or not

Upvotes: 31

Views: 19875

Answers (4)

Sunil Kumar
Sunil Kumar

Reputation: 418

There are two ways of getting the checkbox's status. In the code you can see find(locator_strategy, locator_xpath here locator_strategy is if you are searching the locator by :xpath or :css and the second parameter is locator_xpath which is locator written in the way the first parameter is defined.

So here first way is either you can assign the element you have found and then using element.checked? to get the status of checkbox, whether its checked or not checked. This would return either true or false

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

or, second way, which I feel is better way to proceed and consumes less line of codes.

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

Upvotes: 1

user3114072
user3114072

Reputation:

'expect' syntax:

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

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

Upvotes: 8

jerrytom
jerrytom

Reputation: 363

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

For input type checkbox

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

Upvotes: 1

Thomas Walpole
Thomas Walpole

Reputation: 49880

There are multiple ways depending on exactly what you're trying to do - if you've already found the element and just want to know whether or not it's checked you can do something like

element = find('#yes_1212')
...
element.checked?

If you're trying to assert that the box is on the page and is checked/unchecked you could do

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

or

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

If you want a boolean response and don't already have a reference to the element

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

In all cases if the input element is actually non-visible for styling reasons you can pass visible: false

Upvotes: 46

Related Questions