Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing a radio button from its labels with Capybara

Tags:

capybara

I have a dynamically generated form that looks like this:

Do you like Pizza?
[ ] Yes   [ ] No

The HTML looks like this:

<form>
  <div class="field">
    <label>Do you like Pizza?</label>
    <input
      type="radio" value="true" 
      id="reply_set_replies_attrs_0_pizza_true"
      name="reply_set[replies_attrs][0][pizza]">
    </input>
    <label for="reply_set_replies_attrs_0_pizza_true">Yes<label>
    <input
      type="radio" value="false" 
      id="reply_set_replies_attrs_0_pizza_false"
      name="reply_set[replies_attrs][0][pizza]">
    </input>
    <label for="reply_set_replies_attrs_0_pizza_false">No<label>
  </div>
</form>

I'd like to get check those radio buttons with Capybara. How can I do this? I don't always know the ids of the radio buttons, because there's a few of them and when I also ask about Popcorn and Chicken I don't want to depend on knowing their order.

Is there a way to do something like...

field = find_label("Do you like pizza?").parent('field')
yes = field.find_label('Yes')
yes.click

?

like image 952
user225643 Avatar asked Dec 26 '22 16:12

user225643


2 Answers

Note that when using find, the :text option does a partial text match. Therefore, you could find the div directly:

find('div.field', :text => 'Do you like Pizza?').choose('Yes')

(Also using choose makes radio button selection easier.)

like image 174
Justin Ko Avatar answered May 01 '23 15:05

Justin Ko


not bad!

label = find('label', :text => "Do you like Pizza?")
parent = label.find(:xpath, '..')
parent.find_field("Yes").click
like image 38
user225643 Avatar answered May 01 '23 16:05

user225643