capybara - Find with xPath is leaving the within scope

后端 未结 1 898
温柔的废话
温柔的废话 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):

    
        
    field 1
    field 2

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