【问题标题】:Ruby/Watir - storing watir objects in hash?Ruby/Watir - 将 watir 对象存储在哈希中?
【发布时间】:2014-07-04 03:59:44
【问题描述】:

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

但是如果我想将“元素”哈希作为 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...

有没有更好的方法来做到这一点?

【问题讨论】:

  • 您能否澄清一下您为什么要这样做?我的猜测是您可能应该考虑使用页面对象模式。一个例子是Cheezy's page-object gem

标签: ruby webdriver yaml watir


【解决方案1】:

根据您的YAML 配置构建Class 以提供对@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 文件,并根据加载的内容提供从@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

【讨论】:

    【解决方案2】:

    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-objects/ https://github.com/alisterscott/wmf-custom-page-object

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-17
      • 2015-05-27
      • 2020-05-25
      • 2020-11-10
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 2013-11-15
      相关资源
      最近更新 更多