Capybara writes text variations to an array

I would like to put the dropdown options in an array mainly in capybara. After the process, I expect that you will have a string of lines containing all the options for the drop-down list. I tried the code below, but the length of my array remains 1 no matter what the number of options is.

periods = Array.new() periods = all('#MainContent_dd') print periods.length 
+6
source share
2 answers

The problem is that all('#MainContent_dd') returns all elements with the identifier MainContent_dd . Assuming this is your drop-down list and the identifiers are unique, it is expected that periods.length is 1 (i.e. periods is a select list).

What you want to do is get the option elements instead of the select element.

Assuming your html is:

 <select id="MainContent_dd"> <option>Option A</option> <option>Option B</option> <option>Option C</option> </select> 

Then you can do:

  periods = find('#MainContent_dd').all('option').collect(&:text) p periods.length #=> 3 p periods #=> ["Option A", "Option B", "Option C"] 

What it is:

  • find('#MainContent_dd') - finds the list of choices you want to get from
  • all('option') - Gets all option elements in the select list
  • collect(&:text) - collects the text of each parameter and returns it as an array
+22
source

The @JustinCo answer has a problem if the driver used is not working fast: Capybara will make a driver request for each text call. Therefore, if select contains 200 elements, Capybara will make a 201 request to the browser instead of 1, which can be slow.

I suggest you do this using a single request with Javascript:

 periods = page.execute_script("options = document.querySelectorAll('#MainContent_dd > option'); texts=[]; for (i=0; i<options.length; i++) texts.push(options[i].textContent); return texts") 

or (shorter version with jQuery):

 periods = page.evaluate_script("$('#MainContent_dd').map(function() { return $(this).text() }).get()") 
+2
source

All Articles