How to use Webdriver Testcontainers with Geb/Spock

Combine very Groovy browser automation with instant test browsers via Testcontainers

Michael Kutz
Jan 31 · 2 min read

Getting a browser on you CI/CD environment is one very common problem when doing web UI tests. Testcontainers solves this issue quite well by simply relying on Docker to create a container, which has the container installed.

The documentation about this –and also most examples that can be found– are using JUnit to demonstrate the configuration of the Testcontainers and actually this can be transferred to Spock as described in the docs. However, transferring the Webdriver Testcontainer to my Geb tests.

Geb’ config mechanism uses a Groovy config script (see ConfigSlurper) to create the WebDriver, so it makes sense to create the Testcontainer in that script. So let’s do this!

As described in the documentation we need to add a test dependency (org.testcontainers:selenium) to our build. Now we can create a Selenium Testcontainer in our GebConfig.groovy. E.g. for Chrome:

new BrowserWebDriverContainer()
.withCapabilities(new ChromeOptions())

The docs suggest that we can now just set Geb’s driver to one which is generated by the container:

driver = {
new BrowserWebDriverContainer()
.withCapabilities(new ChromeOptions())
.getWebDriver()
}

However, this fails with a DriverCreationException caused by something like this:

geb.driver.DriverCreationException: callback ‘script1548932529655249223472$_run_closure2@26fb4d06’ returned ‘null’ which is not a WebDriver implementation

This is due to the fact, that the container is not being started automatically, but by JUnit if you use it as a Rule. So what we simply need to do is simply starting the container before getting the WebDriver:

driver = {
def container = new BrowserWebDriverContainer()
.withCapabilities(new ChromeOptions())

// need to start the container since we are not using a @Rule
container.start()

conatiner.getWebDriver()
}

Here is a minimal Gist for your GebConfig.groovy. It configures local Chrome by default, but if you set gebEnv to dockerChrome or dockerFirefox it relies on Testconatiners to fire these up.

Michael Kutz

Written by

I've been a software engineer since 2009, worked in various agile projects & got a taste for quality assurance. Today I'm a quality engineer at REWE digital.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade