Cameron Bass Cameron Bass - 1 month ago 12
Ruby Question

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: "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


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

Answer

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

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

Or:

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