capybara - Find with xPath is leaving the within scope

雨燕双飞 提交于 2019-12-05 01:06:36

You should specify in the xpath that you want to start with the current node by adding a . to the start:

find(:xpath, ".//select[contains(@id, \"_#{FIELDS[:year]}\")]")

Example:

I tested an HTML page of this (hopefully not over simplifying your page):

<html>
    <div id='div1'>
        <span class='container'>    
            <span id='field_01'>field 1</span>
        </span>
    </div>
    <div id='div2'>
        <span class='container'>
            <span id='field_02'>field 2</span>
        </span>
    </div>  
</html>

Using the within methods, you can see your problem when you do this:

within("div#div1"){ puts find(:xpath, "//span[contains(@id, \"field\")]").text }
#=> field 1
within("div#div2"){ puts find(:xpath, "//span[contains(@id, \"field\")]").text }
#=> field 1

But you can see that but specifying the xpath to look within the current node (ie using .), you get the results you want:

within("div#div1"){ puts find(:xpath, ".//span[contains(@id, \"field\")]").text }
#=> field 1
within("div#div2"){ puts find(:xpath, ".//span[contains(@id, \"field\")]").text }
#=> field 2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!