Can I automate Chrome request blocking using Selenium-webdriver for Ruby?

centuryfall picture centuryfall · Oct 23, 2017 · Viewed 8.1k times · Source

I am a QA automation analyst responsible for testing a multi-platform online banking application. For our automation testing we use RubyMine suite with Gherkin/Cucumber, Ruby-scripted steps and Selenium-webdriver, Watir and page-object gems/libraries.

I have a number of scripts that I cannot automate completely without manual intervention, and these include blocking certain network calls through Telerik Fiddler to produce warning pages or error messages, etc. The future of our automation would be to do this through RubyMine instead of Fiddler for network blocking. I know there is a way to do this in Chrome using Inspect Element and the Network menu using enable request blocking. However, I cannot figure out a way to force Chrome through Ruby/Selenium to block a given request. The only way is do manually do it myself, and therefore I can't actually automate these as wanted.

So, my question -- is this a possibility to automate request-blocking with Selenium-webdriver? And, if so, where should I begin to look for help with this?

Thanks.

Answer

Florent B. picture Florent B. · Oct 23, 2017

To block URLs from loading with Selenium with the DevTool API:

def send_cmd(driver, cmd, params={})
  bridge = driver.send(:bridge)
  resource = "session/#{bridge.session_id}/chromium/send_command_and_get_result"
  response = bridge.http.call(:post, resource, {'cmd':cmd, 'params': params})
  raise response[:value] if response[:status]
  return response[:value]
end

send_cmd(driver, "Network.setBlockedURLs", {'urls': ["*"]})
send_cmd(driver, "Network.enable")