Ruby on rails 如何使用水豚将“发现”和“内部”结合起来?

Ruby on rails 如何使用水豚将“发现”和“内部”结合起来?,ruby-on-rails,ruby,rspec,tdd,capybara,Ruby On Rails,Ruby,Rspec,Tdd,Capybara,以下工作如预期: within('h2', text: 'foo') do should have_content 'bar' end 我试图使用find(:xpath,“…”) 一旦找到一个元素,如何应用。查找(:xpath,…'),然后检查中该元素的内容?当您在中的中使用xpath定位器时,它应该以开始(如果不是以开头,则搜索不会在.myclass中进行,而是在整个文档中进行) 例如: 或: @bseen答案中的代码可以写在一行中: expect(find("//h2[te

以下工作如预期:

 within('h2', text: 'foo') do
      should have_content 'bar'
 end
我试图使用
find(:xpath,“…”)


一旦找到一个元素,如何应用
。查找(:xpath,…')
,然后检查中该元素的内容?

当您在
中的
中使用xpath定位器时,它应该以
开始(如果不是以
开头,则搜索不会在
.myclass
中进行,而是在整个文档中进行)

例如:

或:

@bseen答案中的代码可以写在一行中:

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


以下是一种方法:

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

在2.11之后的Rspec新语法中,应该是:

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

为什么不使用一个XPath语句呢?我发现
'h2',text:'foo'
更可读。我指的是你的最后一句话:你可以使用一个XPath,而不是一个XPath接着另一个XPath。同样可以在一行中完成:
find(//h2[text()='foo']/..)。如果我使用
,应该有内容“bar”
。/p[@class=test“
如果我使用
”//p[@class=test]”
它无法找到匹配的相同元素和父元素之外的另一个元素。请帮助
expect(page).to have_xpath("//h2[.='foo']/..", text: 'bar')
 within('h2', text: 'foo') do
   within(:xpath, '..') do
     should have_content 'bar'
   end       
 end
within('h2', text: 'foo') do |h|
   expect(h).to have_content 'bar'
end