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.

{ return [ 'title' => $title = $this->faker->sentence(), 'slug' => Str::slug($title), 'content' => $this->faker->paragraph(), 'status' => PostStatus::DRAFT->value, 'published_at' => null, ]; } public function published(): static
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners