问题描述
我正在使用 Cocoon gem 在 Rails 中构建嵌套表单.这个 gem 为每个重复的表单元素分配一个随机数,以区分它们.
I am using the Cocoon gem to build a nested form in Rails. This gem assigns a random number to each duplicated form element in order to distinguish between them.
例如:
id="challenge_events_attributes_1464333427019_event_time_3i"
其中1464333427019"是一个随机数.
Where '1464333427019' is a random number.
我已经尝试了各种迭代:
I have tried various iterations of this:
x = page.all(:xpath, '//input[contains("challenges_events_attributes")]')
puts "X: #{x.inspect}"
假设我在一个页面上有多个元素,我如何使用 Capybara(可能使用 xpath)定位这些元素,然后为它们赋值?
Assuming I have multiple elements on a page, how can I target these elements with Capybara (perhaps using xpath), and then assign values to them?
推荐答案
不需要使用 xpath,CSS 属性以选择器开头就可以了
There is no need to use xpath, the CSS attribute starts with selector will work fine for this
page.all('input[id^="challenges_events_attributes_"]').each do |el|
el.set('whatever value you want to set')
end
如果你也需要它来匹配 id 的结尾,你可以结合属性以选择器结尾 page.all('input[id^="challenges_events_attributes_"][id$="_event_time_3i"]')
等
if you need it to match the end of the id too you can combine with the attribute ends with selector page.all('input[id^="challenges_events_attributes_"][id$="_event_time_3i"]')
etc.
这篇关于Capybara 匹配元素 id 与正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!