找到一个没有id的元素进行Capybara测试

时间:2016-10-21 11:19:31

标签: ruby-on-rails ruby rspec capybara

我在表单中有多个电子邮件字段。他们都没有故意对他们有身份证明。如果他们没有id,我如何区分测试中的每个元素?为清晰起见,我会展示代码。

TEST

 it "sends an invitation to multiple users" do
  click_on "Invite"

  click_link "Invite Another Team Member"

  fill_in "", with: "user@example.com"
  fill_in "", with: "user2@example.com"

  expect { click_button "Invite" }
    .to change(ActionMailer::Base.deliveries, :count).by(1)
    .and change(Invitation, :count).by(2)

  expect(current_path).to eq(account_users_path)
  expect(page).to have_content("user@example.com")
  expect(page).to have_content("user2@example.com")
end

这实际上创建了一个对象,即底部字段。我怎样才能给文本字段个性化?

FORM

    <%= form_tag account_invitations_url do %>

    <label class="email-label">
      <%= email_field_tag "emails[]", "", placeholder: "Email Address", data: { invitation_modal_email: "" }, id: "" %>
    </label>
    <%= link_to '✚ Invite Another Team Member', "#email", data: { invitation_modal_add: "" }  %>

    <div class="form-actions invitation">
      <span class="button-text"><%= link_to 'Cancel', account_users_path %></span>
      <%= submit_tag "Invite", class: "button button--invitation" %>
    </div>

  <% end %>

##浏览器HTML

enter image description here

1 个答案:

答案 0 :(得分:2)

我认为您可以使用Capybara的方法all来查找具有相同名称的所有元素:

emails = ["user@example.com", "user2@example.com"]
all('input[name="emails[]"]').each_with_index do |field, i|
  field.set(emails[i])
end

或者:

all('input[name="emails[]"]')[0].set("user@example.com")
all('input[name="emails[]"]')[1].set("user2@example.com")