Skip to content

Instantly share code, notes, and snippets.

@lbspen
Created May 29, 2013 23:11
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save lbspen/5674563 to your computer and use it in GitHub Desktop.
Save lbspen/5674563 to your computer and use it in GitHub Desktop.
Select date and time for capybara-rspec from rails forms
def select_date(date, options = {})
field = options[:from]
base_id = find(:xpath, ".//label[contains(.,'#{field}')]")[:for]
year, month, day = date.split(',')
select year, :from => "#{base_id}_1i"
select month, :from => "#{base_id}_2i"
select day, :from => "#{base_id}_3i"
end
def select_time(hour, minute, options = {})
field = options[:from]
base_id = find(:xpath, ".//label[contains(.,'#{field}')]")[:for]
select hour, :from => "#{base_id}_4i"
select minute, :from => "#{base_id}_5i"
end
@lbspen
Copy link
Author

lbspen commented Jun 1, 2013

There is some Rails magic that happens when using the date and time form helpers that makes it non-trivial to test. These methods allow Capybara to set values for date_select and time_select components. I got select_date from Stack Overflow and modified it to create select_time.

For both of these, make sure that the text in the date and time strings is exactly what appears in the option values.

select_date("2013,December,7", :from => "Birthday")
select_time("02 PM", "00", :from => "Start time")

@ClayShentrup
Copy link

  def select_date(date, from:)
    label_el = find('label', text: from)
    id = label_el['for']
    select(date.year, from: "#{id}_1i")
    select(date.strftime("%B"), from: "#{id}_2i")
    select(date.day, from: "#{id}_3i")
  end

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