CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

25 August, 2022

Using Laravel Model Factories in your tests

 Programing Coderfunda     August 25, 2022     Laravel, Laravel Tutorials, Packages     No comments   

Using Laravel Model Factories in your tests


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 Factory
12{
13 protected $model = Post::class;
14 
15 public function definition(): array
16 {
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::PUBLISHED
26 ? 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 Factory
11{
12 protected $model = Post::class;
13 
14 public function definition(): array
15 {
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(): static
28 {
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 Factory
11{
12 protected $model = Post::class;
13 
14 public function definition(): array
15 {
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(): static
26 {
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): static
36 {
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!

  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • User Notifications in Livewire with Megaphone Megaphone is a Livewire UI for Laravel-based user notifications. It uses built-in Laravel notification features to allow you to add bell ic… Read More
  • Dynamically Create and Destroy Servers with this Laravel Package Laravel Dynamic Servers is a package by Spatie that helps you start and stop servers when needed. The primary use case is creating ext… Read More
  • Require Signatures and Associate Them With Eloquent Models Laravel pad signature is a package to require a signature associated with an Eloquent model and optionally generate certified PDFs.Thi… Read More
  • Laravel Notification Event Subscriber Package Laravel Notification Event Subscriber is a simple package that registers an event subscriber to make it easy to run code while sending… Read More
  • Filament Markdown Editor Filament Markdown Editor is a markdown editor for the excellent Filament admin panel. You can quickly install this package and get mar… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Vue3 :style backgroundImage not working with require
    I'm trying to migrate a Vue 2 project to Vue 3. In Vue 2 I used v-bind style as follow: In Vue 3 this doesn't work... I tried a...
  • SQL ORDER BY Keyword
      The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts ...
  • Enabling authentication in swagger
    I created a asp.net core empty project running on .net6. I am coming across an issue when I am trying to enable authentication in swagger. S...
  • failed to load storage framework cache laravel excel
       User the export file and controller function  ..         libxml_use_internal_errors ( true ); ..Good To Go   public function view () : ...
  • Features CodeIgniter
    Features CodeIgniter There is a great demand for the CodeIgniter framework in PHP developers because of its features and multiple advan...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Clean Up Your Code with the whenHas Method - 6/5/2025
  • Laravel OpenRouter - 6/4/2025
  • Enable Flexible Pattern Matching with Laravel's Case-Insensitive Str::is Method - 5/31/2025
  • Cast Model Properties to a Uri Instance in 12.17 - 6/4/2025
  • Simplify Negative Relation Queries with Laravel's whereDoesntHaveRelation Methods - 5/31/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda