Search code examples
scalacucumbercdiguicepicocontainer

Passing variables between Cucumber step definitions


In Cucumber, how do i go about passing variables between step definition classes. Im trying to implement in Scala.

Looking around I have seen people suggest using Guice or Picocontainer or any other DI framework. But have not really come across an example in Scala.

For instance for the example below how do I pass the variable using DI ?

Provider.scala,

class Provider extends ScalaDsl with EN with Matchers with WebBrowser {
  ......

  When("""I click the Done button$""") {
    val doneButton = getElement(By.id(providerConnectionButton))
    doneButton.click()
  }

  Then("""a new object should be created successfully""") {
    // Pass the provider ID created in this step to Consumer definition
  }
}

Consumer.scala,

class Consumer extends ScalaDsl with EN with Matchers with WebBrowser {
  ......

  When("""^I navigate to Consumer page$""") { () =>
    // providerId is the id from Provider above
    webDriver.navigate().to(s"${configureUrl}${providerId}")
  }
}

Solution

  • You can use ThreadLocal to solve your problem

    Here's code snippet for solution.

    object IDProvider{
          val providerId = new ThreadLocal[String]
          def getProviderId: String = {
               providerId.get()
          }
    
          def setProviderId(providerId: String): Unit = {
               providerId.set(providerId)
          }
    }
    

    To access providerID across different step definitions. You can simply call IDProvider.getProviderId

    And to set the value of providerID, simply call IDProvider.setProviderId(PROVIDER_ID)