Synchronize threads to the WEBrick server start <p>I am trying to start a small WEBrick server to mock a real API, to test a Ruby http client I am developing. I am using a modified solution of the one based in <a href="http://dynamicorange.com/2009/02/18/ruby-mock-web-server/#comment-4546" rel="nofollow">this</a> blog comment.</p> <p>It works fine, but the problem is that each time the server starts, the parent thread has to wait an arbitrary amount of time for the server to load. And after adding several tests it gets really slow.</p> <p>So my question is: <strong>is there a way to synchronize the parent thread to continue right after the server thread has finished starting WEBRick?</strong></p> <p>I tried looking at the WEBrick reference, searched the web and even had a look in the WEBrick code, but I got nothing I could use without some really nasty monkey patching.</p> <p>I'm open to other approaches to the problem, but I would like to keep it as dependency-free to gems and libraries as possible. Also, the solutions <strong>must</strong> run in <strong>Ruby 1.9.2</strong>, on <strong>Linux</strong>.</p> <p>Thanks in advance for the answers!</p> <pre><code>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 =&gt; port, :Host =&gt; "127.0.0.1") end sleep pause # give the server time to fire up… YUK! end def stop Thread.kill(@thread) end def attach(&amp;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 =&gt; e @parent_thread.raise e [ 500, { 'Content-Type' =&gt; 'text/plain', 'Content-Length' =&gt; '13' }, [ 'Bad test code' ]] end end end </code></pre>