Skip to content

Instantly share code, notes, and snippets.

@localhostdotdev
Last active March 1, 2019 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save localhostdotdev/1b8773df92c982d48fc3477b5870ce50 to your computer and use it in GitHub Desktop.
Save localhostdotdev/1b8773df92c982d48fc3477b5870ce50 to your computer and use it in GitHub Desktop.
Managing windows with Selenium / Capybara in Ruby

Capybara 3.13.2 / Ruby 2.5.0 / selenium-webdriver (3.141.0) / chromedriver-helper (2.1.0) / ChromeDriver 2.34.522932

Setup

require 'selenium-webdriver'
require 'capybara/dsl'

class C
  extend Capybara::DSL
end

Window management

  • Current windows / tabs: C.windows
  • Switch to window: C.switch_to_window(C.windows.last)
    • The order of the tabs is the one they were opened, if you rearange them, the order stays the same
    • Open each tab for 5 seconds: C.windows.each { |w| C.switch_to_window(w); sleep 5 }
  • Resize window: C.windows.first.resize_to(500, 500)
    • Resize to current screen (macOS, retina display)
coords = system_profiler SPDisplaysDataType | grep Resolution`.scan(/[0-9]+/).map(&:to_i)
C.windows.first.resize_to(coords.first / 2, coords.last / 2)
  • Open new tab: C.open_new_window

Misc

  • Current url: C.current_url

  • Safe execute script (swallows an error that happens every time a command is executed, even when everything goes well):

def safe_execute_script(script)
  C.execute_script(script)
rescue Selenium::WebDriver::Error::UnknownError => e
  puts e.message
end
  • fill_in (uses jQuery and safe execute script to fill in an input)
def fill_in(selector, value)
  safe_execute_script("$('#{selector}').val('#{value}')")
rescue Selenium::WebDriver::Error::UnknownError => e
  puts e.message
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment