spockgeb

Geb & Spock: Close Browser Between Each Test


I need to close my browser between each test. Geb creates the browser for me, so I am under the impression that Geb should shut down the driver between each test. However it doesn't. Here's a structure and part of the GebConfig.groovy.

test_automation
-functional
--src
---test
---groovy
----spec
-----Test Locations
---resources
----GebConfig.groovy

GebConfig.groovy

waiting {
    timeout = 20
}

environments {
    chrome {
        driver = {
            System.setProperty('webdriver.chrome.driver', 'src/test/resources/chromedriver')
            new ChromeDriver()
        }
    }

    firefox {
        driver = { new FirefoxDriver() }
    }
}

I've extended GebSpec to CommonGebSpec and here are multiple things I've tried:

CommonGebSpec.groovy

def setup() {
    resetBrowser()
    getBrowser()
}

def cleanup() {
    browser.close()
    browser.quit()
}
______________________________

def cleanup() {
    browser.clearCookies()
}
______________________________

def cleanup() {
    resetBrowser()
}

I've tried those specifically and may variations thereof. Anyone know why my browser won't close between tests?

Thanks.


Solution

  • Here's an example with its associated thread on the Geb user list. It's overkill probably for answering your question, but it shows how to quit and start a new browser instance for each test.

    Note that you'll have to quit() the browser yourself after each test.

    import geb.spock.GebSpec
    import pages.RememberMePage
    import spock.lang.*
    import utils.PageHelper
    import org.openqa.selenium.Cookie
    
    class RememberMeLoginSpec extends GebSpec {
        @Shared cookieName = "remember-me"
        @Shared cookieValue = "initial"
    
        def "login user with remember me checked and close browser"() {
            given: 
            PageHelper.login(browser, "userOne", "password1!", true, false)
            cookieValue = driver.manage().getCookieNamed(cookieName).getValue()
            browser.close()
        }
    
        def "user opens browser"() {
            when: "cookie is set and user is logged in"
            browser.config.cacheDriver = false
            browser.driver = browser.config.driver
            RememberMePage rememberMePage = browser.to RememberMePage
            // navigate to a page before setting cookie to avoid 
            // https://code.google.com/p/chromedriver/issues/detail?id=728
            go "pageOne"
            Cookie cookie = new Cookie(cookieName, cookieValue)
            driver.manage().addCookie(cookie)
            // navigate to new page to "login" user
            go "pageTwo"
    
            then: "username appears in greeting and page requiring full authentication shows login modal"
            rememberMePage.navigation.greetingText.text().endsWith("userOne")
            rememberMePage.loginModal.loginModal.present
    
            cleanup:
            browser.quit()
       }
    }