Skip to content

Commit

Permalink
Add tests for attaching existing model instances in factories (#35581)
Browse files Browse the repository at this point in the history
  • Loading branch information
bakerkretzmar committed Dec 11, 2020
1 parent 64e28ba commit 3531b36
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions tests/Database/DatabaseEloquentFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,21 @@ public function test_belongs_to_relationship_with_existing_model_instance()
$this->assertCount(3, FactoryTestPost::all());
}

public function test_belongs_to_relationship_with_existing_model_instance_with_relationship_name_implied_from_model()
{
$user = FactoryTestUserFactory::new(['name' => 'Taylor Otwell'])->create();
$posts = FactoryTestPostFactory::times(3)
->for($user)
->create();

$this->assertCount(3, $posts->filter(function ($post) use ($user) {
return $post->factoryTestUser->is($user);
}));

$this->assertCount(1, FactoryTestUser::all());
$this->assertCount(3, FactoryTestPost::all());
}

public function test_morph_to_relationship()
{
$posts = FactoryTestCommentFactory::times(3)
Expand Down Expand Up @@ -342,6 +357,29 @@ public function test_belongs_to_many_relationship_with_existing_model_instances(
unset($_SERVER['__test.role.creating-role']);
}

public function test_belongs_to_many_relationship_with_existing_model_instances_with_relationship_name_implied_from_model()
{
$roles = FactoryTestRoleFactory::times(3)
->afterCreating(function ($role) {
$_SERVER['__test.role.creating-role'] = $role;
})
->create();
FactoryTestUserFactory::times(3)
->hasAttached($roles, ['admin' => 'Y'])
->create();

$this->assertCount(3, FactoryTestRole::all());

$user = FactoryTestUser::latest()->first();

$this->assertCount(3, $user->factoryTestRoles);
$this->assertSame('Y', $user->factoryTestRoles->first()->pivot->admin);

$this->assertInstanceOf(Eloquent::class, $_SERVER['__test.role.creating-role']);

unset($_SERVER['__test.role.creating-role']);
}

public function test_sequences()
{
$users = FactoryTestUserFactory::times(2)->sequence(
Expand Down Expand Up @@ -484,6 +522,11 @@ public function roles()
{
return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin');
}

public function factoryTestRoles()
{
return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin');
}
}

class FactoryTestPostFactory extends Factory
Expand All @@ -508,6 +551,11 @@ public function user()
return $this->belongsTo(FactoryTestUser::class, 'user_id');
}

public function factoryTestUser()
{
return $this->belongsTo(FactoryTestUser::class, 'user_id');
}

public function author()
{
return $this->belongsTo(FactoryTestUser::class, 'user_id');
Expand Down

0 comments on commit 3531b36

Please sign in to comment.