If you want to run your tests headlessly on a Continuous Integration (CI) server you’ll quickly realize that you can’t with an out-of-the-box setup since there is no display output for the browser to launch in. You could use a third party library like Xvfb (tip 38) or PhantomJS (tip 46) but those can be hard to install and aren’t guaranteed to be supported in the long run (like PhantomJS).
Enter Headless Chrome. Headless is simply a mode you can put Chrome into that allows it to run without displaying on screen but still gets you the same great results. This is a better option than using Chrome in a Headless manner such as in a docker container where the the container actually uses Xvfb.
Starting with Chrome 59 (Chrome 60 for Windows) we can simply pass Chrome a few configuration options to enable headless mode.
An Example in Ruby
Before we start make sure you’ve at least got the latest version of Chrome installed along with the latest version of ChromeDriver.
Let’s create a simple Selenium script (the example is posted below).
- We will pull in the requisite libraries and then create our
setupmethod where we will pass Chrome our headless option as a command line argument. The first add_argument of ‘– headless’ allows us to run Chrome in headless mode. The second argument is, according to Google, temporarily required to work around a few known bugs. The third argument is optional but gives us the ability to debug our application in another browser if we need to (using localhost:9222).
- Now let’s finish our test by creating our
Here we are loading a page, asserting on the title (to make sure we are in the right place), and taking a screenshot to make sure our headless setup is working correctly. Here’s what our screenshot looks like:
When we save our file and run it (e.g.
ruby headless_chrome.rb) here is what will happen:
- An empty chrome browser instance will open
- Test runs and captures a screenshot
- Browser closes
Hopefully this tip has helped you get your tests running smoothly locally or on your CI Server. Happy Testing!
This was originally written for and posted on the Elemental Selenium newsletter. I liked it so much I decided to cross post it with some updates.
Oh and if this article worked for you please consider sharing it or buying me coffee!