In the last days I experimented with Selenium (thanks to knoebi for the hint). What is Selenium? Here the description from the website:
Selenium is a test tool for web applications. Selenium tests run directly in a browser, just as real users do.
I have to admit that I like Selenium, and so I will describe in this post how to use it with CakePHP.
First the installation:
- Download Selenium from http://www.openqa.org/selenium-core/download.action (I recommend to download the newest version)
- If you downloaded version 0.6 of Selenium: Copy the “selenium” folder from the zip to your “app/webroot” folder
- If you downloaded version 0.7.0 of Selenium: Copy the content of the “core” folder from the zip to “app/webroot/selenium”
- Download the code snippets from the download section and put the files in the correct folders
So, with that we are ready to write our first, very simple Selenium test case.
Test cases are organized in test suites, so we create first such a test suite in “app/views/pages/tests/”. You may wonder why we create the test suite in a subfolder of “views”. The reason is simple: Selenium tests are written in plain html. Here is our test suite:
<?php // testsuite-login.thtml $selenium->suiteTitle('My first testsuite'); $selenium->addTestCase('Login', 'test_login'); ?>
Let us write our test case. We want to test if we can login into our application and if we are redirected to the correct page. The code should be self-explanatory (if not, please write a comment or have a look in the Selenium reference)
<?php // test_login.thtml $selenium->caseTitle('Login'); $selenium->open('/login'); $selenium->type('name=data[User][username]', 'dho'); $selenium->type('name=data[User][password]', 'test'); $selenium->clickAndWait('submit'); $selenium->assertLocation('/users/dho'); $selenium->assertTextPresent('Daniel Hofstetter'); ?>
That’s it, we are ready to run our test suite. For doing that, we have to switch to our browser and type http://localhost/selenium/TestRunner.html?test=/pages/tests/testsuite-login (if you have several test suites and you do not want to remember such long urls you can edit “app/webroot/selenium/index.html” and add the urls there. The only url you have to remember in this case is http://localhost/selenium). On the right side we have to click on the “All” button and the test starts. Yeah, everything is green, at least here ;-)
Update (2006-05-26): Download link for Selenium modified, added instructions for Selenium 0.7.
Update (2006-11-06): For Selenium 0.8 you can find instructions at http://cakebaker.42dh.com/2006/10/04/new-selenium-helper/.