meijdenmedia's avatar

Unit Test "deep" relational data

Dear community,

In Laravel it is very normal to get data from related objects like $customer->wallet->balance. What is the best approach in testing the value of the customers' current balance? Sometimes this even goes a layer deeper.

Thanks!

0 likes
3 replies
kylemilloy's avatar

There's no "best approach" but in my opinion you'd be better off writing two test classes, one for your Customer model and one for your Wallet model. Then in each you'd confirm that they can link to each other through a belongsTo or hasOne relationship.

Tray2's avatar

I usually do something like this

        $author = factory(Author::class)->create([
            'first_name' => 'Robert',
            'last_name' => 'Jordan'
        ]);

        $this->assertEquals('Jordan, Robert', $author->name);

So in your case I would create the customer add and the wallet belonging to the customer Something like this

$customer = factory(Customer::class)->create();
$wallet = factory(Wallet::class)->create(['customer_id' => $customer->id, 'balance' => 100]);

$this->assertEquals(100, $customer->wallet->balance);
1 like
meijdenmedia's avatar

@TRAY2 - Working like a charm, thanks! I want to mark this as the best answer but I got the 404 page when I hit the button :(

Please or to participate in this conversation.