How to select date from a select box using Capybara in Rails 3?

Aleksandr Shvalev picture Aleksandr Shvalev · Jul 18, 2011 · Viewed 21.5k times · Source

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

Answer

Markus Hartmair picture Markus Hartmair · Feb 22, 2012

Had the same problem. I googled at lot and solved it this way:

  1. 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
    
  2. 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 :)