views:

69

answers:

2

If I have a Matcher[A] how do create a Matcher[Iterable[A]] that is satisfied only if each element of the Iterable satisfies the original Matcher.

class ExampleSpec extends Specification {
  def allSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = error("TODO")
  def notAllSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = allSatisfy(m).not    

   "allSatisfy" should {
     "Pass if all elements satisfy the expectation" in {
      List(1, 2, 3, 4) must allSatisfy(beLessThan(5))
    }

    "Fail if any elements do not satisfy the expectation" in {
      List(1, 2, 3, 5) must notAllSatisfy(beLessThan(5))
    }
  }
}
+5  A: 

I certainly don't claim to be a Specs expert, so my code very likely can be much improved upon. In any case, I was able make it work like this:


class ExampleSpec extends Specification {
  def allSatisfy[A](m: Matcher[A]): Matcher[Iterable[A]] = new Matcher[Iterable[A]]() {
    def apply(v: => Iterable[A]) = {
      val iterable = v
      (iterable.forall(e => {println("checking el " + e); m(e)._1}), "all elements match", "not all elements match")
    }
  }

  def notAllSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = allSatisfy(m).not

  "allSatisfy" should {
    "Pass if all elements satisfy the expectation" in {
      List(1, 2, 3, 4) must allSatisfy(beLessThan(5))
    }

    "Fail if any elements do not satisfy the expectation" in {
      List(1, 2, 3, 5) must notAllSatisfy(beLessThan(5))
    }
  }
}
Arjan Blokzijl
Thanks, that's just what I was looking for. I don't know why I wasn't seeing that.
Garrett Rowe
+1  A: 

Hi,

I thought that I already had this out of the box but that's not the case. I'm planning to add this to specs in the next days:

import org.specs._
import org.specs.matcher._
object SeqMatcher extends Specification {
  implicit def toSeqMatcher[T](m: Matcher[T]) = new ToSeqMatcher(m)
  class ToSeqMatcher[T](m: Matcher[T]) {
    def toSeq: Matcher[Seq[T]] = new Matcher[Seq[T]]() {
      type Res = (Boolean, String, String)
      def apply(v: =>Seq[T]) = ((true, "", "") /: v) { (res: Res, cur: T) =>
        def append(first: String, separator: String, second: String) = 
           first + (if (first.isEmpty) "" else separator) + second
        val currentRes = m(cur)
        if (currentRes._1) 
          (res._1 && currentRes._1, append(res._2, " and ", currentRes._2),  append(res._3, " and ", currentRes._2))
        else
          (res._1 && currentRes._1, append(res._2, " and ", currentRes._2),  append(res._2, " but ", currentRes._2))
      }
    }
  }
  List(1, 2, 6).toSeq must beLessThan(5).toSeq
}
SeqMatcher.reportSpecs

That will print out:

x example 1
    1 is less than 5 and 2 is less than 5 but 6 is less than 5 

Stay tuned!

Eric.

Eric
I added a toIterable method on Matcher[T] to be able to do what is expected here. Please have a go at the latest SNAPSHOTs in the Maven repository. Thanks.
Eric
Sweet. I'll try that out tonight. Thanks Eric.
Garrett Rowe