3

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

1 Answer 1

3

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]")
11
  • Thanks for the help but can you elaborate on that second one?
    – Bitwise
    Commented Oct 21, 2016 at 13:07
  • Also I'm getting this error now Nokogiri::CSS::SyntaxError: unexpected ']' after '['
    – Bitwise
    Commented Oct 21, 2016 at 13:10
  • 1
    @Cameron Bass, you probably need to escape the [] with a single or double backslash: 'emails\[\]' or 'emails\\[\\]'
    – Florent B.
    Commented Oct 21, 2016 at 13:13
  • Uggh,.. It's giving me an Nokogiri::XML::XPath::SyntaxError: Invalid expression: //emails\[\] error
    – Bitwise
    Commented Oct 21, 2016 at 13:15
  • To fix an error please try: all('emails\[\]') or all('input[name=emails\[\]]') (updated the answer). Not clear what do you mean by elaborate on that second one, sorry. I think second example is useful when need to fill in 2 of many options or it may be more readable. Commented Oct 21, 2016 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.