Ultimation
Ultimation

Reputation: 152

How can I make sure threads inside my class end after each rspec test?

I have a jruby class which contains a heartbeat that does something every certain number of seconds: (simplified code below)

class Client
  def initialise
    @interval = 30
    @heartbeat = Thread.new do
      begin
        loop do
          puts "heartbeat"
          sleep @interval
        end
      rescue Exception => e
        Thread.main.raise e
      end
    end
  end
end

And I have a range of rspec tests that instantiate this class.

At the end of each test, I would expect the object to be destroyed, but the threads seem to remain.

At the moment I've fixed this with: client.rb:

def kill
    @heartbeat.kill
end

rspec:

after(:all) do
   client.kill
end

Which seems to do the job - but this doesn't feel like the best way to do it.

What is the best way to approach this?

Using version jruby-9.1.10.0 & rspec 3.7.0

Edit: As per http://ruby-doc.org/core-2.4.0/Thread.html I would expect the thread to normally terminate when the main thread does In my tests I instantiate the client with

describe Client do
  context 'bla' do
    let(:client) do
      described_class.new
    end
    it 'blas' do
    end
  end
end

Upvotes: 1

Views: 862

Answers (1)

neznidalibor
neznidalibor

Reputation: 175

You should replace after(:all) with after(:each).

Should be the correct syntax for what you want to do because after(:all) evaluates after all test cases have been run.

Upvotes: 1

Related Questions