Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Adam Wathan:
Stubbing Eloquent Relations for Faster Tests
Aug 08, 2016 @ 16:52:53

Adam Wathan has a recent post to his site showing you how to stub out your Eloquent relations in a Laravel application for use in your testing (rather than hitting the database directly).

When you’re trying to test methods on an Eloquent model, you often need to hit the database to really test your code.

But sometimes the functionality you’re testing doesn’t really depend on database features. Is there any way to test that stuff without hitting the database?

He starts with a look at the more traditional method, using the models normally and testing with the database. He includes a simple test and class showing a basic "song duration" integer response. He gets into a bit more detail on how the Eloquent code grabs the data it needs when a relation is accessed (hint: not a separate query) and how to update the test to mimic the eager loading of the duration information. He ends the post by pointing out that "nothing is free" however as, if the underlying database implementation changes, the test would start to fail regardless of it not using the database.

tagged: tutorial screencast example relation eloquent unittest stub

Link: https://adamwathan.me/2016/08/04/stubbing-eloquent-relations-for-faster-tests/


Trending Topics: