Geb Programmer : How to access Cookies with Geb?

Lets say we visit the Codemotion agenda; an upcoming Conference in Spain.

We can check whether the website stores any cookies. As shown below it does:

codemotion_spain_-_for_the_communities__by_the_communities

Let say we want to access those cookies with Geb. Web Driver to the rescue.

Geb builds on the WebDriver browser automation library, which means that Geb can work with any browser that WebDriver can

With the help of Web Driver we can get a Set of Cookie objects.

Set<Cookie> cookies = browser.driver.manage().getCookies()

I have put together a method to join cookie name and value as a String.


package codemotion.geb

import geb.Browser
import org.openqa.selenium.Cookie

class GebUtils {
    private static String getCookiesAsString(Browser browser, String delimiter = ';') {
        Set<Cookie> cookies = browser.driver.manage().getCookies()
        String cookiesStr = null
        if ( cookies ) {
            cookiesStr = cookies.collect { Cookie cookie -> "${cookie.name}=${cookie.value}" }.join(delimiter)
        }
        cookiesStr
    }
}

You can verify that a particular website stores cookies with a test such as:

package codemotion

import codemotion.geb.AgendaPage
import codemotion.geb.GebUtils
import geb.Browser
import spock.lang.Specification

class CookiesSpec extends Specification {

    def "verify codemotion website stores cookies"() {

        when:
        def browser = new Browser()
        browser.baseUrl = 'http://2016.codemotion.es/'
        browser.to AgendaPage
        def cookiesStr = GebUtils.getCookiesAsString(browser)
        then:
        cookiesStr
    }
}

Do you like to read about Grails / Geb / Groovy development? If the answer is yes, subscribe to Groovy Calamari. A weekly curated email newsletter about the Groovy ecosystem. Curated by me 🎉

One thought on “Geb Programmer : How to access Cookies with Geb?

Leave a Reply

Your email address will not be published. Required fields are marked *