From: Dave Cantrell Date: 2006-02-13T14:16:47+09:00 Subject: Implementing the Self-Shunt testing pattern I just stumbled across the Self-Shunt unit testing pattern[0] and decided, in my nuby quest to learn more about Ruby, to implement it in Ruby. It's simple enough thanks to duck-typing. Almost ridiculously so, in fact. My question, though, is: does the way I implemented this go against an established ruby idiom or violate "the ruby way" in any way? If so I'd love to hear it. Thanks! -dave [0] http://www.objectmentor.com/resources/articles/SelfShunPtrn.pdf ===== self_shunt.rb require 'test/unit' # Implements self-shunt pattern in Ruby. # Self-shunt detailed at: http://www.objectmentor.com/resources/articles/SelfShunPtrn.pdf class Display def display_item(item) puts "The REAL display is showing: #item" # God only knows what other processing might take place here ... end end class Scanner # accepts any object having a #display_item(item) method # hooray duck typing :) def initialize(display) @display = display end def scan(item) @display.display_item(item) end end # completely pointless class to demonstrate the idea class Item def initialize(name) @name = name end def to_s @name end end # first test the self-shunt class ScannerTest < Test::Unit::TestCase def test_scan scanner = Scanner.new(self) item = Item.new("test item") scanner.scan(item) assert_equal("test item", @displayed_item.to_s) end def display_item(item) @displayed_item = item end end # now do the real thing def main # habits die hard... :) display = Display.new scanner = Scanner.new(display) scanner.scan Item.new("now we are displaying the REAL item") 2.times {puts} # to pad between this output and the test output end main