Laravel Model factories are one of the best features you can use in your application when it comes to testing. Let’s look at the Eloquent Model for this example: declare(strict_types=1); namespace App\Models; use App\Publishing\Enums\PostStatus; use Illuminate\Database\Model; class Post extends Model { protected $fillable = [ 'title', 'slug', 'content', 'status', 'published_at', ]; protected $casts = [ 'status' => PostStatus::class, 'published_at' => 'datetime', ]; }
Let’s have a look at what our test would now look like: it('can update a post', function () { $post = Post::factory()->create(); putJson( route('api.posts.update', $post->slug), ['content' => 'test content', )->assertSuccessful(); expect( $post->refresh() )->content->toEqual('test content'); }); Back to being a simple test - so if we have multiple tests that want to create a draft post, they can use the factory.
it('returns an error when trying to update a published post', function () { $post = Post::factory()->published()->create(); putJson( route('api.posts.update', $post->slug), ['content' => 'test content', expect( $post->refresh() )->content->toEqual($post->content); }); This time we are testing that we are receiving a validation error status when we try to update a published post.