Faking the Queue in Laravel tests

Published under Laravel.

I'm working on a project where we use observers to dispatch a chain of jobs whenever a Volume model is created. While this is great when working on the code base, it can make it a bit difficult to write tests. For example, I want to test one of the jobs in the chain that is dispatched. Specifically, I want to make sure that the job fails when it should, and with the correct message.

So here's what I need the test to do:

  • Fake the JobFailed event so we can assert it was dispatched correctly

  • Create our model, but while the queue is faked, so the chain of jobs dispatched by the observer will not run

  • Dispatch the job we want to test

  • Assert the JobFailed event was fired

Here's what the test looked like originally:

I didn't like the idea of having to store the $queue facade root and then having to replace it after. So I wrapped that up into a package:

Now anytime we need to fake the queue for just a couple of lines, I can use QueueFake::wrap(). The queue will be faked for the duration of the closure.

Check it out on GitHub: https://github.com/ohseesoftware/laravel-queue-fake


Thanks for reading!

Did you find this post useful? Let me know on Twitter! If you found an issue with the content, submit a pull request!

Subscribe to my newsletter to know when I publish more content in the future.

❤️ Likes: 0
📣 Retweets: 0
💬 Replies: 0
🙊 Mentions: 0