dimanche 20 septembre 2015

How can I test for proc and yield in rails?

I have below classes(only 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 codes are for 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 fails, "ActionMailer::Base.deliveries.size" didn't change by 1. And 1 in about 20 times success.
I think it is because of the modified Background class. Maybe yield proc is not executed instantly but in delayed.
I tried 'block.call' instead of yield, but the result is not changed.
How can I make this test always be success?

Aucun commentaire:

Enregistrer un commentaire