0

一个小问题我对 Ruby 还很陌生,我有一个包含其他类实例的类(组合)

我正在尝试访问 Cucumber 中的类实例,但不断返回一个错误 undefined method `bk' for nil:NilClass (NoMethodError) 'bk' method is located inside the internal class 我猜这个错误是因为 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
4

1 回答 1

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 中为此创建一个方法。使用属性访问器很容易做到这一点。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"
于 2013-06-20T16:41:25.653 回答