vendredi 31 juillet 2015

Connecting to background EventMachine application for unit testing

I am writing a headless Ruby application using EventMachine that communicates over sockets. I want to write some unit tests for this app. This means that my Ruby test script needs to launch that app in the background, perform socket communication with it, and then close that process.

This code fails. The socket connection is refused.

require 'socket'
PORT = 7331
CMD = File.expand_path("../../bin/rb3jay",__FILE__)
@thread = Thread.new{ `#{CMD} -D --port #{PORT}` }
@socket = TCPSocket.open('localhost', PORT)
#=> Errno::ECONNREFUSED: Connection refused - connect(2) for "localhost" port 7331

If I inject a 2 second delay before attempting the socket connection, it works as desired:

@thread = Thread.new{ `#{CMD} -D --port #{PORT}` }
sleep 2
@socket = TCPSocket.open('localhost', PORT)

This seems a gross hack. Maybe 2 seconds is long enough for my machine, but too short somewhere else. How should I correctly:

  • Launch my EventMachine application in the background
  • Create a socket connection to it as soon as it is ready
  • After my tests are done, ensure that the socket is closed and that I kill the background application

Aucun commentaire:

Enregistrer un commentaire