CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

Unit Testing with CakeDC DB Test

The only way to go fast, is to go well, my Uncle Bob always said. Research has shown that development with TDD evolves 10% faster than work without TDD. [See here]

CakePHP comes with comprehensive testing support built-in with integration for PHPUnit. It also offers some additional features to make testing easier.

This article will cover how to write Unit Tests with CakePHP and using the CakeDC DbTest plugin.


First, let's bake a new project:

composer create-project --prefer-dist cakephp/app:4.*

Now, we need to think  about a model so we can create it and test it. I guess everybody has written a Products model before, our model would looks like this:

  • Name (string)

  • Slug (string, unique)

  • Description (text)

  • Price (decimal)

If you are not familiar with Slug, Slug is the part of a URL that identifies a page in a human-readable way, usually for pages with friendly urls. It will be the target of our tests.

bin/cake bake migration CreateProducts name:string slug:string:unique price:decimal[5,2] description:text created modified

Pay attention, for slug, It was created with a unique index. Meanwhile our goal will be to have urls like: /slug-of-product and this way, the slug needs to be unique.


Let's run the migrations for database:

bin/cake migrations migrate

At this point, our database is ready with the `products` table and we can start coding and writing the tests.

* Note: some points were abstracted, such as installation, project configuration, and shell commands, because that's not the goal of the article. You can find all information on these in the cookbook.


Let's bake the models, controller, and templates for Product:

bin/cake bake all Products


Now that we have all the Classes we can start writing the unit tests. Let's start with ProductsController, writing one test for add Product:

tests/TestCase/Controller/ProductsControllerTest.php

public function testAdd(): void

    {

        $this->enableCsrfToken();

        $this->enableRetainFlashMessages();

        $this->post('products/add', [

            'name' => 'iPhone 11',

            'slug' => 'iphone-11',

            'price' => 699,

            'description' => 'Lorem ipsum dolor sit amet, aliquet feugiat.',

        ]);

        $this->assertResponseSuccess();

        $this->assertFlashMessage(__('The product has been saved.'));

        $this->assertRedirect('products');

    }

Let's write another test that tries to add a duplicated product. First, we need to update the fixture, then write the test:

tests/Fixture/ProductsFixture.php

    public function init(): void

    {

        $this->records = [

            [

                'id' => 1,

                'name' => 'iPhone SE',

                'slug' => 'iphone-se',

                'price' => 399,

                'description' => 'Lorem ipsum dolor sit amet, aliquet feugiat.',

                'created' => '2020-04-23 13:12:58',

                'modified' => '2020-04-23 13:12:58',

            ],

        ];

        parent::init();

    }

tests/TestCase/Controller/ProductsControllerTest.php

public function testAddDuplicated(): void

    {

        $this->enableCsrfToken();

        $this->enableRetainFlashMessages();

        $this->post('products/add', [

            'name' => 'iPhone SE',

            'slug' => 'iphone-se',

            'price' => 399,

            'description' => 'Lorem ipsum dolor sit amet, aliquet feugiat.',

        ]);

        $this->assertResponseSuccess();

        $this->assertFlashMessage(__('The product could not be saved. Please, try again.'));

        $this->assertNoRedirect();

    }

 

With these tests, we know the work is complete when the acceptance criteria (the slug of product must be unique) of the tests is passed.
That's all? No, this article it's not only about tests, this article is about the CakeDC DbTest plugin and how it can be advantageous.

CakeDC DB Test

Maintaining fixtures on real applications can be hard, a big headache. Imagine writing +1k products on ProductFixture, and adding a relationship like Product belongs to Category, then having to write new fixtures and keep them in sync.

Real applications usually have features like authentication with ACL, where each User has one Role, and each Role can access many features. Administrator has full rights, Manager has many rights, and so on.
Keeping all of this information in our fixtures is painful. Most of the frameworks have plugins to help with that issue. Thanks to the CakeDC team, we can easily let the DbTest to do the "dirty" work for us:

Let's install and load the plugin:

composer require cakedc/cakephp-db-test:dev-2.next

bin/cake plugin load CakeDC/DbTest


