How to setup headless selenium with chromedriver for PHPUnit tests

GitHub source

Setting up Selenium with chromedriver for PHPUnit tests was causing me some headaches. Lots of Googling and experimenting later I have it working stably and you can borrow all of the config/files I used from GitHub.

Let's get crackin'

Partially from GitHub README.md

Ingredients

Recipe

Mac

Linux

Linux Server/Vagrant

  • Run selenium-chrome.sh on your Vagrant box or server to automatically install all dependencies, and run selenium - this was tested on Ubuntu 14.04
  • Run PHPUnit: composer install; vendor/bin/phpunit
  • Look at all that green, oh yea!

Windows

If you know how to run this on Windows, please let me know or create a pull request!

Now for the tests

<?php

class SeleniumTests extends PHPUnit_Extensions_Selenium2TestCase {

    public function setUp() {
        $this->setHost('localhost'); // Our Selenium instance is on localhost
        $this->setPort(4444); // This is the default selenium port

        $this->setBrowser('chrome'); // We're using the chromdriver.  You can also use firefox or IE
        $this->setBrowserUrl('https://www.google.com'); // What we're testing
    }

    public function tearDown()
    {
        $this->closeWindow(); // The class says we should have the 'close' method but we don't, so we're using closeWindow
    }

    public function testGoogleSearchButtonExists() {
        $this->url('/');

        $this->assertContains('Google Search', $this->source());
    }

    public function testCanSearch() {
        $this->url('/');

    $inputElement = $this->byName('q');
    $this->keys('Cheese Burger');
    $inputElement->submit();

    $that = $this;

    // Wait until the AJAX loads the results (as we submitted the search form just above, so our chrome is currently AJAXing the results)
    $this->waitUntil(function() use($that) {
        return $that->byId('resultStats');
    }, 5000);

        $this->assertContains('McDonalds', $this->source()); // This is a dreadful test as McDonalds won't always be on the first page of Google Results :)
    }

}