Bitwise
Bitwise

Reputation: 8461

Find an element without an id for Capybara testing

I have multiple email fields in a form. None of them have an id on them intentionally. How can I differentiate each element in the test if they don't have an id? I'll show code for clarity.

TEST

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

  click_link "Invite Another Team Member"

  fill_in "", with: "[email protected]"
  fill_in "", with: "[email protected]"

  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("[email protected]")
  expect(page).to have_content("[email protected]")
end

This actually creates one object, the bottom field. How can I give the text fields individuality?

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 %>

## Browser HTML

enter image description here

Upvotes: 3

Views: 745

Answers (1)

Oleksandr Avoiants
Oleksandr Avoiants

Reputation: 1929

I think you can use Capybara's method all for finding all elements with same name:

emails = ["[email protected]", "[email protected]"]
all('input[name="emails[]"]').each_with_index do |field, i|
  field.set(emails[i])
end

Or:

all('input[name="emails[]"]')[0].set("[email protected]")
all('input[name="emails[]"]')[1].set("[email protected]")

Upvotes: 3

Related Questions