Then configure the plugin on project:

  1. Copy/replace the phpunit.xml: https://github.com/CakeDC/cakephp-db-test/blob/2.next/phpunit.xml.dbtest

  2. Configure test_template datasource on config/app.php:

'Datasources' => [

    // ...

    'test_template' => [

        'className' => Connection::class,

        'driver' => Mysql::class,

        'persistent' => false,

        'timezone' => 'UTC',

        //'encoding' => 'utf8mb4',

        'flags' => [],

        'cacheMetadata' => true,

        'quoteIdentifiers' => false,

        'log' => false,

        //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],

    ],

    // ...


Now, we can delete our fixture and generate the dump of our database for using on tests:

// migrate the database for template

bin/cake migrations migrate -c test_template

// import fixtures

bin/cake fixture_import dump

// generate dump

/bin/cake db_test -i

 

Finally, we can see some advantages of CakeDC DbTest:

  • Speed.

  • Maintain fixtures with your regular database tool.

  • Run migrations to your dbtest db too.

  • Copy data from your live db to reproduce bugs.
     

That's all, bakers. Now we have test_db.sql, and you can see how our fixtures will come from this data.

You can check the code source of this article on this repository: https://github.com/rafaelqueiroz/cakephp-db-test-sample

 

 

Latest articles

Playing with the new CakePHP Queue

One of the topics discussed in the community is the benefit of a unified, officially supported, CakePHP Queue plugin. Queues are used in most of the projects nowadays and are a central utility plugin. During the CakeFest 2020 event, there were also a couple direct references from speakers: (https://speakerdeck.com/josegonzalez/building-and-releasing-a-cakephp-plugin/?slide=15c) and this comment from Mark Story: https://cakesf.slack.com/archives/C172CS4TE/p1602257791377500.   This motivated me to take a deeper look at the cakephp/queue plugin and write this blog post.   Here at CakeDC we've been using queues for a looooong time. Initially in CakePHP 2, we've used plugins like CakeResque with redis or custom workers tied to Amazon SQS queues. Then in CakePHP 3 & 4 we've been using mostly https://github.com/josegonzalez/cakephp-queuesadilla with redis or mongodb backends. https://github.com/cakephp/queue   First thing would be setting up the plugin in your project, we are going to use the example project we used in CakeFest 2020: https://github.com/cakephp/cakefest2020/#using-docker   So after setting up the project and running it via docker compose, we can proceed to setup the plugin via composer. We will need to add it as a repository and set  

Install via composer

  After the first release it'll be much easier, but for now you'll need to add the package to your composer.json   "repositories": [         {             "type": "vcs",             "url": "https://github.com/cakephp/queue.git"         }     ]   Then do composer require cakephp/queue -W   And install some transport as stated in the official documentation https://book.cakephp.org/queue/1/en/index.html#installation composer require enqueue/redis:^0.9 composer require predis/predis:^1   Ensure your redis server is up and running, you can check the commands sent to your local redis server using redis-cli monitor   Now we are ready to configure the queue, we'll create 1 default queue adding this to the config/app.php file       'Queue' => [         'default' => [             'url' => 'redis:',         ],     ],   Add a Job using `bin/cake bake job Example` and add some code to the execute method       public function execute(Message $message): string     {         $data = $message->getArgument('data');           // do some long operation with data         Debugger::log($data);         sleep(2);           return Processor::ACK;     }   I've added a command utility to enqueue a test message bin/cake bake command addJob       public function execute(Arguments $args, ConsoleIo $io)     {         $callable = [ExampleJob::class, 'execute'];         $arguments = ['id' => 1, 'data' => ['some' => 'data']];           QueueManager::push($callable, $arguments);     }   And finally we can start our worker using bin/cake worker to pull jobs from Redis and process them using the ExampleJob::execute method   Here's all the example code created: https://github.com/cakephp/cakefest2020/tree/feature/cakephp-queue - for your reference.   Please note the plugin is still a work in progress and there is no stable release as of now.  It's looking great so far and we plan to include it in our next projects!  

Best CakePHP Plugins

Members of our team had the privilege of helping with CakeFest 2020 this year. One added virtual feature was the giveaways from CakePHP, these were done in the form of fastest-to-answer, trivia, or participation (random draw).  One of the giveaway games was to share your favorite CakePHP plugin but like, how do we only pick one, right? Anyway… There was a lot of participation in this giveaway! A few people even named our CakeDC Users plugin as their favorite *cue blushing face*. But in all seriousness, I thought it would be a good idea to share with you some of the plugins that were named most useful/helpful by CakeFest attendees this year….   Like I mentioned, the CakeDC users Plugin: https://github.com/CakeDC/users Queue Plugin: https://github.com/dereuromark/cakephp-queue Bake: https://github.com/cakephp/bake DataTables: https://github.com/fheider/cakephp-datatables CakePHP-tools: https://github.com/dereuromark/cakephp-tools Authentication: https://github.com/cakephp/authentication CakePHP-image: https://github.com/josbeir/cakephp-image Fixturize: https://github.com/lorenzo/cakephp-fixturize CakePHP File-Storage: https://github.com/burzum/cakephp-file-storage Crud: https://github.com/FriendsOfCake/crud IDE Helper: https://github.com/dereuromark/cakephp-ide-helper Asset-Compress: https://github.com/markstory/asset_compress CakePHP Debug Kit: https://github.com/cakephp/debug_kit Plum-Search: https://github.com/skie/plum_search CakePHP API: https://github.com/cakedc/cakephp-api/ Bootstrap UI: https://github.com/friendsofcake/bootstrap-ui Trash: https://github.com/usemuffin/trash   You can check out the full list of CakePHP Plugins at Plugins.CakePHP.org.  Have you been utilizing these tools? If not, it may be a good idea to start… while each of these serve their own purpose, using all of them can make your baking process a lot easier.    Perhaps your favorite didn’t make this list? Tell us about it… email HERE. Or, tweet us @CakeDC, @CakePHPThanks for baking!  

CakeFest 2020 recap

Taking a deep breath….. We have made it through another successful CakeFest event.    We didn’t know exactly what to expect with a fully virtual event, as it opens the door for a list of things that can (and most likely will) go wrong. Would the speakers show up? Would the internet connections keep things from running smoothly? Would attendees enjoy the information?   The answer to all of those questions is yes.    The lineup this year was amazing, and we had speakers from 6 different countries! With the ever changing way of life, our team wanted to have a diverse group of speakers, with some talking about some pretty serious subjects - like Dr. Jennifer Akullian and the mental health issues faced in the tech world. Jen allowed for questions and how-to-handle scenarios, and worked through some tough issues with attendees. Workshops from Mark Story, Jorge Gonzalez, Mark Scherer and Jose Lorenzo provided incomparable information while building projects in real time. All of the talks provided useful information that we hope all attendees will take with them as they bake in the future.    Now, does all of this bragging mean we didn’t have any issues? No. As I said in our opening, I think our group is pretty awesome and perfect, but the fact of the matter is, no one is. When bringing people together from all over the world, it is hard to test and check every connection multiple times. We had our fair share of internet lag, connection problems and audio issues. You know what we did? We worked together, fixed it, switched around the schedule and made it happen.   Virtual CakeFest 2020 was a great success, and exceeded our expectations. We were able to gather bakers from all over the world, in real time, and host a live event! I couldn’t believe how interactive the audience was, and everyone is still baking together in our #cakefest chat channel. I hope everyone is as impressed with the turn out as our team is. I know what you’re thinking… when will the recordings be released. We are working on uploading, editing and releasing the videos ASAP. While we tried to find the best universal timezone, we understand that other obligations kept some from attending, and we want to share these videos with you quickly, so know that we are working on it.    To our attendees: THANK YOU. Thank you for joining, supporting our framework and keeping CakePHP alive.   

I would like to thank all of our speakers:

  Remy Bertot  Junichi Okuyama Mark Story Jorge Gonzalez Jose Lorenzo Mark Scherer Jose Gonzalez Cal Evans Ed Barnard Jennifer Akullian Mariano Iglesias Chris Nizzardini Juan Pablo Ramirez
 

A HUGE THANK YOU TO OUR SPONSORS:

   Cake Development Corporation
  Passbolt 
  Marks Software
  RingCentral  


  Here’s to planning next year’s event to be even bigger and better!  

We Bake with CakePHP