簡體   English   中英

Ruby / Watir-將watir對象存儲在哈希中?

[英]Ruby/Watir - storing watir objects in hash?

我是Ruby的新手,我很喜歡它。 與Watir-Webdriver一起玩。 我想將對watir對象的引用存儲在哈希中並將其保存到磁盤,而無需先定義@browser變量。 例如

elements = { 
  :home => @browser.a(:href => /home.php/),
  :photo => @browser.img(:id => "photo"),
  :about => @browser.a(:href => /about.php/)
}

這樣我就可以做類似的事情:

el = elements
el[:home].click
el[:photo].wait_until_present
el[:about].click

顯然,如果我一開始就定義了@browser,就可以使用。

@browser = Watir::Browser.new

但是,如果我想將'elements'哈希作為YAML存儲在文件中怎么辦? 我應該將值存儲為帶引號的字符串並立即進行評估嗎? 喜歡

elements = { 
  :home => "@browser.a(:href => /home.php/)",
  # etc...
}

# store elements as YAML file...
# load elements from YAML file

el = YAML::load_file "elements.yml"
eval(el[:home]).click
eval(el[:photo].wait_until_present

# etc...

有一個更好的方法嗎?

建立一個 ,以根據您的YAML配置提供對@browser的訪問。

修改elements結構以包含所需的數據而不是代碼。 考慮一下這是新類的配置散列/文件。

elements = { 
  :home  => { :tag => "a",   :select => { :href => /home.php/ } },
  :photo => { :tag => "img", :select => { :id   => "photo" } },
  :about => { :tag => "a",   :select => { :href => /about.php/ } }
}

構建一個類以加載elements YAML文件,並根據加載的elements提供@browser對所需內容的訪問。

class WatirYamlBrowserSelect

   # To store your config and browser. 
   attr_accessor :elements, :browser

   def initialize elements_yaml_file
     @elements = YAML.load_file elements_yaml_file
   end

   # Retrieve a configured element from Watir Browser. 
   def element name
     @browser.send( @elements[name][:tag], @elements[name][:select] )
   end

end

然后,當您需要使用它時

# Create an instance of your selector. 
s = WatirYamlBrowserSelect.new( "elements.yaml" )

# Add the browser when you have it
s.browser @browser

# Access the @browser elements
s.element :home
s.element :photo
s.element :about

Alister Scott的博客以及github中的代碼是我用來為一些項目構建所有頁面對象的模板。 我認為它應該可以解決您描述的重復問題。 它還解決了為太多頁面的對象維護太多變量的問題,並使對象按頁面組織,而不是處於更復雜的數據結構中,尤其是當對象數量增加時。

http://watirmelon.com/2011/06/07/removing-local-page-references-from-cucumber-steps/ http://watirmelon.com/2012/06/04/roll-your-own-page-對象/ https://github.com/alisterscott/wmf-custom-page-object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM