Nick Acker Nick Acker - 3 months ago 28
Ruby Question

RSpec: Testing with Threads

In RSpec, I have function that creates a new thread, and inside that thread performs some action–in my case, calls

TCPSocket#readline
. Here's the function as it is right now:

def read
Thread.new do
while line = @socket.readline
#TODO: stuff
end
end
end


Due to thread scheduling, my test will fail if written as such:

it "reads from socket" do
subject.socket.should_receive(:readline)
subject.read
end


Currently the only way I know to hack around this is to use
sleep 0.1
. Is there a way to properly delay the test until that thread is running?

Answer

If your goal is to assert the system state is changed by the execution of your second thread, you should join on the second thread in your main test thread:

it "reads from socket" do
  subject.socket.should_receive(:readline)
  socket_thread = subject.read
  socket_thread.join
end