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
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Write API Integrations in Laravel and PHP Projects with Saloon
    Write API Integrations in Laravel and PHP Projects with Saloon Saloon  is a Laravel/PHP package that allows you to write your API integratio...
  • Credit card validation in laravel
      Validation rules for credit card using laravel-validation-rules/credit-card package in laravel Install package laravel-validation-rules/cr...
  • iOS 17 Force Screen Rotation not working on iPAD only
    I have followed all the links on Google and StackOverFlow, unfortunately, I could not find any reliable solution Specifically for iPad devic...
  • C++ in Hindi Introduction
    C ++ का परिचय C ++ एक ऑब्जेक्ट ओरिएंटेड प्रोग्रामिंग लैंग्वेज है। C ++ को Bjarne Stroustrup द्वारा विकसित किया गया था। C ++ में आने से पह...
  • Python AttributeError: 'str' has no attribute glob
    I am trying to look for a folder in a directory but I am getting the error.AttributeError: 'str' has no attribute glob Here's ...

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

  • July (2)
  • 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)

Loading...

Laravel News

Loading...

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