How to combine find and within using Capybara?

15,972

Solution 1

When you use XPath locator inside within it should start with . (if it doesn't start with . the search is done not within .myclass but within the whole document).

E.g.:

within('.myclass') do
  find(:xpath, './div')
end

or:

find('.myclass').find(:xpath, './div')

Code from @BSeven's answer can be written in one line:

expect(find("//h2[text()='foo']/..")).to have_text('bar')

or

expect(page).to have_xpath("//h2[.='foo']/..", text: 'bar')

Solution 2

With the new syntax of Rspec after 2.11, it should be;

within('h2', text: 'foo') do |h|
   expect(h).to have_content 'bar'
end     

Solution 3

The following is one approach:

 within('h2', text: 'foo') do
   within(:xpath, '..') do
     should have_content 'bar'
   end       
 end
Share:
15,972
B Seven
Author by

B Seven

Status: Hood Rails on HTTP/2: Rails HTTP/2 Rack Gems: Rack Crud Rack Routing Capybara Jasmine

Updated on June 16, 2022

Comments

  • B Seven
    B Seven almost 2 years

    The following works as expected:

     within('h2', text: 'foo') do
          should have_content 'bar'
     end
    

    I am trying to check within the parent element, using find(:xpath, '..')

    Once you find an element, how to apply .find(:xpath, '..'), and then check for something within that element?

  • Andrei Botalov
    Andrei Botalov over 11 years
    The same can be done in one line: find("//h2[text()='foo']/..").should have_content 'bar'
  • pahnin
    pahnin almost 11 years
    If I use './p[@class=test]' its not able to find, If I use '//p[@class=test]' its matching same element and another element outside the parent element.. Please help