Member-only story
Automate Input Range Element in Selenium WebDriver
How to set values in the new HTML5 Range input type

A repost of my daughter’s article with permission. I added a few notes. This is also included in my “How to in Selenium WebDriver” series. You can find more examples like this in my book: Selenium WebDriver Recipes in Ruby.
The input range element is one of the “new” input types in HTML5. It consists of a slider with minimum and maximum values (and steps). Below is an example.
The default is the middle value, in this case, 3 out of the 1–5 range.
<input id="review-rating" name="review[rating]" type="range" min="1" max="5" step="1">
In test automation, we simulate the user dragging to set the desired value in automated test scripts. This article shows how it can be done in Selenium WebDriver (ruby). Here, I want to use the basic Selenium syntax, without JavaScript (i.e. driver.execute_script
).
Naive Approach: Change Value by sending the ‘RIGHT’ key
elem = driver.find_element(:id, "review-rating")
elem.send_keys(:right)
It works, the range is moved to 4.
By the same token, send_keys(:left)
works as well.
Refactor to Page Object Model
I have a habit of refactoring the raw automated test steps based on the Maintainable Test Design. The target test step will be:
review_modal_page.select_rating(5)
This means creating a function select_rating
in ReviewModalPage
:
def select_rating(the_rating)
elem = driver.find_element(:id, "review-rating")
if the_rating >= 3
(the_rating - 3).times do
puts("Move right ...")
driver.find_element(:id, "review-rating").send_keys(:right)
sleep 0.1
end
else
(3 - the_rating).times do
puts("Move left ...")
driver.find_element(:id, "review-rating").send_keys(:left)
sleep 0.1
end
end
end
Some basic coding is there to calculate how many LEFT and RIGHT keys to send to the range element. It worked.