Search code examples
scalaspecs2

Can Specs2 compare sequence elements with one of the existing matchers?


I want to compare 2 sequences of doubles in a specs2 test, something along the lines of:

actualValues must containTheSameElementsAs(expectedValues, _ beCloseTo _)

I can write a manual comparison like

actualValues must containTheSameElementsAs(expectedValues, (a, b) => math.abs(a - b) < 0.001)

but that seems a bit pointless as beCloseTo is already available.

On a wider note, is there a good source of documentation for Specs2? I looked at the user guide but the search in that for "containsAllOf" shows no results and the matchers section doesn't have any entry about collections as far as I can tell.


Solution

  • Most of collection matches should be expressible with contain + combinators. In this case you can write

    List(1.3, 1.7) must contain(beCloseTo(1.5 +/- 0.5)).forall
    

    where forall tests each element. You could replace forall with atLeastOnce if you wanted to test that only one element satisfies your property.

    You could also write it like this if you want the "forall" word to appear sooner in your statement

    forall(List(1.0, 2.0)) { n =>
      n must beCloseTo(1.5 +/- 0.5)
    }
    

    This comes from the MatcherImplicits trait mixed into the Specification but I agree, this is not well-documented.