cancue
cancue

Reputation: 414

How can I test a code with 'Thread.new' in Rails?

In my rails app, Signup Class has below functions,

def register_email
  # Something...
  add_to_other_thread do
    send_verification_email
  end
end

def add_to_other_thread(&block)
  Thread.new do
    yield
    ActiveRecord::Base.connection.close
  end
end

And I want to do 3 tests with these.

  1. Test about add_to_other_thread(&blcok):
    After add_to_other_thread being called with some block, Check whether or not it called Thread.new with proper block.
  2. Test about register_email:
    After register_email being called, Check whether add_to_other_thread(&block) got proper block or not.
  3. In Integral Test:
    After User signing up, Check whether or not proper email was sent(with ActionMailer::Base.deliveries) via other Thread.

Upvotes: 6

Views: 1987

Answers (2)

Ehsan
Ehsan

Reputation: 1022

In addition to @kwerle answer, alternatively in the test you can assign add_to_other_thread return value which is a Thread to a variable and then wait for it to be finished before running the test:

thread = signup.add_to_other_thread
thread.join
# your test goes here

Upvotes: 0

kwerle
kwerle

Reputation: 2401

Make Thread.new just execute the block instead of doing Thready things. Either stub Thread.new or Mock Thread or replace it.

expect(Thread).to receive(:new).and_yield

See also testing threaded code in ruby

Upvotes: 2

Related Questions