现在我已经甩了我三天了。我创建了一个类车型的HTML页面,并告诉黄瓜的步骤定义,其中填充表单数据:这是define_method用例太复杂吗?
class FlightSearchPage
def initialize(browser, page, brand)
@browser = browser
@start_url = page
#Get reference to config file
config_file = File.join(File.dirname(__FILE__), '..', 'config', 'site_config.yml')
#Store hash of config values in local variable
config = YAML.load_file config_file
@brand = brand #brand is specified by the customer in the features file
#Define instance variables from the hash keys
config.each do |k,v|
instance_variable_set("@#{k}",v)
end
end
def method_missing(sym, *args, &block)
@browser.send sym, *args, &block
end
def page_title
#Returns contents of <title> tag in current page.
@browser.title
end
def visit
@browser.goto(@start_url)
end
def set_origin(origin)
self.text_field(@route[:attribute] => @route[:origin]).set origin
end
def set_destination(destination)
self.text_field(@route[:attribute] => @route[:destination]).set destination
end
def set_departure_date(outbound)
self.text_field(@route[:attribute] => @date[:outgoing_date]).set outbound
end
# [...snip]
end
正如你所看到的,我用instance_variable_set创建举行的飞行引用变量,并且变量名和值由配置文件提供(其设计为可由不熟悉Ruby的人编辑)。
不幸的是,这是一个很大的毛茸茸的类,每次我想添加一个新的字段时,我将不得不编辑源代码,这显然是糟糕的设计,所以我一直试图去一个舞台进一步创建用define_method动态设置变量名称的方法,这就是让我在过去的几个夜晚一直保持清醒到凌晨4点。
这是我做了什么:
require File.expand_path(File.dirname(__FILE__) + '/flight_search_page')
class SetFieldsByType < FlightSearchPage
def text_field(config_hash)
define_method(config_hash) do |data|
self.text_field(config_hash[:attribute] => config_hash[:origin]).set data
end
end
end
的想法是,所有你需要做的,添加一个新的字段添加新条目到YAML文件和define_method将创建方法,以允许黄瓜来填充它。
目前,我遇到范围问题 - Ruby认为define_method是@browser的成员。但我想知道的是:这是否可行?我完全误解了define_method吗?
我不完全确定我的理解,但是:你不想读取类加载的配置文件,然后添加类级方法吗? –
你不明白的是对我来说,我想要做的事有点奇怪。你的意思是你希望看到类定义之外的需求和文件加载?正如你所看到的,我是一个新手 - 我真的是一个测试者,而不是开发者 –
(移动评论以回答空间的原因,但它不是*答案。) –