Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine find and within using Capybara?

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?

like image 739
B Seven Avatar asked Dec 14 '12 19:12

B Seven


3 Answers

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')
like image 110
Andrei Botalov Avatar answered Nov 02 '22 16:11

Andrei Botalov


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     
like image 29
beydogan Avatar answered Nov 02 '22 16:11

beydogan


The following is one approach:

 within('h2', text: 'foo') do
   within(:xpath, '..') do
     should have_content 'bar'
   end       
 end
like image 4
B Seven Avatar answered Nov 02 '22 18:11

B Seven