capybara - Find with xPath is leaving the within scope

后端 未结 1 891
温柔的废话
温柔的废话 2021-02-19 14:47

I am trying to build a date selector with Capybara using the default Rails date, time, and datetime fields. I am using the within method to find the select boxes fo

相关标签:
1条回答
  • 2021-02-19 15:38

    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
    
    0 讨论(0)
提交回复
热议问题