2012-04-20 54 views
9

我想用默認的Rails日期,時間和日期時間字段來建立一個帶有水豚的日期選擇器。我正在使用within方法來查找字段的選擇框,但是當我使用xPath來查找正確的方框時,它會離開within作用域,並在元素的頁面上找到第一個匹配項。水豚 - 用xPath查找正在離開範圍內

這是我使用的代碼。我正在測試的頁面有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) 

回答

25

你應該在你想添加一個.到開始啓動與當前節點中的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