RSpec: testing with threads

In RSpec, I have a function that creates a new stream, and inside this stream performs some action - in my case, it calls TCPSocket#readline . Here's the function as it is now:

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

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

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

Currently, the only way I know is to use sleep 0.1 . Is there a way to properly delay the test until this thread is started?

+7
source share
2 answers

If your goal is to claim that the state of the system changes by executing your second thread, you should join 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 
+9
source

This is a bit of a hack, but here is a before block that you can use if you want the stream to be yield , but have the ability to call join at the end of the stream.

 before do allow(Thread).to receive(:new).and_yield.and_return(Class.new { def join; end }.new) end 
0
source

All Articles