Tomus Tomus - 1 year ago 78
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}"

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

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


def config_defines_method?(key)

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 ='./config.yaml')

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

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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download