2013-06-20 118 views
0

一個小問題,我是相當新的紅寶石,我有一個包含其他類(組成)紅寶石/青瓜成分設計

我試圖內黃瓜訪問類實例的實例類,但保留返回「的零:NilClass(NoMethodError) ‘一個錯誤 未定義的方法`BK BK’的方法位於內部類 我猜這個錯誤是因爲黃瓜不能訪問內部類裏面。 什麼是設計這個或一個合適的解決方案的最佳方式?

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 

回答

1

問題簡化

的問題可以被簡化爲可見無黃瓜(即,問題是一般紅寶石編碼問題):

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 

爲了然後調用@interior對象的bk方法,你就那麼需要訪問它從開始@car_configurator

@car_configurator.interior.bk 
#=> "bk method"