Tech It Easy: April 2015

Wednesday, 8 April 2015

Geb - Very Groovy Browser Automation



Dear Java/Testing friends,

Try to have a look at Geb(pronounced as 'Jeb') http://www.gebish.org/, which is a browser automation library built on WebDriver and leverages power of Groovy language and jQuery like content selection (using CSS selectors).
WebDriver is now there in Selenium 2.0  (Selenium 1.0 + WebDriver = Selenium 2.0).


Please find a sample script below. In this script I have also used a cool feature of Groovy language called Groovy Grapes (@Grab). Grapes are like dependencies of the script. We no need to download dependencies and add them to the class path (Grapes does all the heavy lifting for us).

To run the following script you need groovy in the path.

Then run the following command in command prompt

groovy Geb_Demo.groovy

@Grab("org.gebish:geb-core:0.10.0")
@Grab("org.seleniumhq.selenium:selenium-firefox-driver:2.43.1")
@Grab("org.seleniumhq.selenium:selenium-support:2.43.1")
import geb.Browser

Browser.drive {
    go "http://google.com"
 
    // make sure we actually got to the page
    assert title == "Google"
 
    // enter wikipedia into the search field
    $("input", name: "q").value("wikipedia")
 
    // wait for the change to results page to happen
    // (google updates the page dynamically without a new request)
    waitFor { title.endsWith("Google Search") }
 
    // is the first link to wikipedia?
    def firstLink = $("li.g", 0).find("a")
    assert firstLink.text().contains("Wikipedia")
 
    // click the link 
    firstLink.click()
 
    // wait for Google's javascript to redirect to Wikipedia
    waitFor { title.contains("Wikipedia") }
    browser.driver.executeScript("alert('Hello Gopal');")
}