hspec / hspec-wai

Helpers to test WAI applications with Hspec

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Analyse the response body (instead of expecting an exact value)

JivanRoquet opened this issue · comments

Is there a way to get the response body and perform tests on it?

Let's say I get a response body like this:

{
    "results": [42, 12, 66, 73, 59]
}

and all I care about is that there are 5 items in results and they are all Int. I don't care about each individual value.

I could not find any obvious way to achieve this by reading the code.

The only alternative I can think of at the moment is throwing hspec-wai altogether and locally run the API for real during the tests, then query the endpoints for real, get the response body, and analyse it. Any alternative using hspec-wai would be tremendously useful.

get returns an SResponse. As a fallback, you can just do with it whatever suits you, e.g. (untested):

r <- get "/foo"
let body = simpleBody r
case decode body of
  Right (Object o) | Just (Array xs) <- HM.lookup "results" o -> V.length xs `shouldBe` 5
  _ -> expectationFailure $ unexpected response <> show body

You may still be better of to define some data type for your expected response + a FromJSON instance for it and decode that. Working with Value is notoriously inconvenient.

Sounds good. Thanks for the guidance.