Easily find elements with XPath in Capybara by using Chrome's Dev Tools
Imagine you have multiple identical elements on a page and that you need to select a specific element during a system test.
If your test were written like this, it would fail with a
Capybara::Ambiguous: Ambiguous match error.
test "opening modal" do visit root_path click_button("Launch Modal") end
One solution is to use XPath to target the desired element. However, figuring out the XPath can be tricky. Luckily Chrome’s DevTools give us the ability to easily copy an element’s XPath.
Now you can use find with xpath to target the specific element.
test "opening modal" do visit root_path find(:xpath, "/html/body/div/div/button").click end
But what if the development DOM is not the same as your test DOM? One solution is to drop a
byebug into the system test if you’re not using a headless browser. This will keep the browser open and allow you to use the dev tools within the context of the testing browser.
test "opening modal" do visit root_path byebug end