Search code examples
rubyrspecthread-synchronization

How to test threads


We have threads:

module Task
  def self.execute
    "result"
  end
end

threads = []
threads << Thread.new { Task.execute }

We need to specify the test that checks the result:

expect(Task.execute).to eq("result")

We added a thread inside a thread:

threads << Thread.new do
  deep_thread = Thread.new { Task.execute }
  deep_thread.join
end

How can we check the result of method calls inside a thread? How can we check that the two threads finished, and also check the result of deep_thread?


Solution

  • Test the results of method calls separately outside of the thread logic.

    Then test the thread creation logic separately with something like:

    let(:thread) { double }
    it 'creates threads' do
      expect(Thread).to receive(:new).exactly(5).times.and_return(thread)
      expect(thread).to receive(:join).exactly(5).times.and_return(true)
      expect(Task).to receive(:execute).exactly(5).times.and_return("xyz")
      expect(subject.execute).to eq "xyz"
    end