I'm writing a spec for a controller in Rails 3 project using RSpec and Capybara, and I want to select current date from a select box. I tried:
select Date.today, :from => 'Date of birth'
but the spec fails and I get error:
Failure/Error: select Date.today, :from => 'Date of birth' NoMethodError: undefined method `to_xpath' for Mon, 18 Jul 2011:Date
How to fix it?
P.S. In view file I use simple_form_for tag and the select box is generated by code:
f.input :date_of_birth
Had the same problem. I googled at lot and solved it this way:
Wrote date select macros into /spec/request_macros.rb The select_by_id method is necessary for me, because the month is dependent on the translation
module RequestMacros
def select_by_id(id, options = {})
field = options[:from]
option_xpath = "//*[@id='#{field}']/option[#{id}]"
option_text = find(:xpath, option_xpath).text
select option_text, :from => field
end
def select_date(date, options = {})
field = options[:from]
select date.year.to_s, :from => "#{field}_1i"
select_by_id date.month, :from => "#{field}_2i"
select date.day.to_s, :from => "#{field}_3i"
end
end
Added them to my /spec/spec_helper.rb
config.include RequestMacros, :type => :request
Now in my integration tests in spec/requests i can use
select_date attr[:birthday], :from => "user_birthday"
Thanks to http://jasonneylon.wordpress.com/2011/02/16/selecting-from-a-dropdown-generically-with-capybara/ and https://gist.github.com/558786 :)
You need to specify the exact value as it's in the select menu in html. So if your select has values like "2011/01/01" then you need to write:
select '2011/01/01', :from => 'Date of birth'
Your code fails because you pass a date object.
with credit to Markus Hartmair for an excellent solution, I prefer to use labels as selectors because of improved readability. So my version of his helper module is:
module SelectDateHelper
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
end
call it like this:
select_date "2012,Jan,1", :from => "From date"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With