Testing Your Multi-database Multi-tenant Laravel Application

https://media.licdn.com/dms/image/D4D12AQF1GggB9-6qzg/article-cover_image-shrink_720_1280/0/1695238380041?e=2147483647&v=beta&t=8W5yL5H_xSLyU2j2LlLeUK50wJ_feX1ITiPs7aPStQE

For some months now I have been working on a multi-tenant loan management system which uses the Tenancy For Laravel package. Find it here on Github. Following their documentation, everything works perfectly so far. The only issues I have had is setting up my feature tests. The documentation on the testing doesn’t seem to work very well and it made me want to pull out my hair. After hours of trying, I finally came up with a simple solution to set up my tests.

First of, let’s talk about what was not working. From the docs here, the only thing to do is to initialize tenancy in the test setUp method and everything should work fine. This failed and I had to find another way.

Here is what I did:


Quick explanation of what is going on here. The setUp method is initializing tenancy so that everything works as if the application is being accessed through a tenant subdomain. I had to call withoutMiddleware because, those middlewares were causing the requests to fail.

Note: they were being used in my routes/web.php file.

tearDown was for cleaning things up.

All my test classes extended this as the base test class like so:


And that’s it, my tests were finally running. Hope this helps someone. If you found this useful, let me know in the comments. If you have implemented this in a different way as well, let me know in the comments.

Laravel News Links