Capybara我怎么能填写所有相同名称的输入?

时间:2013-09-10 14:35:59

标签: ruby-on-rails rspec capybara

我有一个包含input字段的表单,可以动态添加或删除。我的所有输入都是

name='first_name[]'

我如何填写所有意见?

1 个答案:

答案 0 :(得分:10)

如果您只是在每个输入中输入任何内容,则可以使用all获取所有匹配元素的集合。然后你可以迭代每个输入它们。

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

如果您需要输入特定的,那么有几个解决方案。

如果输入字段唯一唯一的东西是它们的位置,那么你可以找到所有输入字段,然后按位置选择一个:

# 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')

或者,您可以使用css-selector(或xpath选择器)。但是,阅读起来有点困难:

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

很少有您想要查找的元素(输入)没有任何独特之处。通常在它周围有一些相关和独特的元素(即页面上必须有其他东西,作为用户,你用来区别于其他元素)。

例如,在以下html中:

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

有两个具有相同名称的输入字段。但是,可以根据它们的相关兄弟跨度来区分它们,这会告诉用户输入与之相关。

在这种情况下,您可以找到span,转到父div,然后在该div的范围内找到输入。基本上,这是基于用户找到输入。

page.find('span', :text => 'User2').find(:xpath, '..').fill_in('first_name[]', :with => 'text')