Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add raw() method to factory #34278

Merged
merged 2 commits into from
Sep 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/Illuminate/Database/Eloquent/Factories/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,19 @@ public function make($attributes = [], ?Model $parent = null)
return $instances;
}

/**
* Get the raw attributes generated from the factory.
*
* @param array $attributes
* @param \Illuminate\Database\Eloquent\Model|null $parent
* @return array
*/
public function raw($attributes = [], ?Model $parent = null)
{
return $this->state($attributes)
->getExpandedAttributes($parent);
}

/**
* Make an instance of the model with the given attributes.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/Database/DatabaseEloquentFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,27 @@ public function test_make_creates_unpersisted_model_instance()
$this->assertCount(0, FactoryTestUser::all());
}

public function test_basic_model_attributes_can_be_created()
{
$user = FactoryTestUserFactory::new()->raw();
$this->assertIsArray($user);

$user = FactoryTestUserFactory::new()->raw(['name' => 'Taylor Otwell']);
$this->assertIsArray($user);
$this->assertEquals('Taylor Otwell', $user['name']);
}

public function test_expanded_model_attributes_can_be_created()
{
$post = FactoryTestPostFactory::new()->raw();
$this->assertIsArray($post);

$post = FactoryTestPostFactory::new()->raw(['title' => 'Test Title']);
$this->assertIsArray($post);
$this->assertIsInt($post['user_id']);
$this->assertEquals('Test Title', $post['title']);
}

public function test_after_creating_and_making_callbacks_are_called()
{
$user = FactoryTestUserFactory::new()
Expand Down