Collin
Collin

Reputation: 103

Capybara::ElementNotFound: Unable to find css "a"

I have been trying to fix this error for a very long time now and I can't seem to figure out what it is. Thanks in advance for your help!

I am writing tests for a rails app with capybara and rspec trying to click on an element in a nav bar and then test to make sure the page is correct, but it seems no matter how I tell capybara to click the element, it can't find it.

   ...
  subject { page }

  describe 'when clicking Home link', :js do
    before do
      visit some_path
      find('a', text: "Home").click
    end
    it { should have_selector('title', text: 'bla bla bla') }
  end
  ...

I have tried many different versions of this code, including

  click_link('Home'),
  click_on('Home'),
  find('a.header-link.header-link-home', text: 'Home').click,
  find_link(...).click,
  click_button(...)

and so on, as well as with and without :js, and in different "within" statements, but I always get Capybara::ElementNotFound: Unable to find css "a". I have also tried increasing capybara's default wait time to 5 seconds.

This is the element that I am trying to click (according to the page's source code)

  <a class="header-link header-link-home" href="/">Home</a>

Gem versions: capybara (1.1.4), rspec (2.12.0)

Thanks a ton, I really appreciate it!

Upvotes: 9

Views: 7771

Answers (2)

Collin
Collin

Reputation: 103

It turns out that some of the links weren't showing up because the page I as on wasn't loaded properly because it didn't have any data in it. I saw this when I opened it on the localhost server, but save_and_open page (as Ju Liu suggested; Thanks!) would probably have done the same thing. I needed to either start from a different page that had loaded properly or add in some factories and populate the page.

Upvotes: 0

Ju Liu
Ju Liu

Reputation: 3999

Your code should be correct, I've always used click_link 'Foobar'. Have you tried to add a

save_and_open_page

after the visit line? It generally helps me a lot to understand why capybara can't find stuff.

Upvotes: 9

Related Questions