From: Eric Hodel Date: 2006-04-04T05:59:30+09:00 Subject: Re: Mocking whole classes On Apr 3, 2006, at 6:37 AM, Thiago Arrais wrote: > Has anyone tried to mock whole classes (instead of mocking only the > objects)? I've found it more pain than its worth because I change the implementation then have to go change all my mocks. No fun. > Classes are, like everything else in Ruby, just objects. This allows > us to mock them just like we would mock any other object. I have been > working on a Rails application (that will be shared with you as soon > as I get it translated, I promise) in which I needed to do exactly > that. > > The class I wanted to mock is responsible for communicating to my > back-end database and fetching the appropriate objects (instances of > itself). The object-finding functionality is implemented as class > level methods. If I need the N latest headlines from a reporter named > 'johnson', I just need to call `Headline.latest(N, "johnson"). When I need that kind of behavior I tend to do something like this: require 'flickr' class Flickr attr_accessor :responses, :uris def open(uri) @uris << uri yield StringIO.new(@responses.shift) end end I'm using open-uri so I inject a new open into my class that shadows Kernel's open. My tests prime it with a bunch of responses and when I call open I just record the URI and return the in-order response. For my test I check that the right URIs were accessed and the right data came back. Here's a test: class FlickrTest < Test::Unit::TestCase def setup @flickr = Flickr.new 'API_KEY' @flickr.responses = [] @flickr.uris = [] end def test_find_email @flickr.responses << <<-EOF drbrain EOF nsid = @flickr.find_email :find_email => 'drbrain@segment7.net' assert_equal 1, @flickr.uris.length assert_equal 'http://flickr.com/services/rest/? api_key=API_KEY&find_email=drbrain% 40segment7.net&method=flickr.people.findByEmail', @flickr.uris.first assert_equal '50178138@N00', nsid end end -- Eric Hodel - drbrain@segment7.net - http://blog.segment7.net This implementation is HODEL-HASH-9600 compliant http://trackmap.robotcoop.com