Spek operations not respecting locality

I've been using Spek since its announcement a few days ago. It's been a great little tool so far, but this is something I have to question.

The code I wish to test

fun <K, V : Comparable<V>> Map<K, V>.max(): Pair<K, V>? {   if (isEmpty()) return null

  val max = entrySet().reduce {
  current, next -> if (current.getValue() < next.getValue()) next
                   else current
  }

  return Pair(max.getKey(), max.getValue())
}


My tests:

class MapUtilsSpec: Spek() {{   given("A map") {   val map = HashMap<Int, Int>()

  &nbsp;&nbsp;on("with zero insertions") {

           it(“returns null for max()”) {
           val max = map.max()

           assertTrue(max == null,
                           “There should be no max value, but was $max”)
           }
  }

  &nbsp;&nbsp;on("with one insertion") {

           map.put(1, 1)

           it(“returns the single entry as max”) {
           val max = map.max()

           assertEquals(Pair(1, 1), max,
                           “Expected (1, 1) as maximum, but was $max”)
           }
  }
  }
}}


If I execute the tests, my first test will fail because (1, 1) is already inserted. If I move the map.put(1, 1) statement down into the it-block, everything works as expected. Is this by design? If so, why?

Hi Christian,

Currently there is a limitation in that a given is not “reset” between every action. We’ve been looking at ways of solving this and some options are on the table, but nothing implemented yet.

In your case however, I’m thinking that your context may actually be different? In the first case you have an empty map, while in the second one you have a map with one element. So essentially two different contexts, which mean two different givens.