jgravois's avatar

Trying to test if a relationship exists

I am trying to test if the relationship on a model exists and is empty but the test fails with

Property [bands] does not exist on this collection instance.
/** @test */
    public function a_consignment_can_be_a_fixed_rate () {
        $this->withoutExceptionHandling();
        $con = Consignment::with('bands')->whereConsignmentCode('FIXED')->get();

        $this->assertTrue($con->bands->isEmpty());
    } // end test

I have tried without the $this->withoutExceptionHandling(); as well.

I have also tried $this->assertNull($con->bands).

0 likes
1 reply
Talinon's avatar

@jgravois withoutExceptionHandling() is going to have no affect on a unit test. You would use that on a feature test where you are making a request to the application and want to disable exception handling in order to see the underlying error instead of the exception.

Now that is cleared up. The first thing I notice is you're getting a collection, but treating it like a single model.

 Consignment::with('bands')->whereConsignmentCode('FIXED')->get();  // collection

So, when you access bands on $con, you are trying to access a property on the collection, and getting the error.

Changing get() to first() would retrieve a single model, and then your test should work.

Please or to participate in this conversation.