I'm using webrat with cucumber and I would like to test if a radio button is checked already when I am on a page. How can I do that ? I didn't find any step in webrat which can do that.
8 Answers
expect(find_field("radio_button_name")).to be_checked

- 43,526
- 67
- 220
- 351

- 2,115
- 28
- 28
input("#my_box").should be_checked

- 1,191
- 6
- 9
-
Seems this method no longer works. I'm using Capybara 2.4.1. The `find_field` method suggested by @evedovelli did the trick. – Lachlan Cotter Dec 10 '14 at 07:41
-
I would suggest not using "should be_checked" but instead: expect(find_field("my_boxt")).to be_checked – Mar 03 '15 at 19:04
There are cases when you cannot rely on checkboxes having ids or labels or where label text changes. In this case you can use the have_selector
method from webrat.
From my working code (where I do not have ids on checkboxes).
response_body.should have_selector 'input[type=radio][checked=checked][value=information]'
Explanation: test will return true if body of document contains an radio button (input[type=radio]
) which is checked and that has the value "information"

- 106,591
- 44
- 118
- 155
Just changed a web_step checkbox to radio button
Add the following step to web_steps.rb
Then /^the "([^"]*)" radio_button(?: within "([^"]*)")? should be checked$/ do |label, selector|
with_scope(selector) do
field_checked = find_field(label)['checked']
if field_checked.respond_to? :should
field_checked.should be_true
else
assert field_checked
end
end
end
And you can write the following to check whether the given raido button is checked or not
And the "Bacon" radio_button within "div.radio_container" should be checked

- 4,278
- 7
- 46
- 71
You can use the built-in checkbox matcher in web_steps.rb:
And the "Bacon" checkbox should be checked
However, you'll need to have a label on your checkbox that matches the ID of the corresponding checkbox input field. The f.label helper in Rails takes a string to use as the ID in the first argument. You may have to build a string that includes the field name and the checkbox name:
f.label "lunch_#{food_name}, food_name
f.radio_button :lunch, food_name
In any case, use this directive to see that you've got the HTML correct:
Then show me the page

- 71
- 1
- 4
Wrapped Jesper Rønn-Jensen his function + added name which is used by rails:
Then /^I should see that "([^"]*)" is checked from "([^"]*)"$/ do |value, name|
page.should have_selector "input[type='radio'][checked='checked'][value='#{value}'][name='#{name}']"
end

- 1,969
- 3
- 21
- 24
And the "Obvious choice" checkbox should be checked
Although it might be a radio button, but the code will work. It is just checking for a fields labelled with that text.

- 1,299
- 11
- 25
You can use method checked?
on your field
expect(find_field("radio_button_id").checked?).to eq(true)

- 1,104
- 12
- 17