[英]Ruby/Cucumber Composition design
我是Ruby的新手,有一个小问题,我有一个包含其他类的实例的类(组成)
我正在尝试访问Cucumber中的类实例,但始终为nil返回错误的未定义方法'bk':NilClass(NoMethodError) 'bk'方法位于内部类内部,我猜测此错误是因为Cucumber无法访问内饰类。 设计此解决方案或合适解决方案的最佳方法是什么?
class CarConfig
def initialize(browser, wait)
@browser = browser
@wait = wait
@equipments = Equipment.new(@browser)
@interior = Interior.new(@browser)
@engines = Engines.new(@browser)
@exterior = Exterior.new(@browser)
@grades = Grades.new(@browser)
end
def click_comfort
@browser.find_element(:css, 'a.xdata-id-Comfort').click
end
def check_equipment
equipment_availability = []
equipment_not_available = " equipment not available"
equipment_currently_available = "equipment available"
equipment = [@equipments.lifestyle,@equipments.elegance, @equipments.comfort, @equipments.executive, @equipments.luxury,
@equipments.innova].each do
end
equipment_availability.push equipment
if "#{equipment_availability}".include? "disabled"
equipment_not_available
else
equipment_currently_available
end
结束
Cucumber
Given /^I have selected Comfort$/ do
@car_configurator = CarConfig.new(@browser, @wait)
@browser.get $car_config_page
sleep(2)
@car_configurator.click_comfort
sleep(3)
end
Then /^I should see interior BK as available$/ do
@interior.bk.should_not include ("disabled"), ("selected")
end
问题简化
该问题可以简化为不使用黄瓜即可看到(即,问题是通用的ruby编码问题):
class Interior
def bk()
return 'bk method'
end
end
class CarConfig
def initialize(browser, wait)
@browser = browser
@wait = wait
@interior = Interior.new
end
end
@car_configurator = CarConfig.new('browser', 'wait')
@interior.bk
#=> stuff.rb:16:in `<main>': undefined method `bk' for nil:NilClass (NoMethodError)
问题是@interior
在main的范围内不存在(或者您的情况是黄瓜步骤)。 它仅在CarConfig实例(即@car_configurator
内定义。
解
如果要访问@interior
,则需要在@interior
为此创建一个方法。 使用属性访问器通常很容易做到这一点。 CarConfig类将添加以下行:
attr_accessor :interior
这样该类变为:
class CarConfig
attr_accessor :interior
def initialize(browser, wait)
@browser = browser
@wait = wait
@interior = Interior.new
end
end
然后要调用@interior
对象的bk
方法,则需要从@car_configurator
开始访问它:
@car_configurator.interior.bk
#=> "bk method"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.