如何在Rails中使用'Thread.new'测试代码?

can*_*cue 6 testing multithreading unit-testing ruby-on-rails minitest

在我的rails应用程序中,注册类具有以下功能,

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
Run Code Online (Sandbox Code Playgroud)

我想用这些进行3次测试.

  1. 测试add_to_other_thread(&blcok):
    在使用某个块调用add_to_other_thread 之后,检查它是否使用适当的块调用Thread.new.
  2. 关于register_email的测试:
    在调用register_email 之后,检查add_to_other_thread(&block)是否得到了正确的阻止.
  3. 在积分测试中:
    用户注册后,检查是否通过其他线程发送了正确的电子邮件(使用ActionMailer :: Base.deliveries).

kwe*_*rle 2

让Thread.new只执行块而不是做Thready的事情。存根 Thread.new 或模拟线程或替换它。

expect(Thread).to receive(:new).and_yield
Run Code Online (Sandbox Code Playgroud)

另请参阅在 ruby​​ 中测试线程代码