6

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.
cancue
  • 384
  • 3
  • 18
  • possible duplicate of [How can I test for proc and yield in rails?](http://stackoverflow.com/questions/32677966/how-can-i-test-for-proc-and-yield-in-rails) – Drenmi Sep 20 '15 at 16:55
  • @Drenmi This question is not duplicate of 'How can I test for proc and yield in rails?'. The above question is about 'Thread.new', and the latter question is about 'overriding class in test or block delay in test'. The latter question is about details in only a possible way for above solution. – cancue Sep 20 '15 at 17:20

2 Answers2

2

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

kwerle
  • 2,225
  • 22
  • 25
0

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
Ehsan
  • 1,022
  • 11
  • 20