How can I override the class with proc and yield in test on rails?

I have below classes (just for example),

class Background
  def self.add_thread(&blcok)
    Thread.new do
      yield
      ActiveRecord::Base.connection.close
    end
  end
end

class Email
  def send_email_in_other_thread
    Background.add_thread do
      send_email
    end
  end
  def send_email
    UserMailer.greeting_email.deliver_now
  end
end

And below are the codes for the tests,

class EmailTest < ActiveSupport::TestCase
  class Background
    def self.add_thread(&block)
      yield
    end
  end

  test 'should send email' do
    assert_difference 'ActionMailer::Base.deliveries.size', 1 do
      send_email_in_other_thread
    end
  end
end

But this test failed, "ActionMailer :: Base.deliveries.size" did not change to 1. And 1 is about 20 times success.
I think this is due to a modified background class. Perhaps overriding in the test does not work or the assignment of proc is not performed instantly, but in a delay.
I tried "block.call" instead of harvest, but the result is the same.
How can I make this test always successful?

+1
source share
1 answer

. Thread.new , , .

, .

join, , , , () , .

Thread.new do
  yield
  ActiveRecord::Base.connection.close
end.join

Rails . SideKiq Resque, .

0

Source: https://habr.com/ru/post/1608185/


All Articles