Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Cucumber steps for selecting time and date (using Capybara)
require "xpath" # XPath is a separate gem now
module Cucumber
module Rails
module CapybaraSelectDatesAndTimes
def select_date(field, options = {})
date = Date.parse(options[:with])
selector = %Q{.//fieldset[contains(./legend, "#{field}")]}
within(:xpath, selector) do
find(:xpath, '//select[contains(@id, "_1i")]').find(:xpath, ::XPath::HTML.option(date.year.to_s)).select_option
find(:xpath, '//select[contains(@id, "_2i")]').find(:xpath, ::XPath::HTML.option(date.strftime('%B').to_s)).select_option
find(:xpath, '//select[contains(@id, "_3i")]').find(:xpath, ::XPath::HTML.option(date.day.to_s)).select_option
end
end
def select_time(field, options = {})
time = Time.parse(options[:with])
selector = %Q{.//fieldset[contains(./legend, "#{field}")]}
within(:xpath, selector) do
find(:xpath, '//select[contains(@id, "_4i")]').find(:xpath, ::XPath::HTML.option(time.hour.to_s.rjust(2,'0'))).select_option
find(:xpath, '//select[contains(@id, "_5i")]').find(:xpath, ::XPath::HTML.option(time.min.to_s.rjust(2,'0'))).select_option
end
end
def select_datetime(field, options = {})
select_date(field, options)
select_time(field, options)
end
end
end
end
World(Cucumber::Rails::CapybaraSelectDatesAndTimes)
When /^(?:|I )select "([^\"]*)" as the "([^\"]*)" time$/ do |time, selector|
select_time(selector, :with => time)
end
When /^(?:|I )select "([^\"]*)" as the "([^\"]*)" date$/ do |date, selector|
select_date(selector, :with => date)
end
When /^(?:|I )select "([^\"]*)" as the "([^\"]*)" date and time$/ do |datetime, selector|
select_datetime(selector, :with => datetime)
end

Nice idea! Thx for sharing!

amiel commented Mar 7, 2012

I made an update, took me a while to figure out that //select was going back to root, so wasn't actually within the "field".

https://gist.github.com/1990208

The basic difference is something like this for each line with //select

-          find(:xpath, '//select[contains(@id, "_2i")]').find(:xpath, ::XPath::HTML.option(date.strftime('%B').to_s)).select_option
+          find(:xpath, './/select[contains(@id, "_2i")]').find(:xpath, ::XPath::HTML.option(date.strftime('%B').to_s)).select_option

Thank you amiel, you saved me hours of debuggin (already lost one D= )

mad props - I saw this in Cucumber-Rails - very yay!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment