Testing multiple calls to an object

Manfred Stienstra

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."])

You’re reading an archived weblog post that was originally published on our website.