Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Created November 23, 2021 17:29
Show Gist options
  • Save james2doyle/d94698b3b74f0d00c193700eed1d6e9b to your computer and use it in GitHub Desktop.
Save james2doyle/d94698b3b74f0d00c193700eed1d6e9b to your computer and use it in GitHub Desktop.
Example usage of Laravels Spatie Snapshot testing package being used on a JsonResource output and a FormRequest rules array
<?php
namespace Tests\Snapshots;
use Illuminate\Http\Resources\Json\JsonResource;
use Spatie\Snapshots\MatchesSnapshots;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Models\User;
use App\Http\Resources\UserResource;
use App\Http\Requests\UserStoreRequest;
class UserHttpSnapshotTest extends TestCase
{
use RefreshDatabase, WithFaker, MatchesSnapshots;
protected function setUp(): void
{
parent::setUp();
// replace the faker with a predicable seed so the values stay the same
$this->app->bind(\Faker\Generator::class, function () {
$faker = \Faker\Factory::create();
$faker->seed(1);
return $faker;
});
}
/**
* @test
*/
public function it_can_create_snapshots_for_users_resource()
{
/** @var User */
$user = User::factory()->create([
'name' => 'Fake User',
'email' => 'someone@example.com',
]);
/** @var JsonResource */
$resource = new UserResource($user->load('profile', 'settings'));
$this->assertMatchesJsonSnapshot($resource->toJson());
}
/**
* @test
*/
public function it_can_check_the_output_of_the_user_request_rules()
{
/** @var array */
$rules = app()->call([new UserStoreRequest, 'rules']);
$this->assertMatchesJsonSnapshot(json_encode($rules));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment