2015-05-28 1 views
3

Боль:scala specs2 - как совместить список шаблонов или критериев?

val someString = "how are you today?" 
val expectedWordsInStringList = List("how", "you") 

Как я могу соответствовать, что строка содержит все ожидаемые слова?

//would of liked to have: (there is no method containAllElements) 
    someString must containAllElements(expectedWordsInStringList) 

Законченное писать этот тест (и не доволен результатом)

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) 

    } 
    } 
} 

ответ

1

Вы можете определить пользовательские строки Искателя. Как насчет

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) 
    } 
    } 
} 
+0

я бы ожидал specs2 есть из коробки согласовани для списка элементов – Nimrod007

+0

@ Nimrod007 Существует 'containAllOf [T ] (seq: Seq [T]) 'в признаке' org.specs2.matcher.TraversableBaseMatchers'. Однако я не уверен, что это полезно, поскольку существуют явные 'StringBaseMatchers' (такие как метод' contains', который вы используете), и я не могу найти что-то вроде 'containsAllOf'. –

1

Вы можете разделить строку на пробелы, то используйте contain(allOf(...))

val someString = "how are you today?".split(" ").toSeq 
someString must contain(allOf("how", "you")) 

 Смежные вопросы

  • Нет связанных вопросов^_^