Customize Page Navigation By Overriding Geb's getPageUrl()

Feb 23, 2014

gebGeb's page object pattern offers the ability to set a url for a page, that allows you to navigate directly to a page. The url is used when calling the to() method (eg. to myPage).

An application I'm working on includes dynamic elements in its urls; the urls contain a session token, and can include a return page, and/or various content IDs. This makes it essentially impossible to navigate directly to the page. And unless you're testing app navigation, it's better to navigate directly. It keeps your code clean and helps mitigate brittleness.

The solution I've come up with is to parse the current url and use it to navigate directly to my pages. To do this, I needed to override Geb's getPageUrl() (thanks to the Geb user group on this!).

BasePage.groovy

/\*\*
 \* override Geb's getPageUrl method...
 \*
 \* This allows us to navigate directly to pages that have session tokens in the url. To use, create
 \* a static pageName instead of url in your page, and pass it the difference in the url. Then
 \* call to MyPage as you normally would.
\*\*/
String getPageUrl() {
    // if pageName exists, grab the current url and replace pageName in url...
    if(this.class.pageName) {
        getDriver().currentUrl.replaceAll("html#.\*/", "html#/${this.class.pageName}/sessionToken/")
    } else {
        // normal page with url...
        this.class.url
    }
}

In my example above, we override Geb's getPageUrl with our own getPageUrl, added to a BasePage, that we'll extend in our page object. In this new getPageUrl, we want to replace the page name in the url (eg. http://localhost/html#/PAGENAME/...). To do this we grab the current url and just replace the current page name with the target page. All the other elements in the url should be correct.

Now we also need to make sure normal pages continue to operate, so we first test to see if pageName property exists in the page. If not, we execute Geb's normal url code. To get the target pageName, we add it as a static property to the page (instead of url), named pageName. The code would looke something like this:

MyPage.groovy

class MyPage extends BasePage { static pageName = "myPage"

Now we can simply call to MyPage as you would with a page with a normal url. Not too shabby!