Rails Cucumber Capybara ID/班级选择



所以这是我的测试。

When(/^the admin user broadcasts "([^"]*)" to the notification feed$/) do |userBroadcast|
  visit('/broadcasts/new.html')  
  fill_in('.nifty_form', with: userBroadcast)
  click_button('Broadcast')
end

我已经添加到我的new.html.erb中,一个名为" nifty-form"的类

<h1>New broadcast</h1>
<%= form_for(@broadcast) do |f| %>
    <% if @broadcast.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(@broadcast.errors.count, "error") %> prohibited this broadcast from being saved:</h2>
          <ul>
            <% @broadcast.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
          </ul>
        </div>
    <% end %>
    <%= hidden_field_tag 'page', @current_page %>
    <div id="broadcast-area" class="main-input-area">
      <p>
        <%= f.text_area :content, cols: "100%", rows: "10", class: 'nifty-form',
                        title: "Broadcast text goes here", autofocus: 'autofocus'%>
      </p>
      <div id="url-part">
        <%= link_to("Shortens URL",
                    id: "split-arrow",
                    title: "Press this to shorten the URL") %>
        <%= text_field_tag :shorten_url, nil,
                           title: "Enter URL that you wish to shorten",
                           size: "50%" %>
      </div>
      <br/>
      <div id="">
        <%= f.submit 'Broadcast', confirm: 'Do you really want to broadcast?' %> |
        <%= link_to 'Back', broadcasts_path(page: @current_page) %>
      </div>
</div>

但是出于某种原因,我得到了结果:

Unable to find field "nifty_form" (Capybara::ElementNotFound)   

我已经查看了渲染页的来源,如下:

<textarea cols="100%" rows="1o" class="nifty_form" title="Broadcast text goes here" autofocus="autofocus" name="broadcast[content]" id="broadcast_content" style="z-index: auto; position: relative; line-height: normal; font-size: 10.6667px; transition: none; background: transparent !important;" data-gramm="true" data-txt_gramm_id="b763ea7b-2eef-d3c8-b750-a085d2c9ce80" data-gramm_id="b763ea7b-2eef-d3c8-b750-a085d2c9ce80" spellcheck="false" data-gramm_editor="true"></textarea>

所以看到它在渲染页面中具有ID,我决定写一个带有该ID的测试的ID:

When(/^the admin user broadcasts "([^"]*)" to the notification feed$/) do |userBroadcast|
  visit('/broadcasts/new.html')  
  fill_in('#broadcast_content', with: userBroadcast)
end

,但我又一次留下了相同的错误消息

   Unable to find field "broadcast_content" (Capybara::ElementNotFound)

有没有一种方法可以打印出Capybara可以看到的所有Div班级?我该如何调试这个问题?我是否正确地假设Cappybara在单击按钮后遵循链接?会议保持活力?

capybaras fill_in ins foft_in的输入的名称,ID,占位符或标签文本。它不需要CSS选择器。在您的示例中,将转化为

fill_in('broadcast_content', with: userBroadcast)

由于ID为'Broadcast_Content'Not'#broadcast_content'

如果要使用CSS选择器,则需要做

之类的事情
find(:css, '#broadcast_content').set(userBroadcast) # the :css is optional if your default selector type is set to :css

在最新版本的Capybara中,定位器字符串现在是可选的,并且:ID和:类选项,因此我相信您的初始尝试也可以写为

fill_in(class: 'nifty_form', with: userBroadcast)

尽管在页面上通常不是唯一的类,您可能最好坚持使用ID

最新更新