title: Inject JS file into capybara chrome headless
body: <p>I have RSpec with Capybara and Chrome Headless in my tests. For some pages, I load external JS files where other javascripts depends on.</p>
  
  <p>I'd like to make my tests independent of this external JS calls, e.g. when I'm offline they won't work and throw JS errors. Changing the production code (e.g. testing the environment and then load or don't load files or execute scripts) feels extremely ugly, so this won't be an option.</p>
  
  <p>Therefore, I was thinking about injecting some sort of mocking script into the browser on every page visit. The problem is, methods like <code>page.evaluate_script</code> or <code>page.execute_script</code> only run the script when the page is loaded. And at this point, the production JS code already threw an error.</p>
  
  <p>I was searching around trying to find a solution, but I haven't found an option for chrome headless to load a file or execute scripts on every page load.</p>
  
  <p>My setup currently looks like this</p>
  
  <pre><code>Capybara.register_driver :chrome_headless do |app|
    options = Selenium::WebDriver::Chrome::Options.new
    options.add_argument("no-sandbox")
    options.add_argument("headless")
    options.add_argument("disable-gpu")
    options.add_argument("window-size=1400,1400")
  
    capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
      acceptInsecureCerts: true
    )
  
    Capybara::Selenium::Driver.new(
      app, browser: :chrome, options: options, desired_capabilities: capabilities
    )
  end
  Capybara.javascript_driver = :chrome_headless
  </code></pre>
  
  <p>I also tried to build an extension and use it with </p>
  
  <pre><code>options.add_extension("spec/support/chrome_extension_test_helper/chrome_extension_test_helper.crx")
  </code></pre>
  
  <p>but it seems that the extension is not loaded (I added a <code>console.error("foobar")</code> in the extension but nothing is shown. So maybe self signed extensions are not allowed? Furthermore, I would want to build such an extension on the fly without having to pack it through chrome every time I change something.</p>
  
  <p>So, is there a way to load a mock JS file into chrome headless with capybara?=</p>