Laravel Model factories are one of the best features you can use in your application when it comes to testing. They provide a way to define data that is predictable and easy to replicate so that your tests are consistent and controlled.
Let's start with a simple example. We have an application used for blogging, so naturally, we have a Post
model that has a status for if the post is published, drafted, or queued. Let's look at the Eloquent Model for this example:
1declare(strict_types=1); 2 3namespace App\Models; 4 5use App\Publishing\Enums\PostStatus; 6use Illuminate\Database\Model; 7 8class Post extends Model 9{10 protected $fillable = [11 'title',12 'slug',13 'content',14 'status',15 'published_at',16 ];17 18 protected $casts = [19 'status' => PostStatus::class,20 'published_at' => 'datetime',21 ];22}
As you can see here, we have an Enum for the status column, which we will design now. Using an enum here allows us to take advantage of PHP 8.1 features instead of plain strings, boolean flags, or messy database enums.
1declare(strict_types=1); 2 3namespace App\Publishing\Enums; 4 5enum PostStatus: string 6{ 7 case PUBLISHED = 'published'; 8 case DRAFT = 'draft'; 9 case QUEUED = 'queued';10}
Now, let's get back to the topic we are here to discuss: model factories. A simple factory would look very simple:
1declare(strict_types=1); 2 3namespace Database\Factories; 4 5use App\Models\Post; 6use App\Publishing\Enums\PostStatus; 7use Illuminate\Database\Eloquent\Factories\Factory; 8use Illuminate\Support\Arr; 9use Illuminate\Support\Str;10 11class PostFactory extends Factory12{13 protected $model = Post::class;14 15 public function definition(): array16 {17 $title = $this->faker->sentence();18 $status = Arr::random(PostStatus::cases());19 20 return [21 'title' => $title,22 'slug' => Str::slug($title),23 'content' => $this->faker->paragraph(),24 'status' => $status->value,25 'published_at' => $status === PostStatus::PUBLISHED26 ? now()27 : null,28 ];29 }30}
So in our tests, we can now quickly call our post factory to create a post for us. Let's have a look at how we might do this:
1it('can update a post', function () { 2 $post = Post::factory()->create(); 3 4 putJson( 5 route('api.posts.update', $post->slug), 6 ['content' => 'test content', 7 )->assertSuccessful(); 8 9 expect(10 $post->refresh()11 )->content->toEqual('test content');12});
A simple enough test, but what happens if we have business rules that say you can only update specific columns depending on post type? Let's refactor our test to make sure we can do this:
1it('can update a post', function () { 2 $post = Post::factory()->create([ 3 'type' => PostStatus::DRAFT->value, 4 ]); 5 6 putJson( 7 route('api.posts.update', $post->slug), 8 ['content' => 'test content', 9 )->assertSuccessful();10 11 expect(12 $post->refresh()13 )->content->toEqual('test content');14});
Perfect, we can pass an argument into the create method to make sure that we are setting the correct type when we create it so that our business rules aren't going to complain. But that is a little cumbersome to keep having to write, so let's refactor our factory a little to add methods to modify the state:
1declare(strict_types=1); 2 3namespace Database\Factories; 4 5use App\Models\Post; 6use App\Publishing\Enums\PostStatus; 7use Illuminate\Database\Eloquent\Factories\Factory; 8use Illuminate\Support\Str; 9 10class PostFactory extends Factory11{12 protected $model = Post::class;13 14 public function definition(): array15 {16 $title = $this->faker->sentence();17 18 return [19 'title' => $title,20 'slug' => Str::slug($title),21 'content' => $this->faker->paragraph(),22 'status' => PostStatus::DRAFT->value,23 'published_at' => null,24 ];25 }26 27 public function published(): static28 {29 return $this->state(30 fn (array $attributes): array => [31 'status' => PostStatus::PUBLISHED->value,32 'published_at' => now(),33 ],34 );35 }36}
We set a default for our factory so that all newly created posts are drafts. Then we add a method for setting the state to be published, which will use the correct Enum value and set the published date - a lot more predictable and repeatable in a testing environment. Let's have a look at what our test would now look like:
1it('can update a post', function () { 2 $post = Post::factory()->create(); 3 4 putJson( 5 route('api.posts.update', $post->slug), 6 ['content' => 'test content', 7 )->assertSuccessful(); 8 9 expect(10 $post->refresh()11 )->content->toEqual('test content');12});
Back to being a simple test - so if we have multiple tests that want to create a draft post, they can use the factory. Now let us write a test for the published state and see if we get an error.
1it('returns an error when trying to update a published post', function () { 2 $post = Post::factory()->published()->create(); 3 4 putJson( 5 route('api.posts.update', $post->slug), 6 ['content' => 'test content', 7 )->assertStatus(Http::UNPROCESSABLE_ENTITY()); 8 9 expect(10 $post->refresh()11 )->content->toEqual($post->content);12});
This time we are testing that we are receiving a validation error status when we try to update a published post. This ensures that we protect our content and force a specific workflow in our application.
So what happens if we also want to ensure specific content in our factory? We can add another method to modify the state as we need to:
1declare(strict_types=1); 2 3namespace Database\Factories; 4 5use App\Models\Post; 6use App\Publishing\Enums\PostStatus; 7use Illuminate\Database\Eloquent\Factories\Factory; 8use Illuminate\Support\Str; 9 10class PostFactory extends Factory11{12 protected $model = Post::class;13 14 public function definition(): array15 {16 return [17 'title' => $title = $this->faker->sentence(),18 'slug' => Str::slug($title),19 'content' => $this->faker->paragraph(),20 'status' => PostStatus::DRAFT->value,21 'published_at' => null,22 ];23 }24 25 public function published(): static26 {27 return $this->state(28 fn (array $attributes): array => [29 'status' => PostStatus::PUBLISHED->value,30 'published_at' => now(),31 ],32 );33 }34 35 public function title(string $title): static36 {37 return $this->state(38 fn (array $attributes): array => [39 'title' => $title,40 'slug' => Str::slug($title),41 ],42 );43 }44}
So in our tests, we can create a new test that ensures that we can update a draft posts title through our API:
1it('can update a draft posts title', function () { 2 $post = Post::factory()->title('test')->create(); 3 4 putJson( 5 route('api.posts.update', $post->slug), 6 ['title' => 'new title', 7 )->assertSuccessful(); 8 9 expect(10 $post->refresh()11 )->title->toEqual('new title')->slug->toEqual('new-title');12});
So we can control things in our test environment using factory states nicely, giving us as much control as we need. Doing this will ensure that we are consistently preparing our tests or would be a good reflection of the applications state at specific points.
What do we do if we need to create many models for our tests? How can we do this? The easy answer would be to tell the factory:
1it('lists all posts', function () {2 Post::factory(12)->create();3 4 getJson(5 route('api.posts.index'),6 )->assertOk()->assertJson(fn (AssertableJson $json) =>7 $json->has(12)->etc(),8 );9});
So we are creating 12 new posts and ensuring that when we get the index route, we have 12 posts returning. Instead of passing the count into the factory method, you can also use the count method:
1Post::factory()->count(12)->create();
However, there are times in our application when we might want to run things in a specific order. Let's say we want the first one to be a draft, but the second is published?
1it('shows the correct status for the posts', function () { 2 Post::factory() 3 ->count(2) 4 ->state(new Sequence( 5 ['status' => PostStatus::DRAFT->value], 6 ['status' => PostStatus::PUBLISHED->value], 7 ))->create(); 8 9 getJson(10 route('api.posts.index'),11 )->assertOk()->assertJson(fn (AssertableJson $json) =>12 $json->where('id', 1)13 ->where('status' PostStatus::DRAFT->value)14 ->etc();15 )->assertJson(fn (AssertableJson $json) =>16 $json->where('id', 2)17 ->where('status' PostStatus::PUBLISHED->value)18 ->etc();19 );20});
How are you using model factories in your application? Have you found any cool ways to use them? Let us know on twitter!
0 comments:
Post a Comment
Thanks