簡體   English   中英

紅寶石/黃瓜成分設計

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM