Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Model events from firing using phpunit?

I want to prevent Model events such as 'created'. 'updated' etc when testing my application using phpunit.

In the documentation of Laravel it says that you can prevent events from firing by using

$this->expectsEvents(App\Events\UserRegistered::class);

But in my situation I have no class to expect.

Even if I use $this->withoutEvents(); to prevent all events, eloquent events are fired.

How can I prevent eloquent events?

like image 953
Alex Kyriakidis Avatar asked Sep 26 '15 15:09

Alex Kyriakidis


2 Answers

If you really just want to disable the model's observer, such as creating, created, updated, etc. then you can call the model's façade method unsetEventDispatcher.

For example, you can place it in the test class's setUp method. And you don't have to reset it in tearDown because the framework automatically does this in setUp for the next test.

protected function setUp(): void
{
    parent::setUp();
    App\MyModel::unsetEventDispatcher();
}

If you want this to be temporary, then look into withoutEventDispatcher.

Also you could getEventDispatcher and save that to a temporary variable then setEventDispatcher again after you've completed your business as is demonstrated in this answer: https://stackoverflow.com/a/51301753/4233593

like image 196
Jeff Puckett Avatar answered Sep 30 '22 09:09

Jeff Puckett


Method 1:

You can prevent model events from firing by mocking the Observer. Here's how:

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

        factory(MyModel::class)->states('pending')->create([
                'user_id' => 1,
                'publisher_revenue' => 10,
        ]);

 // Your test logic goes here
}

Method 2:

You can call the following in your setUp() method:

 MyModel::unsetEventDispatcher();

Both Tested and working in Laravel 5.6.

like image 44
Hyder B. Avatar answered Sep 30 '22 09:09

Hyder B.