behrooznik's avatar

what is the problem of this test?

after running the following test i got this Error:

Failed asserting that actual size 0 matches expected size 1.

this is my test:

public function a_user_can_toggle_following() { $john=$this->SignIn(); $this->assertCount(0, $john->follows );

    $sally=factory(User::class)->create();
    $nick=factory(User::class)->create();

    $john->follow($sally);
    $this->assertCount(1, $john->follows );

    $john->follow($nick);
    $this->assertCount(2, $john->follows );

    $john->unfollow($nick);
    $this->assertCount(1, $john->follows );

}

And these are the related methods that I used in the test:

public function follow(User $user) { return $this->follows()->save($user); }

public function unfollow(User $user)
{
    return $this->follows()->detach($user);
}


public function follows()
{
    return $this->belongsToMany(User::class, 'follows', 'user_id', 'following_user_id');
}

whats the problem??

0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

Whenever you first get $john->follows, that result is cached on $john, so you need to get fresh instance after taking the action:

public function a_user_can_toggle_following() {
	$john=$this->SignIn();
	$this->assertCount(0, $john->follows );

	$sally=factory(User::class)->create();
	$nick=factory(User::class)->create();

	$john->follow($sally);
	$this->assertCount(1, $john->fresh()->follows ); // fresh instance

	$john->follow($nick);
	$this->assertCount(2, $john->fresh()->follows ); // fresh instance

	$john->unfollow($nick);
	$this->assertCount(1, $john->fresh()->follows ); // fresh instance
}

You could use the query builder either:

public function a_user_can_toggle_following() {
	$john=$this->SignIn();
	$this->assertEquals(0, $john->follows()->count() );

	$sally=factory(User::class)->create();
	$nick=factory(User::class)->create();

	$john->follow($sally);
	$this->assertEquals(1, $john->follows()->count() ); // fresh query

	$john->follow($nick);
	$this->assertEquals(2, $john->follows()->count() ); // fresh query

	$john->unfollow($nick);
	$this->assertEquals(1, $john->follows()->count() ); // fresh query
}
1 like

Please or to participate in this conversation.