lukeraymonddowning / poser

Create class based model factories in Laravel applications in seconds.
MIT License
277 stars 10 forks source link

Error when running factory with belongsTo relationship twice in a test #64

Closed minthemiddle closed 4 years ago

minthemiddle commented 4 years ago

I believe there is an error with Poser when I use a factory with belongsTo relationships twice in a test:

use Tests\Factories\StrikeFactory;
…

/** @test */
    public function member_can_see_only_current_round_on_strike_index()
    {
       // A round can have active = 1 or 0, default is 1
        $round_inactive = factory(Round::class)->create([
            'active' => 0,
        ]);
        $round_active = factory(Round::class)->create();
        $strike_inactive = StrikeFactory::new()
            ->forRound($round_inactive)
            ->create()
            ->first();
        $this->assertEquals($round_inactive->id, $strike_inactive->round_id);
        // this assertion passes

        $strike_active = StrikeFactory::new()
            ->forRound($round_active)
            ->create()
            ->first();
        $this->assertNotEquals($strike_inactive->round_id, $strike_active->round_id);
        // assertion fails: Failed asserting that '1' is not equal to '1'.
    }

With Strike.php model contains:

    public function round()
    {
        return $this->belongsTo(Round::class);
    }

It also fails when I create the active round in place:

$strike_active = StrikeFactory::new()
            ->forRound(RoundFactory::new())
            ->create()
            ->first();
lukeraymonddowning commented 4 years ago

Hullo!

I haven't tried to replicate this yet but is the issue to do with the first() call?

StrikeFactory::new()
            ->forRound($round_inactive)
            ->create()
            ->first(); // This bit here

You're only creating a single Strike model, but then call first as though it were a collection. I could be missing something, let me know if so.

lukeraymonddowning commented 4 years ago

Also, any chance you could post your migrations for the relevant database tables so that I can replicate them?

minthemiddle commented 4 years ago

Yes, the first() seems to be the problem. Had them as leftover from the old manual factory classes. Cut them and it seems to work. Let me confirm before you try to replicate.

minthemiddle commented 4 years ago

Can confirm that the ->first() was the culprit. Removed it and it works repeatly without hickups.