PatrickSJ's avatar

How to have JSON_NUMERIC_CHECK applied on test response?

If I take an object and assert a JSON response has it using $response->assertJsonFragment($new_labor->toArray()); then it fails with float/decimal numbers because 16.5 is not "16.50".

I can get around this manually simply by decoding the response and looping through the keys, but is there a built-in way to handle this that I've missed? Maybe something I can set on the response or the model? I've tried browsing the API, but I've missed it if it is there.

$labor = factory(WorkorderLabor::class)->raw();

$response = $this->store($this->workorder, $labor);

$new_labor = WorkorderLabor::latest('id')->first();

$response->assertJsonFragment($new_labor->toArray());
Unable to find JSON fragment: 

[{"billable_hours":"16.50"}]

within

[{"billable_hours":16.5,"created_at":"2019-02-17 15:30:07","date_of_service":"2016-01-23","description":"Sint quis debitis omnis aut.","id":11,"num_of_techs":7,"updated_at":"2019-02-17 15:30:07","workorder_id":9}].

Edit: In order to solve I had to use the following, but having to do this for any model that contains decimal / float attributes and involves a JSON response is a bit convoluted.

$this->assertArraySubset(
    json_decode($new_labor->toJson(JSON_NUMERIC_CHECK), true),
    json_decode($response->content(), true)
);
0 likes
1 reply
PatrickSJ's avatar
PatrickSJ
OP
Best Answer
Level 12

So, huh. Issue is solved by setting the $casts attribute on the model. That ensured consistency.

Please or to participate in this conversation.