How To Select from a Dropdown List with Ruby & Watir Webdriver
The Issue
There are multiple ways to go about selecting from a dropdown list; some will work better than others depending on a variety of factors. Let's take a look at an efficient way to select from a dropdown using Ruby & Watir-Webdriver.
The Answer
A common solution is the select command, allowing us to select directly select through a list in one line of code. This will appear as follows:
browser.select_list(:id,"entry_1000001").select "Ruby"
Alternatively, you can click on the list itself in order to pull up the dropdown, and then attempt to click your desired option after. This would appear as such:
#clicking the dropdown browser.select_list(:id,"entry_1000001").click #clicking the option from the opened dropdown browser.option(:text,”Ruby”).click
This allows you to interact with the selected dropdown. To validate that we see the correct options, we can use if logic:
if browser.option(:text,”Ruby”).exists? == false fail "Dropdown option is not available" end
You can apply these assertions as many times as you like to cover just a few options, or validate every selection from a list. These are particularly useful when the list options will change based on an outside variable.
The Code
Lets look at two examples: using the select command to select from a dropdown, and using click on the list, and selecting a different option by using click on the option. We’ll use the Watir Webdriver Demo page: bit.ly/watir-webdriver-demo.
#Option 1: Clicking and Selecting require 'rubygems' require 'watir-webdriver' browser = Watir::Browser.new :chrome browser.goto "bit.ly/watir-webdriver-demo" browser.select_list(:id,"entry_1000001").click browser.option(:text,"Ruby").click puts “Select List Value= #{browser.select_list(:id,”entry_1000001”).value}” browser.select_list(:id,"entry_1000001").send_keys :enter
#Option 2: Setting the value in the drop down require 'rubygems' require 'watir-webdriver' browser = Watir::Browser.new :chrome browser.goto "bit.ly/watir-webdriver-demo" browser.select_list(:id,"entry_1000001").select "Java" puts “Select List Value= #{browser.select_list(:id,”entry_1000001”).value}
The Result
We can save the file (dropdown1.rb) and run it from the command line. Here is a breakdown of the result:
- Browser opens
- Browser navigates to the Watir Webdriver Demo URL
- Selects Ruby from the dropdown by using click the dropdown, then use click on Ruby
- Selects Java directly from dropdown using select_list
Here we have the command line output, displaying our messages for the respective examples:
The Takeaway
You’re now set to take dropdown lists from two different approaches. Practice using both approaches to see how they interact with dropdowns in your test automation.