Scala specs2 - how to match a list of matches or criteria?
Pain:
val someString = "how are you today?"
val expectedWordsInStringList = List("how", "you")
How can I match that the string contains all the expected words?
//would of liked to have: (there is no method containAllElements)
someString must containAllElements(expectedWordsInStringList)
Finished writing this test (and not happy with the result)
class HowToMatchListOfMatcher extends Specification {
"HowToMatchListOfMatcher" should {
"not use reduce to match on list of matchers" in {
val testString = "some string with 1 and 2"
val containList:List[String] = List("1", "2")
val matcherList:List[Matcher[String]] = List(contain("1"), contain("2"))
def matchAll(matcherList: List[Matcher[String]]) = matcherList.reduce((m1,m2)=> m1 and m2)
//how can i match this without reduce ? or with using the containList
testString must matchAll(matcherList)
}
}
}
+3
source to share
2 answers
You can define a custom string connector. What about
import org.specs2.mutable._
import org.specs2.matcher.{Expectable, Matcher}
class HowToMatchListOfMatcher extends Specification {
import CustomMatchers._
"HowToMatchListOfMatcher" should {
"not use reduce to match on list of matchers" in {
val testString = "some string with 1 and 2"
testString must containAllSubstringsIn(List("1", "2", "bar"))
}
}
}
object CustomMatchers {
def containAllSubstringsIn(expectedSubstrings: Seq[String]) = new Matcher[String] {
def apply[S <: String](expectable: Expectable[S]) = {
result(expectedSubstrings.forall(expectable.value.contains(_)),
expectable.description + " contains all substrings in " + expectedSubstrings,
expectable.description + " doesn't contain all substrings in " + expectedSubstrings + "\nMissing substrings: " + expectedSubstrings.filterNot(expectable.value.contains(_)), expectable)
}
}
}
+1
source to share