【问题标题】:How to stub a thread using Rspec?如何使用 Rspec 存根线程?
【发布时间】:2013-06-28 21:58:23
【问题描述】:

我正在尝试测试一个线程。假设客户,地点,消息都在上面的代码中,但是发布起来会很长。我正在尝试测试“消息”变量,但由于它不是实例变量并且它位于线程内,因此我无法很容易地对其进行测试。我假设存根线程将是使用 rspec 测试它的正确途径,但是如果您对如何准确测试“消息”变量有任何其他建议,那将非常有帮助。这是我正在做的基本版本:

Class Messages
  def order_now
    conf = venue.confirmation_message
    message = "Hi #{customer.first_name}, "
    if conf && conf.present?
      message << conf
    else
      message << "your order has been received and will be ready shortly."
    end

    Thread.new do
      ActiveRecord::Base.connection_pool.with_connection do
        Conversation.start(customer, venue, message, {:from_system => true})
      end
      ActiveRecord::Base.connection_pool.clear_stale_cached_connections!
    end         
  end
end

提前谢谢你!

【问题讨论】:

    标签: multithreading testing rspec controller stub


    【解决方案1】:

    你必须在这里变得聪明一点:

    it "should test the conversation message" do
      Conversation.should_receive(:start).with(
        instance_of(Customer), 
        instance_of(Venue),
        "your order has been received and will be ready shortly.",
        {:from_system => true}
      ).and_call_original
    
      message_instance.order_now.join
    end
    

    基本上,您可以测试您是否使用正确的参数调用了您的Conversation::start。但是,这里有一个微妙之处 - 您调用 message_instance.order_now.join,因为 order_now 返回线程,并且您希望在 rspec 示例完成之前等待线程完成运行。 #join 将阻止主线程的执行,直到引用的线程完成运行。否则,rspec 示例可能会在线程执行之前完成运行,从而导致测试失败。

    【讨论】:

    • 我在该方法中添加了更多细节,希望能够为测试提供更多信息。我只是想测试一下,如果venue.confirmation 为空白,则表明“您的订单已收到并将很快准备就绪”。字符串将被铲入消息字符串中。我想测试消息变量,但 rspec 只允许您测试像 @message 这样的实例化变量,所以我可以测试响应的唯一方法是在线程内。让我知道您的想法以及如何使用 Rspec 测试消息变量。谢谢!
    • 你也可以这样做:allow(Thread).to receive(:new).and_yield
    猜你喜欢
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多