Opening several threads with watir-webdriver results in 'Connection refused' error Opening several threads with watir-webdriver results in 'Connection refused' error selenium selenium

Opening several threads with watir-webdriver results in 'Connection refused' error


You're basically creating a race condition between the instances of your browser to connect to the open port watir-webdriver is finding. In this case, your first instance of the browser sees that port 9517 is open and connects to it. Because you're spinning up these instances in parallel, your second instance also thinks port 9517 is open and tries to connect. But oops, that port is already being used by the first browser instance. That's why you get this particular error.

This also explains why the sleep 2 fixes the issue. The first browser instance connects to port 9517 and the sleep causes the second browser instance to see that 9517 is taken. It then connects on port 9518.

EDIT

You can see how this is implemented with Selenium::WebDriver::Chrome::Service#initialize (here), which calls Selenium::WebDriver::PortProber (here). PortProber is how the webdriver determines which port is open.