Select a date in a DatePicker with Selenium WebDriver

How to use Selenium WebDriver to select a date in a date picker

Test Case 1: Select tomorrow’s date (Simple)

require 'active_support/all'
Date.today
Date.today.advance(:days => 1) # tomorrow
Date.today.next_week
Date.today.strftime("%m/%d/%Y") #=> 12/17/2022 if today is 2022-12-17
driver.find_element(:name, "date").click
# calculate the day tomorrow
date_tomorrow = Date.today.advance(:days => 1)
day_tomorrow = date_tomorrow.strftime("%d")

# click the day on the date picker
driver.find_element(:xpath, "//ul[@data-view='days']/li[text()=#{day_tomorrow}]").click
driver.find_element(:tag_name, "body").click
result = driver.find_element(:name, "date")["value"]
expect(result).to eq(date_tomorrow.strftime("%m/%d/%Y"))

Test Case 2: Select tomorrow’s date (edge cases)

# force tomorrow's date to be the first day of the month
date_tomorrow = Date.today.end_of_month.tomorrow

# edge case, end of the month
if date_tomorrow.month != Date.today.month
driver.find_element(:xpath, "//ul/li[@data-view='month next']").click
end
Test Execution in TestWise, pass!
load File.dirname(__FILE__) + "/../test_helper.rb"
require "active_support/all"

describe "Date Picker" do
include TestHelper

before(:all) do
# browser_type, browser_options, site_url are defined in test_helper.rb
@driver = $driver = Selenium::WebDriver.for(browser_type, browser_options)
driver.manage().window().resize_to(1280, 720)
driver.get("https://fengyuanchen.github.io/datepicker/")
end

after(:all) do
driver.quit unless debugging?
end

it "Select tomorrow's date in datepicker" do
driver.find_element(:name, "date").click
date_tomorrow = Date.today.tomorrow
# if month changes
if date_tomorrow.month != Date.today.month
driver.find_element(:xpath, "//ul/li[@data-view='month next']").click
end
day_tomorrow = date_tomorrow.day
driver.find_element(:xpath, "//ul[@data-view='days']/li[text()=#{day_tomorrow}]").click

driver.find_element(:tag_name, "body").click
result = driver.find_element(:name, "date")["value"]
expect(result).to eq(date_tomorrow.strftime("%m/%d/%Y"))
end
end

--

--

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