Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara how i can fill_in all inputs with the same name?

I have a form with input fields which can be added or removed dynamically. All my inputs are

name='first_name[]'

How i can fill in all my inputs?

like image 500
prosto.vint Avatar asked Sep 10 '13 14:09

prosto.vint


1 Answers

If you are just inputting anything into each input, you can get a collection of all matching elements using all. Then you can iterate over each to input them.

all_matching_inputs = page.all(:fillable_field, 'first_name[]')
all_matching_inputs.each{ |e| e.set('text') }

If you need to input specific ones, then there are a couple of solutions.

If the only thing unique about the input field is their position, they you could find all input fields and then select one by position:

# Set the first match       
page.all(:fillable_field, 'first_name[]').first.set('text')

# Set the third match (note 0-based index)
page.all(:fillable_field, 'first_name[]')[2].set('text')

# Set the last match
page.all(:fillable_field, 'first_name[]').last.set('text')

Alternatively, you could use a css-selector (or xpath selector). However, it is a bit harder to read:

# Set the second match (note 1-based index)
page.find('input[name=first_name\[\]]:nth-of-type(2)').set('text')

It is rare that there is nothing unique about the element (input) you want to find. Usually there is some element around it that is related and unique (ie there must be something else on the page that, as a user, you are using to differentiate it from others).

For example, in the following html:

<div>
    <span>User1</span>
    <input name='first_name[]'>
</div>
<div>
    <span>User2</span>
    <input name='first_name[]'>
</div>

There are two input fields with the same name. However, they can be distinguished based on their related sibling span, which tells the user the input is related to.

In this case, you can find the span, go to the parent div, and then locate the input within the scope of that div. Essentially, this is finding the input based on the user.

page.find('span', :text => 'User2').find(:xpath, '..').fill_in('first_name[]', :with => 'text')
like image 131
Justin Ko Avatar answered Nov 11 '22 01:11

Justin Ko