16

I have a test that renders two of the same elements on the page. I understand what the problem is with the error but I'm just not sure how to fix it? Here is my test:

TEST

 it "deletes the correct snitch" do
        user    = login_user
        snitch  = create(:snitch, :healthy, owner: user.accounts.first)
        snitch2 = create(:snitch, :healthy, owner: user.accounts.first)

        visit root_path
        delete = page.find(".icon-delete")
        first(delete).click
        expect(page).to have_content("Please confirm this delete.")


 end

ERROR

 Managing snitches deleting a snitch from the index page deletes the correct snitch
 Failure/Error: delete = page.find(".icon-delete")

 Capybara::Ambiguous:
   Ambiguous match, found 2 elements matching css ".icon-delete"

How can I pick just one of the icon delete on the page?

3 Answers 3

22

I would suggest wrapping it in a more specific finder as below:

within find('#my_unique_id') do
  find(".icon-delete").click
end

That however would require you to have an id on the parent element. If you don't have this, you could go the simple route of selecting the first one on that page then calling click on that:

first(".icon-delete").click
Sign up to request clarification or add additional context in comments.

1 Comment

this solution skips the amazing automatic waiting feature that Capybara has, though stackoverflow.com/questions/39859291/…
14
click_on "Link Text.", match: :first

Comments

9

First takes the same parameters as find (not elements) so to just click on the first matching element you would do

page.first('.icon-delete').click

There is a difference to take into account though, since nil is a valid response for first it won't (by default) wait for a matching element to appear. If you do need it to wait for the element you just need to pass one of the count options

page.first('.icon-delete', minimum: 1).click

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.