Support the ongoing development of Laravel.io →
Database Eloquent Testing
Last updated 2 years ago.
0

I think that you can make a partial (or normal) mock of your model and mock items() method to return whatver you want.

Last updated 2 years ago.
0

I personally use phpspec/phpspec and a nifty little package from @benconstable called benconstable/phpspec-laravel. Jeffery Way has at least a couple of free videos on getting started with PHPSpec if you need: PHPSpec Is So Good and Laravel, PHPSpec, Refactoring

Ben's package has a great readme to show how to test relationships, but it essentially becomes as easy as:

function it_should_have_users()
{
    $this->users()->shouldDefineRelationship(
        'hasMany', 'Acme\User'
    );
}

Hope this helps you out!

Last updated 2 years ago.
0

Thank you for replies! jlaswell, The problem is not in testing relationships, but in mocking them.

radmen suggested mocking items() method of Category model, but you can do that when you are using injected model via Controller's constructor, like this:

    public function __construct(Category $category)
    {
        $this->category = $category; // injecting category
    }


//and then in controller action:
$category = $this->category->findOrFail($categoryId); //this we can mock
$items = $category->items()->get(); // this we cannot mock as category it is not injected 

Here we are telling Laravel to use mocked model:

$this->app->instance('Category', $categoryMock);

So I can't see a way to mock the category object, not injected model...

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

dor-denis dor-denis Joined 9 Jul 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.