0

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.

Alchalade
  • 307
  • 1
  • 5
  • 14
  • you could let the code work as needed by creating a model and letting the observer fire off the jobs ... you can fake the queue so it won't actually dispatch but you will be able to assert that things were queued – lagbox Jun 21 '20 at 15:28
  • I see, that means I have to test the job in a different test file to be sure that it does the thing I expect from it. Am I right ? – Alchalade Jun 21 '20 at 15:29
  • kinda depends what you are doing and how this is setup but you do have the facilities to be able to test a lot of things by faking a lot of services, obviously how you have also designed your code also comes into play with how easy it will be or not to test in isolation – lagbox Jun 21 '20 at 15:32
  • Thank you a lot. It is working now with two separated test files and a faked queue :) – Alchalade Jun 21 '20 at 16:03

1 Answers1

1

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();
    }
}

Bedram Tamang
  • 3,748
  • 31
  • 27