[mocha-developer] counter-intuitive behaveour when passing a proc to Mocha::Expectation#returns

Chris Roos chrisjroos at gmail.com
Thu Jan 11 10:16:28 EST 2007

> The example given for a stub in the referred essay is this:
>   public class MailServiceStub implements MailService {
>     private List<Message> messages = new ArrayList<Message>();
>     public void send (Message msg) {
>       messages.add(msg);
>     }
>     public int numberSent() {
>       return messages.size();
>     }
>   }
> Mocha won't allow you to do this, since you'd need to have access to "Message
> msg" when stubbing the "send" method above, which isn't the case as you note.

Maybe not, but ruby will :-)  The equivalent would be, as James
previously suggested, a fake version.  Somewhere in the load path of
your tests, you would define the above class.  Something like:

class MailServiceStub
  def initialize(messages = [])
    @messages = messages
  def send(msg)
  def number_sent

> Thus we are not able to save the message for further verification - f.ex. if the
> calling unit, which we want to test is actually passing the message on to the
> MailServiceStub or whether it's eating it.
Actually, you don't need the MailServiceStub in order to test whether
your calling unit is passing the message on.  You would probably have
something like:

def test_should_pass_message_to_mail_service
  message = stub
  mail_service = mock
  client = Client.new
  client.send_message(mail_service, message)

A simple Client to satisfy this test would be:

class Client
  def send_message(mail_service, message)

To be honest, I'm slightly confused by your two messages but am hoping
this explanation helps a bit.


More information about the mocha-developer mailing list