Search code examples
rubywatirwatir-classic

How to select particular option in a select list?


I'm trying to select option 2, but first it is selecting 2 then changing to 1.

This is the HTML of the select list:

<select id="IDITForm@additionalVehicleDrivers|1@youngestDriverExperienceVO@id">
  <option style="background-color: rgb(252, 218, 175);" value="-1">Select</option>
  <option value="1">0</option>
  <option value="2">1</option>
  <option value="3">2</option>
  <option value="4">3</option>
  <option value="5">4</option>
  <option value="1000000">5</option>
  <option value="1000001">more than 5</option>
</select>

This is the Watir code for selecting 2:

b.select_list(:id,"IDITForm@additionalVehicleDrivers|1@youngestDriverExperienceVO@id").select "2"

Solution

  • The problem is that you are using Watir-Classic's select method with a parameter that matches both an option's text as well as another option's value.

    If you take a look at the code for the Watir::SelectList#select method:

    def select(item)
      matching_options = []
      perform_action do
        matching_options = matching_items_in_select_list(:text, item) +
          matching_items_in_select_list(:label, item) +
          matching_items_in_select_list(:value, item)
        raise NoValueFoundException, "No option with :text, :label or :value of #{item.inspect} in this select element" if matching_options.empty?
        matching_options.each(&:select)
      end
      first_present_option_value matching_options, :text
    end   
    

    You can see that:

    1. It gets a list of matching options based on text, label and value and
    2. Then for each matching option Watir-Classic selects it.

    For your specific example, this means that

    1. 2 options match the input "2":
      • <option value="2">1</option> matches since its value is "2"
      • <option value="3">2</option> matches since its text is "2"
    2. Watir-Classic is selecting each of these options, in this specific order, which is why you see the dropdown switch to "1" and then "2"

    Given the way the method is written and how your select list is written, you cannot use the select method. While the best choice is to move to Watir (previously Watir-Webdriver), there are workarounds in Watir-Classic.

    Remove the ambiguity by specifically selecting an option based on only the value attribute:

    id = "IDITForm@additionalVehicleDrivers|1@youngestDriverExperienceVO@id"
    b.select_list(:id, id).select_value "3"
    #=> will select <option value="3">2</option>
    

    If you want to stick to selecting by text, directly locate/select the option element:

    id = "IDITForm@additionalVehicleDrivers|1@youngestDriverExperienceVO@id"
    b.select_list(:id, id).option(:text, "2").select
    #=> will select <option value="3">2</option>