Search code examples
seleniumgroovyphantomjsgeb

How to set a cookie in Geb / Selenium with PhamtomJS


How do you set cookie in Geb ? I'm running into the following error with the given example:

org.openqa.selenium.InvalidCookieDomainException: {"errorMessage":"Can only set Cookies for the current domain" ....

.. Ive also tried explicitly setting the cookie domino using the Cookie Builder though that only cause another exception : org.openqa.selenium.UnableToSetCookieException: {"errorMessage":"Unable to set Cookie"}

Note that I used to have a baseURL in the GebConfig.groovy file .. but I have removed it as well .. Other then PhantomJS driver config, there are no settings in the config file.

I'm on OSX and using PhantomJS latest version (1.3.0 jar, and 2.1.1 driver OSX).

Note the example DOES work using the Chrome Webdriver for some reason.

import geb.spock.GebSpec
import org.openqa.selenium.Cookie

class SetCookieIT extends GebSpec {
    def "Cookie example"() {
        given:
        def options = driver.manage()

        when:
        go "https://www.wikipedia.org/"
        then:
        !options.getCookieNamed("my-geb-cookie")

        when:
        options.addCookie(new Cookie("my-geb-cookie", "foobar"))
        go "https://www.wikipedia.org/"
        then:
        title == "Wikipedia"
        options.getCookieNamed("my-geb-cookie").value == "foobar"
    }
}

Solution

  • Wikipedia is not spelt with an "ie" in the domain name and "org.com" also looks very strange. Maybe next time you want to provide an example which is actually executeable and does something meaningful. :-7

    For me this works nicely:

    package de.scrum_master.stackoverflow
    
    import geb.spock.GebReportingSpec
    import org.openqa.selenium.Cookie
    
    class SetCookieIT extends GebReportingSpec {
      def "Cookie example"() {
        given:
        def options = driver.manage()
    
        when:
        go "https://www.wikipedia.org/"
        then:
        !options.getCookieNamed("my-geb-cookie")
    
        when:
        options.addCookie(new Cookie("my-geb-cookie", "foobar"))
        go "https://www.wikipedia.org/"
        then:
        title == "Wikipedia"
        options.getCookieNamed("my-geb-cookie").value == "foobar"
      }
    }
    

    If you have any further problems, please update your question and provide an SSCCE reproducing the actual problem.


    Update after the question was modified: The problem with PhantomJS is that it refuses to create cookies if you do not explicitly specify the domain. This works:

    options.addCookie(new Cookie("my-geb-cookie", "foobar", ".wikipedia.org", "/", null))