Automate Input Range Element in Selenium WebDriver

How to set values in the new HTML5 Range input type

<input id="review-rating" name="review[rating]" type="range" min="1" max="5" step="1">

Naive Approach: Change Value by sending the ‘RIGHT’ key

elem = driver.find_element(:id, "review-rating")
elem.send_keys(:right)

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)
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

Failed with Edit Rating

I used the same modal page for adding and editing review ratings. Naturally, I tried to reuse the ReviewModalPage 's select_review method.

it "edit review" do
# find a course,
course_page.click_edit_review

review_modal_page = ReviewModalPage.new(driver)
review_modal_page.select_review(4)
# ...
end

Alternate Approach: Manually reset the slider

Reset the rating to 1 before setting the rating to the desired value.

def select_rating(the_rating)
5.times { elem.send_keys(:left) }
(the_rating - 1).times do
driver.find_element(:id, "review-rating").send_keys(:right)
end
end

Alternate Approach: Reset the slider

Use clear to reset the value for the slider to default (the middle value).

elem.clear

Faster Approach: Selenium Advanced User Interactions

The problem with sending LEFT and RIGHT keys is that it is slow. Consider a rating element with many steps.

elem = driver.find_element(:id, "review-rating")
elem.clear
driver.action.click_and_hold(elem).move_by(300,0).release.perform()
Selenium::WebDriver::Error::MoveTargetOutOfBoundsError:
move target out of bounds
(Session info: chrome=106.0.5249.119)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store