Tests

For testing, there is some helpful methods that can be found so handy.

Available methods

getJsonRequest

It's a shorthand for sending a json get request.

postJsonRequest

Shorthand for sending a json post request.

patchJsonRequest

It sends a json patch request.

deleteJsonRequest

Shorthand for sending a json delete request.

resourceToJson

This method converts you resource or resource collection instance to an array, then you can compare converted data with response from som route.

 1public function example(): void {
 2    $token   = $this->actingAsAdminUser();
 3    $model   = Post::find(1);
 4    $related = $model->comments();
 5
 6    $this->getJsonRequest(
 7        uri: "/api/blog/posts/{$model->id}/comments",
 8        token: $token
 9    )
10         ->assertOk()
11         ->assertExactJson(
12             $this->resourceToJson(
13                 Comment::getResourceCollection( $related->paginate() )
14             )
15         );
16}

Factory contract

This contract helps to create fake data for your test suite. the implementation class should be like this.

 1use Hans\Valravn\Repositories\Contracts\Repository;
 2use Hans\Valravn\Testing\Contracts\Factory;
 3use Illuminate\Database\Eloquent\Factories\Factory as EloquentFactory;
 4
 5class PostFactory extends Factory {
 6
 7    protected static function getFactory(): EloquentFactory {
 8        return PostFactory::new(); // or Post::factory();
 9    }
10
11    public static function getRepository(): Repository {
12        return app( IPostRepository::class )->disableAuthorization();
13    }
14    
15}
To prevent authorization errors, it's recommended to call disableAuthorization() on your repository instance.

You can make your own methods for generating fake data for your relationships.

Available methods

preCreateHook

PreCreate hook executes before running factory. so, if your factory requited data from other entities, you can create your needed data in preCreateHook method. for instance, we might have a belongsTo relationship and before creating our data, we need a model from related entity.

create

Create an instance and stores it into the database.

make

Create an instance but doesn't store it on database.

createMany

Create many fake data at once and return the created data as a collection.

getModel

It returns created model by factory class.