【问题标题】:How to combine find and within using Capybara?如何使用 Capybara 结合 find 和 inside?
【发布时间】:2012-12-14 19:50:16
【问题描述】:

以下按预期工作:

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

我正在尝试使用 find(:xpath, '..') 在父元素内进行检查

找到一个元素后,如何应用.find(:xpath, '..'),然后检查那个元素内的东西?

【问题讨论】:

  • 为什么不只使用一个 XPath 语句?
  • 我发现'h2', text: 'foo' 更具可读性。
  • 我指的是您的最后一句话:您可以使用单个 XPath,而不是先应用一个 XPath,然后再应用另一个。

标签: ruby-on-rails ruby rspec tdd capybara


【解决方案1】:

当您在within 中使用XPath 定位器时,它应该以. 开头(如果它不以. 开头,则搜索不在.myclass 内而是在整个文档内完成)。

例如:

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

或:

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

@BSeven 回答的代码可以写成一行:

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

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

【讨论】:

  • 如果我使用'./p[@class=test]'它无法找到,如果我使用'//p[@class=test]'它匹配相同的元素和父元素之外的另一个元素..请帮助
【解决方案2】:

用Rspec 2.11以后的新语法,应该是;

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

【讨论】:

    【解决方案3】:

    以下是一种方法:

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

    【讨论】:

    • 一行也可以:find("//h2[text()='foo']/..").should have_content 'bar'
    猜你喜欢
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2015-12-20
    • 2017-04-06
    相关资源
    最近更新 更多