Mocking a tcp server

I have an class that should connect to a server and just wait for
responses. Here's the class, it's very basic

    class Connection
      def initialize(host, port)
        @host, @port = host, port
        @server = @host, @port


      def listen do
          while cmd = @server.gets
            puts cmd

This seems to work if I connect to a live server. It's not working
perfectly, because it only gets a couple of responses and then quits
before it has all of them. However, if do t = and then
call t.join after the thread block, it just hangs there. So I'm not
sure what to do about that.

Secondly, I don't know how to mock up the server. I have this class:

class TCPSocket
  def gets
    while $server_messages.empty?
      # just sit and do nothing


and in my unit tests I add a string to $server_messages. If I join my
thread in Connection#listen it just hangs, and if I don't join, it
just exits without getting any messages. How can I listen for
arbitrary messages in another thread, and how can I mock up the


My recent blog post might give you some ideas:

James Edward Gray II


On Apr 23, 2006, at 3:04 AM, Pat Maddox wrote:

Secondly, I don't know how to mock up the server.