How to login before executing Geb tests

843 views Asked by At

I've got REST webservice based on Grails. There's obligatory authentication before you can access any page except login. I use Geb & Spock for integration tests, running through Gradle. My question is: how can I provide authentication before executing any test? I have 2 ideas:

  1. Run tests in order (log in at first, then run others). How? (must be triggering by command gradle integrationTest)
  2. Execute JS script before every test which authenticate me. How to implement this in test?
2

There are 2 answers

0
Jay On BEST ANSWER

What kind of authentication? For Basic authentication have a look at: HTTP Basic Authentication credentials passed in URL and encryption so you could just add that to your base url.

If you have to go through the login process, you can use the setupSpec() and setup methods. The former gets executed before anything else happens, the latter before each individual test method.

You can use the @Stepwise notation to stop cookies from being deleted between test methods. If you have different geb classes and want all of them to be prepended with your setup or setupSpec method, use the extends notation:

class BaseClass extends GebSpec {
    def setupSpec() {
        <loginProcess>
    }
}

@Stepwise
class ASpec extends BaseClass {
    testMethod() { }
}

@Stepwise
class BSpec extends BaseClass {
    testMethod() { }
}

note that this will execute the login process one extra time because it happens in the BaseClass as well. I got around this with an

if (this.getClass().getPackage().getName() != "gebMethods")

block but I guess there might be a more elegant solution.

0
erdi On
  1. If it's a web service I'd not use Geb for testing it. Geb is a tool for driving browsers and REST web services are best tested using http clients, like REST-assured.

  2. I would make authentication configurable in the app and disable it for most tests apart from ones that explicitly test authentication.