現在我已經甩了我三天了。我創建了一個類車型的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嗎?
我不完全確定我的理解,但是:你不想讀取類加載的配置文件,然後添加類級方法嗎? –
你不明白的是對我來說,我想要做的事有點奇怪。你的意思是你希望看到類定義之外的需求和文件加載?正如你所看到的,我是一個新手 - 我真的是一個測試者,而不是開發者 –
(移動評論以回答空間的原因,但它不是*答案。) –