Search code examples
watirwatir-webdriveroptgroup

Specifying an 'optgroup' with watir-webdriver


I've got an HTML page with the following format:

   <select id="name_list">
      <optgroup label="env1">
          <option value="comp1">comp1 details</option>
      </optgroup>
      <optgroup label="env2">
          <option value="comp1">comp1 details</option>
      </optgroup> 
   </select>

And trying to click on the option with value=comp1 which is inside optgroup-env2 specifically. Is there any way to specify this path? Note that both 'options' values are exactly the same under the different 'optgroup' nodes...

Many thanks!


Solution

  • You can locate an optgroup like any other element. Then you can search within that group for your option.

    browser.optgroup(:label =>'env2').option(:value => 'comp1').select
    

    Update - It looks like there is a bug in watir-webdriver that prevents the above from working.

    When creating the locator for the label, watir-webdriver calls the following method:

    def should_use_label_element?
      @selector[:tag_name] != "option"
    end
    

    For the optgroup, this returns false, which means that watir goes and looks for an associated label element (rather than checking the attribute).

    As a temporary workaround, you could use css:

    browser.element(:css => 'optgroup[label="env2"]').option(:value => 'comp1').select
    

    A bug has been created for this issue (see Issue 219).