Capybara can not find element by id

13,792

Solution 1

By default Capybara doesn't find elements that are not visible on the page. You can try

page.find('#notice_sent', visible: :all)

to see if that's the case. If so, and you're testing an app, then you should perform whatever actions a user would perform that would make that element visible, and then check for its presence.

Solution 2

Though I am a newbie to Capybara, I think this might work for you !!

page.find('#notice_sent', :visible => false)

Also, add this code to your env.rb file.

Capybara.ignore_hidden_elements = false
Share:
13,792
Todd R
Author by

Todd R

"If it's not tested, how do you know whether it works?"

Updated on July 24, 2022

Comments

  • Todd R
    Todd R almost 2 years

    Capybara is not able to find a <p> tag by it's id in my cucumber test. I'm able to see the element when I save_and_open_page. But I can't locate it with has_css? or find:

    pry(#<Object>)> page.html.scan(/notice_sent/).count
    => 1
    pry(#<Object>)> page.html.scan(/id=\"notice_sent\"/).count
    => 1
    pry(#<Object>)> page.find('#notice_sent')
    Capybara::ElementNotFound: Unable to find css "#notice_sent"
    from /Users/me/.gem/ruby/2.1.7/gems/capybara-2.4.4/lib/capybara/node/finders.rb:41:in 'block in find'
    

    What am I missing?

  • Todd R
    Todd R about 8 years
    page.html return a string so find is not a valid method
  • Thomas Walpole
    Thomas Walpole about 8 years
    To use finders on a string you would need to create a Capybara::Node::Simple from it like Capybara.string(page.html).find(...) - while this is possible, it's really better just to figure out why Capybara isn't finding the element in the session - see my answer
  • Todd R
    Todd R about 8 years
    Yep - the id was on the page but wasn't visible until I added a click on a tab
  • Thomas Walpole
    Thomas Walpole about 8 years
    Setting ignore_hidden_elements to false is a really bad idea 99% of the time, especially if you're using Capybara as a testing tool. It will lead to incorrectly passing tests for a lot of UI issues.