title: Headless operations don't work inside Sinatra route
body: <p>I am using the <code>headless</code> and <code>selenium-webdriver</code> gems to launch a headless Firefox browser:</p>
  
  <pre class="lang-rb prettyprint-override"><code>headless = Headless.new(
    video: {
      frame_rate: 12,
      codec: 'libx264'
    }
  )
  headless.start
  driver = Selenium::WebDriver.for(:firefox)
  </code></pre>
  
  <p>With this code I can write the following:</p>
  
  <pre class="lang-rb prettyprint-override"><code>driver.navigate.to("http://google.com")
  </code></pre>
  
  <p>Yet the following raises an error after I visit '/' in the browser:</p>
  
  <pre class="lang-rb prettyprint-override"><code>get '/' do
    driver.navigate.to("http://google.com")
    erb :root
  end
  </code></pre>
  
  <p>The error is as follows: </p>
  
  <pre><code>*** Errno::ECONNREFUSED Exception: Failed to open TCP connection to 127.0.0.1:7055 (Connection refused - connect(2) for "127.0.0.1" port 7055)
  </code></pre>
  
  <p>I'm pretty sure this is because the <code>driver.navigate</code> is not being called in the headless scope, therefore it can't connect to the Firefox instance. </p>
  
  <p>I have also tried using the modular sinatra style, but the same error occurred. </p>
  
  <hr>
  
  <p><strong>workaround</strong></p>
  
  <p>What I ended up doing is separating the headless server in a separate script. This script has <code>loop</code> and gets input, printing the output of running the command in the headless scope. Then from the sinatra server, i use <code>PTY.spawn</code> to instantiate the server and pass around its stdin and stdout so I can use it in my Sinatra app. This way the headless script is only run once (therefore multiple headless servers aren't started) and I can connect to it from my Sinatra routes. I can't interact with the headless script's variables or methods directly - I need to just use i/o. </p>
  
  <p>I am hoping for an answer which hows how to make the original code work, though (when the sinatra app's routes are called in headless scope)</p>