一个小问题我对Ruby很新,我有一个包含其他类的实例的类(组合)
我正在尝试访问Cucumber中的类实例,但不断返回错误 未定义的方法`bk'代表nil: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
答案 0 :(得分:1)
问题简化
没有Cucumber可以简化问题(即问题是一般的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
不存在于主要范围内(或者在黄瓜步骤中)。它仅在CarConfig的实例中定义 - 即@car_configurator
。
<强>解决方案强>
如果要访问@interior
,则需要在CarConfig中为此创建方法。使用attribute accessor很容易完成。 CarConfig类将添加以下行:
attr_accessor :interior
这样班级就变成了:
class CarConfig
attr_accessor :interior
def initialize(browser, wait)
@browser = browser
@wait = wait
@interior = Interior.new
end
end
然后要调用bk
对象的@interior
方法,您需要从@car_configurator
开始访问它:
@car_configurator.interior.bk
#=> "bk method"