Testing multiple calls to an object

Manfred Stienstra, 29 Apr 2008, 12:14 in testing, last updated 29 Apr 2008, 12:15 (edit).

Have you ever wanted to test multiple writes to $stderr? Mocking frameworks aren’t good at that, instead you can write a simple class to record method calls.

class Receptor
  require 'singleton'
  include Singleton
  
  attr_accessor :messages
  
  def initialize
    @messages = []
  end
  
  def method_missing(*attrs)
    self.messages << attrs
  end
end

$stderr = Receptor.instance

And in your tests:

messages = Receptor.instance.messages
assert messages.include?(['puts', "[!] Error!"])
assert messages.include?(['puts', "[?] Couldn't find preferences file."])

Comments

  1. Norbert Crombach about 2 hours later: (delete | show email)

    I dig it.

Add your comment

In order to fight spam on this blog, posting comments from a browser without javascript is currently not supported.