【问题标题】:How can I test a code with 'Thread.new' in Rails?如何在 Rails 中使用“Thread.new”测试代码?
【发布时间】:2015-09-20 06:25:30
【问题描述】:

在我的 rails 应用中,Signup Class 具有以下功能,

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

我想用这些做 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)。

【问题讨论】:

  • @Drenmi 这个问题与“如何在 Rails 中测试 proc 和 yield?”不是重复的。上面的问题是关于“Thread.new”,后一个问题是关于“测试中的覆盖类或测试中的块延迟”。后一个问题仅以上述解决方案的可能方式与细节有关。

标签: ruby-on-rails multithreading unit-testing testing minitest


【解决方案1】:

使 Thread.new 只执行块而不是做 Thready 的事情。存根 Thread.new 或 Mock Thread 或替换它。

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

另见testing threaded code in ruby

【讨论】:

    【解决方案2】:

    除了@kwerle 答案,或者在测试中您可以将add_to_other_thread 返回值(即Thread)分配给变量,然后等待它完成后再运行测试:

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

    【讨论】:

      猜你喜欢
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 2023-03-11
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多