byCoder
byCoder

Reputation: 9184

Select value via index using watir and ruby

I have such code:

total_terms = @driver.select_list(:name => 'ctl00$cp$cbRodzajUslugi').length
    if (1...5).include?(total_terms)
      @driver.select_list(:name => 'ctl00$cp$cbRodzajUslugi').option(:index, total_terms).select
    else
      @driver.select_list(:name => 'ctl00$cp$cbRodzajUslugi').option(:index, (total_terms-2)).select
    end

and I am trying to select some value via index. First, I calculate how long my select_list is, and then I select. But in the browser, I see that nothing is selected. What did I do wrong?

Upvotes: 1

Views: 1832

Answers (1)

Justin Ko
Justin Ko

Reputation: 46836

Your code is probably throwing exceptions.

Select lists do not have a method length

The line

@driver.select_list(:name => 'ctl00$cp$cbRodzajUslugi').length

is not valid since select lists do not have a method length. Assuming you want the number of options, need to add the options method to get a collection of options in the select list:

@driver.select_list(:name => 'ctl00$cp$cbRodzajUslugi').options.length   

5 or less options selects non-existent option

The line

if (1...5).include?(total_terms)
  @driver.select_list(:name => 'ctl00$cp$cbRodzajUslugi').option(:index, total_terms).select

will throw an exception due to there being nothing at the specified index. The :index locator is 0-based - ie 0 means the first option, 1 means the second option, etc. This means that when there are two options, you will try to select :index => 2, which does not exist. You need to subtract 1:

if (1...5).include?(total_terms)
  @driver.select_list(:name => 'ctl00$cp$cbRodzajUslugi').option(:index, total_terms-1).select

Upvotes: 3

Related Questions