Marcin Erdmann

Groovy, Grails, Geb...

Resizing browser window in Geb tests

It sometimes proves useful to be able to resize browser window in your Geb tests. Up to not so long ago WebDriver (which is used by Geb to drive browsers) did not provide such a functionality and you had to resort to different hacks that never worked in all of the browsers, but thankfully nowadays it is pretty straightforward.

To make sure that the browser window is maximised before any tests are executed we can add the following to the driver closure in GebConfig.groovy:

driver = {
    def driverInstance = new FirefoxDriver()
    driverInstance.manage().window().maximize()
    driverInstance
}

One of the possible usages of browser window resizing can be testing responsive sites. So for example if we want to write a specification that performs some tests on the site laid out as for an iPhone 4 and then maximise the site when done we could use the following:

class IPhone4Spec extends GebSpec {

    void setupSpec() {
        driver.manage().window().size = new Dimension(640, 960)
    }

    void cleanupSpec() {
        driver.manage().window().maximize()
    }

    (...)

}

As a side note, it seems like you can also modify the position of the browser window using the WebDriver.Window class instance which can be retrieved using driver.manage().window() but I can't think of how that could be useful.