Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a top level array in json with specs2

Tags:

json

scala

specs2

In specs2 you can match an array for elements like this:

val json = """{"products":[{"name":"shirt","price":10, "ids":["1", "2", "3"]},{"name":"shoe","price":5}]}"""

def aProductWith(name: Matcher[JsonType],  price: Matcher[JsonType]): Matcher[String] =
  /("name").andHave(name) and /("price").andHave(price)

def haveProducts(products: Matcher[String]*): Matcher[String] =
  /("products").andHave(allOf(products:_*))

json must haveProducts(
  aProductWith(name = "shirt", price = 10) and /("ids").andHave(exactly("1", "2", "3")),
  aProductWith(name = "shoe", price = 5)
)

(Example taken from here: http://etorreborre.github.io/specs2/guide/SPECS2-3.0/org.specs2.guide.Matchers.html)

How do I do the same thing i.e. match the contents of products if products is a root element in the json? What should haveProducts look like?

val json = """[{"name":"shirt","price":10, "ids":["1", "2", "3"]},{"name":"shoe","price":5}]"""
like image 985
vrepsys Avatar asked Jan 28 '26 01:01

vrepsys


1 Answers

You can replace /("products").andHave(allOf(products:_*)) with have(allOf(products:_*)) like this:

val json = """[{"name":"shirt","price":10, "ids":["1", "2", "3"]},{"name":"shoe","price":5}]"""

def aProductWith(name: Matcher[JsonType],  price: Matcher[JsonType]): Matcher[String] =
  /("name").andHave(name) and /("price").andHave(price)

def haveProducts(products: Matcher[String]*): Matcher[String] = have(allOf(products:_*))

json must haveProducts(
  aProductWith(name = "shirt", price = 10) and /("ids").andHave(exactly("1", "2", "3")),
  aProductWith(name = "shoe", price = 5)
)
like image 145
Markus1189 Avatar answered Jan 30 '26 19:01

Markus1189



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!