capybara / selenium form_tag - 找不到元素

时间:2015-09-11 12:57:11

标签: ruby-on-rails selenium capybara

我有以下表格:

<div class="row search-area" id="test">
  <%= form_tag search_index_path, method: :get do %>
  <div class="small-12 medium-1 large-1 columns search-field">
    <%= label_tag "From", nil, class: "right inline" %>
  </div>
  <div class="small-12 medium-2 large-2 columns search-field">
    <%= text_field_tag(:start_date, params[:start_date], :value => "yyyy-mm-dd", :class => "datepicker") %>
  </div>
  <div class="small-12 medium-1 large-1 columns search-field">
    <%= label_tag "To", nil, class: "right inline" %>
  </div>
  <div class="small-12 medium-2 large-2 columns search-field">
    <%= text_field_tag(:end_date, params[:end_date], :value => "yyyy-mm-dd", :class => "datepicker") %>
  </div>
  <div class="small-12 medium-1 large-1 columns search-field">
    <%= label_tag "Guests", nil, class: "right inline" %>
  </div>
  <div class="small-12 medium-2 large-2 columns search-field">
    <%= number_field(:number_of_guests, params[:number_of_guests], in: 1.0..20.0, step: 1.0) %>
  </div>
  <div class="small-12 medium-3 large-3 columns">
    <%= submit_tag "Search", name: nil, :class => "button" %>
  </div>
  <% end %>
</div>

我正在尝试编写一些功能规范,以确保搜索按预期工作。我对此非常陌生,但在阅读了一些教程后,我最终得到了以下测试:

describe "search form works" do
  context "search", :driver => :selenium do
    it "searches bookings for hosts" do
      visit root_url
      fill_in 'start_date', with: "2015-06-01"
      fill_in 'end_date', with: "2015-06-07"
      select "1", :from => 'number_of_guests'
      click_button 'Search'

      expect(page).to have_content 'Mr Host 5'
    end
  end
end

问题是当我运行测试时出现以下错误:

Failures:

  1) search form works search searches bookings for hosts
     Failure/Error: fill_in 'start_date', with: "2015-06-01"
     Capybara::ElementNotFound:
       Unable to find field "start_date"
     # ./spec/features/search_spec.rb:7:in `block (3 levels) in <top (required)>'

我正在使用的问题form_tag(我读过/看过的所有示例和教程都使用了'form_tag')?

1 个答案:

答案 0 :(得分:0)

从班级&#39; datepicker&#39;中猜测你有你的每个日期字段 - 这些字段是否被转换为某种javascript驱动的日期选择小部件?如果是这样,并且在转换字段后查看页面上的实际html,您很可能会看到名称为&quot; start_date&#39;的输入字段。和&#39; end_date&#39;实际上是隐藏的。 Capybara默认情况下找不到页面上看不到的字段,因为用户无法与它们进行交互。有两个解决方案 - 第一个是告诉Capybara找到隐藏的元素

fill_in 'start_date', visible: false, with: "2015-06-01"

这可以在一些驱动程序中运行,但由于它不再复制用户行为而非常hacky。第二种解决方案是通过调用用户实际必须点击的页面上的元素来#click来复制用户行为,以输入日期。