2016-11-14 41 views
0

如何測試方法,我有這個類:紅寶石 - 使用MINITEST

require 'yaml' 

class Configuration 
    class ParseError < StandardError; end 

    attr_reader :config 

    def initialize(path) 
    @config = YAML.load_file(path) 
    rescue => e 
    raise ParseError, "Cannot open config file because of #{e.message}" 
    end 

    def method_missing(key, *args, &block) 
    config_defines_method?(key) ? @config[key.to_s] : super 
    end 

    def respond_to_missing?(method_name, include_private = false) 
    config_defines_method?(method_name) || super 
    end 

    private 

    def config_defines_method?(key) 
    @config.has_key?(key.to_s) 
    end 
end 

我怎麼寫方法測試:method_missing的,respond_to_missing?config_defines_method? 我對單元測試有一些瞭解,但是當談到Ruby時,我很新。如果IM測試是正確的,因爲當我運行耙測試它給了我這個

def setup 
    @t_configuration = Configuration.new('./config.yaml') 
end 

def test_config_defines_method 
    @t_configuration.config[:test_item] = "test" 
    assert @t_configuration.respond_to_missing?(:test_item) 
end 

林不知道:

到目前爲止,我已經嘗試過這種

NoMethodError: private method `respond_to_missing?' called for #

如果沒有明確的如何解決這個問題,任何人都可以指導我到一個寫類似測試的地方嗎?到目前爲止,我只找到了你好世界類型的測試例子,在這種情況下幫助不大。

回答

2

documentation for #respond_to_missing?所述,您不想直接調用該方法。相反,你想檢查對象是否響應你的方法。這是使用#respond_to?方法完成的:

assert @t_configuration.respond_to?(:test_item) 
+0

謝謝,所以現在我知道它是某種默認方法繼承的所有對象 – Tomus