Search code examples
rubywatiroptgroup

Ruby pick random element from select list with optgroups


i m currently trying to select a random element from a select list, i can map all the options and then pick one randomly , but the problem is the optgroup inside te selector, here is a sample of the html and my code. HML:

<select class="formDY-control" name="destino" id="destino">
<option value="0" style="background-color:#eeeeee">Selecciona Lugar de

 Recogida</option>
<optgroup value="0" label="Aeropuertos">
<option value="LUX01">Luxemburg Aeropuerto</option></optgroup>
<optgroup value="0" label="Todos los Destinos">
<option value="LUX01">Luxemburg Aeropuerto</option>
<option value="LUX02">Luxemburg City Ciudad</option>
</optgroup></select>

And here my code

ciudad = browser.select_list(id: 'destino').options.map(&:value)
ciudad.shift
city = ciudad.sample
browser.select_list(id: 'destino').select(city)

Problem is that the code returns that the selected option (array sample) is not in the select list


Solution

  • Instead of randomly picking an option value, you can pick a random option element. Then you can use it's select method to select that specific option (rather than asking the select list to find the option again):

    ciudad = browser.select_list(id: 'destino').options
    ciudad.shift
    city = ciudad.sample
    city.select