Specs2: How to turn a Seq[Matcher[A]] into a single Matcher[A]?

647 views Asked by At

Given a sequence Seq[Matcher[A]] I want to obtain a single Matcher[A] that succeeds when all matchers inside the sequence succeed.

Edit

The answer provided by myself seems a bit clumsy and in addition it would be nice if all failing matchers of the sequence produced a result

2

There are 2 answers

9
ziggystar On

Ok, I've found a way:

(matchers: Seq[Matcher[A]]).reduce(_ and _)

Somehow I thought there has to be a different way, like writing _.sequence.

0
iwein On

The problem with creating a new matcher from the matcher sequence is that it becomes harder to find which matcher failed.

The better option in my opinion is to match against each matcher separately like so:

val matchers: Seq[Matcher[Boolean]] = Seq(
  ((_: Boolean).equals(false), "was true 1"),
  ((_: Boolean).equals(true), "was false 2"),
  ((_: Boolean).equals(true), "was false 3")
)

"work with matcher sequence" in {
  matchers.foreach(beMatching => false must beMatching)
}

You can see from the output that the matchers are invoked separately and the first failure causes a test failure with the message of that matcher.

Depending on the case you have it might even be better to generate Expectations for each matcher, so it will execute them all and show you a proper overview, not just the first failure. I didn't go that far (yet).