Date Archives dicembre 2015

Go Experiments – #1 – Rsz

I recently started to play with the Go language. I felt the need to change languages, paradigms and to study something new.

Meanwhile, my girlfriend needed a tool to quickly resize her images, for some university projects. What best occasion to study something new? I read many articles about Go, that suggest to use the language for some specific applications, like CLI tools or microservices. Exactly what I needed.

So… here’sĀ Rsz!

I love command line interface tools. I started using them more seriously some months ago, when I began using Linux everyday. I love how much they can cut times for repetitive tasks.

I have not compiled it yet, so if you want to use it you will need to have Go installed on your machine. However, in the next days/weeks I will add some new features and the compiled executables for both Linux and Windows platforms.

Have a nice day, and happy holidays! šŸ™‚

A Quickie – Dealing with Observers and Testing in Laravel 5.1

If you use Laravel 5.1, you probably heard about model observers. Basically, they just observe a certain model and when a certain action is done (or it is going to be done) it executes a separate logic. It is really a great way to deal with model events, instead of declaring things right in the EventServiceProvider.

Said that, this morning I had some issues while dealing with observers during testing with PHPUnit.

The Laravel documentation says that you can disable event triggering with something like:

<?php

class ExampleTest extends TestCase
{
    public function testUserRegistration()
    {
        $this->withoutEvents();

        // Test user registration code...
    }
}

(source:Ā http://laravel.com/docs/5.1/testing#mocking-events)

Here’s the bad news: it does not work with observers. Even if you type theĀ $this->withoutEvents();Ā the observer is loaded and called. Bye bye, isolated testing!

Now, it seems that no one on internet had a similar issue. That’s quite strange because I like observers and I think they are useful, and more elegant than the classic model events declaration.

This is how I solved my problem.

public function testCanSave()
{
    $this->app->bind(MediaUploaderObserver::class, function(){
        return $this->getMockBuilder(MediaUploaderObserver::class)->disableOriginalConstructor()->getMock();
    });

    // test logic goes here...
}

By using the $this->app->bindĀ method to create a new binding in the service container, I managed to solve the problem. The closure passed as the second argument returns a mock of the originalĀ MediaUploaderObserverĀ class.

Screenshot from 2015-12-08 14:02:34

And that’s all, folks!