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

后端 未结 11 1506
梦如初夏
梦如初夏 2020-12-05 10:27

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.t         


        
11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 11:07

    In my particular situation, I'm adding potentially multiple date select fields to the page with accepts_nested_attributes_for functionality. This means, I'm not sure what the full id or name of the fields are going to be.

    Here's the solution I came up with in case it helps anyone else Googling this:

    I'm wrapping the date select field in a container div with a class:

    <%= f.date_select :date_of_birth %>

    Then in my feature spec:

    within '.date-of-birth-container' do
      find("option[value='1']", text: 'January').select_option
      find("option[value='1']", text: '1').select_option
      find("option[value='1955']").select_option
    end
    

    Here's a helper method I wrote for it:

    def select_date_within_css_selector(date, css_selector)
      month_name = Date::MONTHNAMES.fetch(date.month)
      within css_selector do
        find("option[value='#{date.month}']", text: month_name).select_option
        find("option[value='#{date.day}']", text: date.day.to_s).select_option
        find("option[value='#{date.year}']").select_option
      end
    end
    

    Then using the helper:

    select_date_within_css_selector(Date.new(1955, 1, 1), '.date-of-birth-container')
    

提交回复
热议问题