Debugging Selenium code with IRB

Occasionally something will change in our system under test that breaks a Selenium test (or two). Most of the time we can walk through the failure, make some tweaks and run it again – repeating the process until it passes. Depending on how long it’s been since we last worked with the code, or how deeply buried the code is, it may not be enough to fix the test and we may have to tackle one or more of the underlying methods we used to build the code.

In these situations it can be helpful to debug our tests using an interactive prompt or REPL. In the case of Ruby we can use irb or Interactive Ruby to manually step through the Selenium actions, watching and learning. Here’s the general format for working with Selenium in irb; it’s very similar to how we code it:

  1. Launch interactive ruby: irb
  2. First, import the Selenium library: require 'selenium-webdriver'
  3. Second, create an instance of Selenium and launch the browser: driver = Selenium::WebDriver.for :firefox
    1. If you’ve got Chrome installed with an updated PATH, you can also swap firefox for chrome.
  4. Third, start entering your Selenium commands: driver.get ''

Here’s a simple example using irb:

In this example I’m bringing up Chrome as my browser and navigating to Google. I’m finding the search query box, typing my last name ‘Kenst’ and clicking enter. Thus an example of searching Google for my last name!

Technically once the browser is up we can navigate to whatever page we need without typing ALL of the individual commands. This is really valuable in those instances when you need to login, then navigate several pages before getting to the place you can debug. In other words do all the setup outside of irb, directly in the browser. Once you are in the proper location step through your code one command at a time (and lines with => show the responses to our commands, if any). Those responses will help us debug our tests by confirming what elements Selenium is picking up and what our methods are returning (if anything).

Additional References:

  • Andrew Morton

    I use the Pry gem to debug. It drops you into a REPL from wherever you call it, allowing you to run your code up to a debug point. Usage is as simple as

    require ‘pry’

    • Thanks for the tip, I’ll give it a try.

      • Eric Thomson

        Thanks for the tip. Since I usually just use an editor, I miss the debug mode of an IDE. This gives me a way to step through the code.

  • Chris G. Sellers

    This works great, except when the action of instantiating the webdriver causes firefox to die and become defunct, how do I see what is happening then? 🙂

    • I’m not sure if I’ve seen that but in any case, more information would probably help. See if you can turn on logging and see what additional information you can get. (This might be a decent reference: Also make sure you’ve got the latest browser and driver versions.