How to get Capybara to click on <li> in navigation menu?

I am writing a test for a navigation menu. This test worked until I changed the options in the <li> in the rails view from hard-coded options to be retrieved from the database. How should I setup this test so it mimics the user choosing the selection from the navigation drop-down?

my spec:

feature "user can navigate to a restaurant page" do
  scenario "views a restaurant page" do
    visit root_path

    within('#restaurants'){
      click_on 'Corner Pub'
    }
  end
end

My test fails with:

  1) user can navigate to a restaurant page views a restaurant page
     Failure/Error: click_on 'Corner Pub'
     Capybara::ElementNotFound:
       Unable to find link or button "Corner Pub"

from the navigation partial:

    <li class="nav-link more" id="restaurants"><a href="/restaurants/">restaurants</a>
      <ul class="submenu">
        <% Restaurant.reviewed_restaurants.each do |restaurant| %>
          <li><%= link_to restaurant.name, restaurant %></li>
        <% end %>
      </ul>
    </li>

From the html:

<li class="nav-link more" id="restaurants"><a href="/restaurants/">restaurants</a>
  <ul class="submenu">
    <li><a href="/restaurants/corner-pub">Corner Pub</a></li>
  </ul>
</li>

Are you sure that’s your HTML in test? Do you have fixtures that seed the test database with that restaurant?

Yeah, you are right. rookie mistake. I don’t have it set to do that yet.

A useful way to debug this type of error is to call save_and_open_page, which is provided by the Launchy gem.

Also, you can use Pry to trigger a pause within a scenario in order to use Capybara interactively, then copy the code back into your test once it’s correct.

1 Like