2016-11-14 42 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