msmith1114
msmith1114

Reputation: 3229

Capybara/Rspec: Filling out Multiple Radio buttons

I figure there is probably a better way to do this then copy-pasting 100 times.

But essentially I have a form page that has a LOT of radio buttons (95 to be exact). That im using page.find(:xpath) to trigger('click') on.

The Xpath looks a bit like this:

page.find(:xpath, '/html/body/div/div[2]/div/div[2]/form/div[2]/table/tbody/tr[1]/td[2]/div/label').trigger('click')

The TR[x] goes up for each row of radio button options, with the TD[x] being which to choose (1-10)

I really am just needing to pick a random number between 1-10 for each TD, for an automation test (just to make sure it works).

Would some sort of for loop accomplish this? Something like: (Im not familiar with ruby, but this is what I pulled up just from a quick google)

for i in 1..85
   $h = 1 + rand(10)
   page.find(:xpath, '/html/body/div/div[2]/div/div[2]/form/div[2]/table/tbody/tr[i]/td[h]/div/label').trigger('click')
end

Would that work?

edit: Here is the HTML for a Row:

<tr class="all no-rate complete" data-original="2" change-check="false" the-row="17">
<td class="face">
<td class="face">
<td class="face">
<td class="face">
<div class="radio-inline radio-inline--empty">
<input id="set_stuff_17_rating_3" type="radio" name="set[stuff][17][rating]" value="3" data-control="" data-rating="" filter-class="complete">
<label class="integer opt" for="set_stuff_17_rating_3">Number Rating</label>
</div>
</td>
<td class="face">
<td class="face">
<td class="face">

Upvotes: 0

Views: 353

Answers (2)

Thomas Walpole
Thomas Walpole

Reputation: 49880

Given the updated info about the actual structure of the page, something like

page.all("table.table--ratings tbody tr", minimum: 85).each do |row|  
  row.all("td label").sample.click
end

would do what's being asked without the large brittle XPath expression.

Upvotes: 2

Florent B.
Florent B.

Reputation: 42518

You could iterate over each row :

page.all(:xpath, '/html/body/div/div[2]/div/div[2]/form/div[2]/table/tbody/tr').each do |el|
  $h = 1 + rand(10)
  el.find(:xpath, './td[#{h}]/div/label').click
end

Note that you should refactor your XPath to make it more maintainable.

And with the HTML you provided:

page.all(:xpath, "//form//tr[td[@class='face']]").each do |el|
  h = 1 + rand(10)
  el.find(:xpath, "(.//input[@type='radio'])[#{h}]").click
end

Upvotes: 1

Related Questions