Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara match element id with regex

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.

For example:

id="challenge_events_attributes_1464333427019_event_time_3i"

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}"

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?

like image 631
port5432 Avatar asked May 27 '16 07:05

port5432


1 Answers

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

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.

like image 151
Thomas Walpole Avatar answered Oct 23 '22 21:10

Thomas Walpole