我是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...
有更好的方法吗?
答案 0 :(得分:0)
根据您的@browser
配置构建Class以提供对YAML
的访问权限。
修改您的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
答案 1 :(得分:0)
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