How to select date from a select box using Capybar

2019-01-14 06:51发布

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

11条回答
一夜七次
2楼-- · 2019-01-14 07:17

Given the following Formtastic code renders Rails default date selector:

= f.input :born_on, end_year: Time.now.year, start_year: 60.years.ago.year

In your spec, break the date into separate calls to each individual select tag:

select '1956', from: 'person_born_on_1i'
select 'July', from: 'person_born_on_2i'
select '9', from: 'person_born_on_3i'

I don't like that this code is so aware of the HTML, but it does work with the versions of gems at this time.

Gems:

  • Capybara 2.1.0
  • Formtastic 2.2.1
  • Rails 3.2.13
  • RSpec 2.13.0
查看更多
迷人小祖宗
3楼-- · 2019-01-14 07:17

The following worked for me, using a date_field:

fill_in "Date", with: DateTime.now.strftime('%m/%d/%Y')
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-14 07:17

It looks like this one has been sufficiently covered, but see Capybara's docs for an official answer. You can select by name, id, or label text.

查看更多
Emotional °昔
5楼-- · 2019-01-14 07:18

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"
查看更多
手持菜刀,她持情操
6楼-- · 2019-01-14 07:18

For Rails 4, in case somebody gets to this question without being limited to Rails 3.

  select '2020',  from: 'field_name_{}_1i'
  select 'January',  from: 'field_name_{}_2i'
  select '1', from: 'field_name_{}_3i'

You can of course extract this to a helper and make it dynamic.

查看更多
登录 后发表回答