I've been building a Laravel based json api for fun and one major part of it is testing the results of the API. Once I know my results are good I want to use them to validate future tests. I had setup a couple local variables, copied and pasted my results and built the functions to remap the arrays for validation but this was a pain. So this gist will give you a trait to automatically save json responses and validate them from the file.
Follow me on on twitter or asked.io.
- Download SeeOrSaveJsonStructure.php to your tests folder.
- Add the trait to your tests/TestCase.php
class TestCase extends Illuminate\Foundation\Testing\TestCase
{
use SeeOrSaveJsonStructure;
...
- Edit your phpunit.xml file
- In the php tag add the new env variables.
- Define your RESPONSE_FOLDER
<php>
<env name="SAVE_RESPONSES" value="true"/>
<env name="RESPONSE_FOLDER" value="C:\jsonapi"/>
</php>
Call $this->seeOrSaveJsonStructure() after you've called $this->json().
public function testSort()
{
$this->json('GET', '/api/user?sort=-id');
$this->seeOrSaveJsonStructure();
}
When SAVE_RESPONSES is enabled the response from your json call will be saved to your RESPONSE_FOLDER in an easy to find .json file.
When SAVE_RESPONSES is disabled your json file will be used to validate the json structure with seeJsonStructure().