October 2, 2012

# Grokking Geb - Prerequisites

Extremely sorry about the delay on Part 2 of this series. Graduate exams are just round the corner and I am unable to find time for quality research. Exams get over by end of November.

I thoroughly enjoy Geb and I think it is the most stylish way to write functional tests.

**So, the Prerequisites : **

1. Some Groovy Magic. Most of all that you need to learn Groovy is covered in this manual but for obvious reasons if you get obsessed with the language you might want to consider Groovy in Action. If you are from a Java (except for closures) or a Python background, you could probably skim through the tutorial for 15 minutes and you are there already).

2. A little Selenium. The more, the better but fear not this single page tells you all that you need to know about the Selenium Webdriver that you would generally use.

3. jQuery selectors (everybody says that it is easy but frankly, I refer to the manual at least twice per hour. I am dumb, so…). If you are new to jQuery, you would want to start from basic selectors and click on the left navigation menu for more.

4. PageObjects is actually not a prerequisite for Geb but PageObjects are so awesome that you never wanted to think about Geb outside of it. Interestingly, PageObjects is not a technology that you need to pick. It is cute little pattern which says that you wrap the structure of your HTML page into an Object so that the actual test does not have to deal with it. Hah. Got you. Let me put that in plain English.

Say, you have a registration form with input textbox which has an id of "nametext". How would you get the handle of the textbox? In DOM terms, in javascript, you would just do a

	document.getElementById("nametext")


In Selenium, you would do a very similar thing

	driver.findElement(By.id("nametext"))


So, if you would want to populate Jason in your text box in Selenium, you would do a

	driver.findElement(By.id("nametext")).sendKeys("Jason");


If you do that for all your input fields, very soon your testcases become ugly and hateful. Instead of that, in OO terms, you encapsulate. You create a new class, say RegistrationPage and wrap your findElement and sendKeys as in :

	public class RegistrationPage{

…

public RegistrationPage fillRegistrationForm(String name, String email){

driver.findElement(By.id("nametext")).sendKeys(name);
driver.findElement(By.id("emailtext")).sendKeys(email);

}

}


and from your testcase, you would say


RegistrationPage regPage=new RegistrationPage();
regPage.fillRegistrationForm("Jason","jason@bourne.com");



(Even better idea is to wrap your input values into a class and pass it to the fillRegistrationForm)

In fact, Geb leverages PageObjects in a much better way - jQuery selectors to the rescue


class InputFormPage extends Page{

…

static content={
name {$("input", id:"entry_0")} emailAddress {$("input", id:"entry_1")}
}
}


and in your testcase, you would just say

name.value ("Jason")