Starting with Selenium

Posted 2012-08-23
Written by Matt Frost
Category code

I was a little scared when it came to setting up Selenium, I figured it was going to be difficult to setup and configure. So I was pleasantly surprised when it really wasn't. So here are a few of the mistakes I made; since I use Vagrant to do all my development I actually grabbed Selenium and started from there. Not a good place to start, although as I found out later; not a total dead end. So after a question I posed on Twitter, a few puzzled responses and the realization that running it on my Mac was a much better starting point; that's essentially what I did. Going forward, I'm assuming you've got PHPUnit and the PHPUnit Selenium extension installed - if you need a quick referral..

sudo pear channel-discover pear.phpunit.de
sudo pear install phpunit/PHPUnit
sudo pear install phpunit/PHPUnit_Selenium

Java and the Selenium Server

Once you have PHPUnit setup appropriately and you have Java installed, you need to grab a copy of the Selenium Server .jar file from here. Now that you have the .jar, Java is installed and you have PHPUnit_Selenium - you need to start the Selenium Server and background it.

java -jar /path/to/selenium-server-standalone-2.25.0.jar &

PHPUnit

The Selenium Server is now running on your Mac, PHPUnit is just waiting for you to write your first PHPUnit_Extensions_SeleniumTestCase. So let's step through a really basic example.

class CheckTitleTest extends PHPUnit_Extensions_SeleniumTestCase
{
    public function setUp()
    {
        $this->setBrowser('*googlechrome');
        $this->setBrowserUrl('http://localhost:8080');
    }
    // test
    public function testTitleIsSetCorrectly()
    {
        $this->open('/');
        $this->assertTitle('My Test Page');
    }
}
What is this little snippet doing? Well let's start with the setup. We're telling the Selenium which browser we're going to use and what URL we're going to be working with. That's pretty much it. Cool so far no?

Now for the actual test, what are we doing there? We'll we have a path relative to the browser URL that we've set and the open method is well named, because it's going to open that path. Finally we have our first somewhat familiar face, an assertion. When we call the assertTitle method, we're passing in the title we expect to see, if it matches we pass otherwise we fail.

In summation

It was really cool to see the Selenium Server launch my web browser and come back with my test results, and while this example may not be the most practical example; I believe it demonstrates a very basic interaction. You should checkout the PHPUnit and Selenium Documentation - to see all the assertions that are available to you. I'd have posted a more robust example, but I just figured all this stuff out today. I was really blown away at how quickly I was able to get everything set up.

Comments

There are no comments

Posting comments after has been disabled.