If you have an hieararchy of classes and the parent class method has a
complex dispatch logic to the children then you may like to test if the
dispatch happens correctly or not.
Here is an example -
I have many types of audio players and there is a base player doing some
common stuff.
#— file players.rb -------
class BasePlayer
def play
# do base players job
end
end
class Mp3Player < BasePlayer
def play
# play mp3 files
end
end
#--------------------------
I oftentimes in my test want to know if the base class’s or derived
class’s
play method was invoked. This example may not be enough to convince you
of
the requirement but I do have use cases in which I want to know where in
hierarchy was the method handled. So I have this test with associated
wrapper module.
#-----file tc_players.rb----------
require ‘test/unit’
require ‘players’
class PlayerTestCase < Test::Unit::TestCase
def setup
@b = BasePlayer.new
@m = Mp3Player.new
end
def test_play
@b.extend(PlayerExtender)
@m.extend(PlayerExtender)
assert_equal( “BasePlayer”, @b.play[0] )
assert_equal( “Mp3Player”, @m.play[0] )
end
end
module PlayerExtender
def PlayerExtender.extended(xtendee)
xtendee.class.instance_methods(false).each do |m|
PlayerExtender.wrap_method(xtendee.class, m)
end
end
def PlayerExtender.wrap_method(klass, meth)
klass.class_eval do
alias_method “old_#{meth}”, “#{meth}”
define_method(meth) do |*args|
[self.class.name, self.send(“old_#{meth}”,*args)]
end
end
end
end
#-------------------------
I am posting this here for two reasons.
(a) Please let me know if this can be improved or I have overlooked a
simpler solution
(b) In the hope that this could be useful to others.
Thanks