Tomus Tomus - 19 days ago 7
Ruby Question

Ruby - how to test method using minitest

I have this class:

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


how do I write test for methods: method_missing, respond_to_missing?, config_defines_method?
I have some understanding about unit testing but when it comes to Ruby im pretty new.

So far i have tried this:

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


Im not sure if im testing it right, because when i run rake test it gives me this:


NoMethodError: private method `respond_to_missing?' called for #


If there is no clear way how to solve this, can anyone direct me to a place where similar tests are written? So far Ive only found hello world type of test examples which are not helping much in this case.

Answer

As mentioned in the documentation for #respond_to_missing?, you do not want to call the method directly. Instead, you want to check that the object responds to your method. This is done using the #respond_to? method:

assert @t_configuration.respond_to?(:test_item)
Comments