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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With