【发布时间】:2012-01-13 13:44:51
【问题描述】:
我正在尝试启动一个小型 WEBrick 服务器来模拟真实的 API,以测试我正在开发的 Ruby http 客户端。我正在使用基于 this 博客评论的修改解决方案。
它工作正常,但问题是每次服务器启动时,父线程都必须等待任意时间才能加载服务器。在添加了几个测试之后,它变得非常慢。
所以我的问题是:有没有办法在服务器线程完成启动 WEBRick 后同步父线程以继续?
我尝试查看 WEBrick 参考,搜索网络,甚至查看 WEBrick 代码,但如果没有一些非常讨厌的猴子补丁,我什么都无法使用。
我对解决此问题的其他方法持开放态度,但我希望尽可能保持它对 gems 和库的无依赖性。此外,解决方案必须在 Linux 上的 Ruby 1.9.2 中运行。
提前感谢您的回答!
require "rack"
class ApiMockServer
def initialize(port = 4000, pause = 1)
@block = nil
@parent_thread = Thread.current
@thread = Thread.new do
Rack::Handler::WEBrick.run(self, :Port => port, :Host => "127.0.0.1")
end
sleep pause # give the server time to fire up… YUK!
end
def stop
Thread.kill(@thread)
end
def attach(&block)
@block = block
end
def detach()
@block = nil
end
def call(env)
begin
unless @block
raise "Specify a handler for the request using attach(block). The " +
"block should return a valid rack response and can test expectations"
end
@block.call(env)
rescue Exception => e
@parent_thread.raise e
[ 500, { 'Content-Type' => 'text/plain', 'Content-Length' => '13' }, [ 'Bad test code' ]]
end
end
end
【问题讨论】:
标签: ruby multithreading mocking webrick