algui91 algui91 - 19 days ago 5
Scala Question

Writing Given/Then/When specs with complex objects

I am trying to make use of

GWT
specs with full support, but the examples of its official documentation are a bit simple.

Searching in SO I found this question:



But it is too old (3 years) and I think the way of doing
GWT
in
specs2
has changed.

So far I have this simple test:

class FlowCollectorSpec extends Specification
with GWT
with StandardRegexStepParsers { def is = s2"""

Given a API route to get flows ${apiCaller.start}
Given an access to the API URL: http://192.168.56.102:8080/stats/flow/
When getting flow stats for a switch with id: 1
Then status code should be: 200 ${apiCaller.end}
"""

val anAPIUri = readAs(".*: (.*)$").and((s: String) => s)

val apiCaller =
Scenario("apiCaller").
given(aString).
given(anInt).
when(anAPIUri) {case url :: dpid :: _ => FlowCollector.getSwitchFlows(dpid)}.
andThen(anInt) {case expected :: actual :: _ => actual.code must_== expected}
}


How could I specify a complex object in a Given statement? something like this:

Given a Json response: ${jsonResponse}

Answer

If your data is complex and cannot be displayed on one line you can simply write

 class FlowCollectorSpec extends Specification
  with GWT
  with StandardRegexStepParsers { def is = s2"""

 Given a API route to get flows                                                 ${apiCaller.start}
   Given an access to the API URL:     http://192.168.56.102:8080/stats/flow/
   Given some complex data
   When getting flow stats for a switch with id: 1
   Then status code should be: 200                                              ${apiCaller.end}
"""

  val anAPIUri = readAs(".*: (.*)$").and((s: String) => s)

  val apiCaller =
    Scenario("apiCaller").
      given(aString).
      given(complexData).
      given(anInt).
      when(anAPIUri) { case url :: Json(j) :: dpid :: _ => FlowCollector.getSwitchFlows(dpid) }.
      andThen(anInt) { case expected :: actual :: _ => actual.code must_== expected }

  val complexData = readAs(".*").andThen(_ => Json("some json"))

  case class Json(value: String)

  object FlowCollector {
    def getSwitchFlows(dpid: Int) = FlowResult(code = 200)
  }

  case class FlowResult(code: Int)
}

Otherwise your solution is the right one.

Comments