Alchalade
Alchalade

Reputation: 307

Testing Model with Observer in Laravel 7

I'm trying to test a controller which creates a model.

There is an observer that listens the created event on the model. The observer is responsible to dispatch jobs to create sub-models(table entries) that depend on the base model/table.

I know that I'm sure it will work is the worst thing to say while testing. To be able to test the functionality of the whole process I add something like ;

if (env('APP_ENV') === 'testing') {
    TariffPricingComponentsCalculater::dispatchNow($tariff, $components);
}

I have the feeling that this piece of code should not be in the prod version. Is there a cleaner way to dispatch the job immediately while testing

Thank you.

Upvotes: 0

Views: 1521

Answers (1)

Bedram Tamang
Bedram Tamang

Reputation: 4365

The better approach to disable observers while testing would be calling Model::unsetEventDispatcher() in setup method.

For example: Here I have Plan model which has an observer called PlanObserver and I can disable them in setup method of test class by:

class PlanTest extends TestCase
{
    use RefreshDatabase;

    public function setUp():void
    {
        parent::setUp();
        
        Plan::unsetEventDispatcher();
    }
}

Upvotes: 1

Related Questions