From a8a4efc3790daa6f146c8bb51c7350b4b8dd518d Mon Sep 17 00:00:00 2001 From: Bernerd Schaefer Date: Tue, 6 Jul 2010 16:03:32 -0500 Subject: [PATCH] Use TCPServer to find available port for server This protects against the race conditions which inevitably occur when booting multiple capybara servers (such as running specjour). TCPServer.new() will set recently opened sockets to SOCK_WAIT status to ensure that a certain amount of time elapses before they are reused. --- lib/capybara/server.rb | 20 ++++---------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/lib/capybara/server.rb b/lib/capybara/server.rb index 5f145426..b0f41037 100644 --- a/lib/capybara/server.rb +++ b/lib/capybara/server.rb @@ -83,8 +83,10 @@ class Capybara::Server private def find_available_port - @port = 9887 - @port += 1 while is_port_open?(@port) and not is_running_on_port?(@port) + server = TCPServer.new('127.0.0.1', 0) + @port = server.addr[1] + ensure + server.close if server end def is_running_on_port?(tested_port) @@ -97,18 +99,4 @@ private return false end - def is_port_open?(tested_port) - Timeout::timeout(1) do - begin - s = TCPSocket.new(host, tested_port) - s.close - return true - rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH - return false - end - end - rescue Timeout::Error - return false - end - end