水豚 - 使用XPath查找的范围之内离开(capybara - Find with xPath i

2019-07-29 02:31发布

我试图建立与使用默认Rails的日期,时间和日期时间字段水豚的日期选择器。 我现在用的within法找到该领域的选择框,但是当我使用XPath找到正确的箱子离开within的范围,并找到该元素的页面上的第一次出现。

这里是我使用的代码。 我测试浏览的页面有2个日期时间字段,但我只能把它改变,因为这个错误的第一。 目前,我有一个ID的div容器包装了日期时间字段,但我不接通的代码由标签查找计划。

module  Marketron
  module DateTime

    def select_date(field, options = {})
      date_parse = Date.parse(options[:with])

      year = date_parse.year.to_s
      month = date_parse.strftime('%B')
      day = date_parse.day.to_s

      within("div##{field}") do
        find(:xpath, "//select[contains(@id, \"_#{FIELDS[:year]}\")]").select(year)
        find(:xpath, "//select[contains(@id, \"_#{FIELDS[:month]}\")]").select(month)
        find(:xpath, "//select[contains(@id, \"_#{FIELDS[:day]}\")]").select(day)
      end

    end

    def select_time(field, options = {})
      require "time"
      time_parse = Time.parse(options[:with])

      hour = time_parse.hour.to_s.rjust(2, '0')
      minute = time_parse.min.to_s.rjust(2, '0')

      within("div##{field}") do
        find(:xpath, "//select[contains(@id, \"_#{FIELDS[:hour]}\")]").find(:xpath, "option[contains(@value, '#{hour}')]").select_option
        find(:xpath, "//select[contains(@id, \"_#{FIELDS[:minute]}\")]").find(:xpath, "option[contains(@value, '#{minute}')]").select_option

      end

    end

    def select_datetime(field, options = {})
      select_date(field, options)
      select_time(field, options)
    end

    private

      FIELDS = {year: "1i", month: "2i", day: "3i", hour: "4i", minute: "5i"}

  end
end

World(Marketron::DateTime)

Answer 1:

你应该在你想添加一个启动与当前节点中的XPath指定. 到开始:

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

例:

我测试的这一个HTML页面(希望不是在简化您页):

<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>

方法中使用,你可以看到你的问题,当你这样做:

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

但是你可以看到,但指定的XPath当前节点内看(即使用. ),你得到你想要的结果:

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


文章来源: capybara - Find with xPath is leaving the within scope