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

$faker->optional() is not getting called foreach transaction #101

Open
manuphatak opened this issue May 5, 2015 · 3 comments
Open

$faker->optional() is not getting called foreach transaction #101

manuphatak opened this issue May 5, 2015 · 3 comments

Comments

@manuphatak
Copy link

$faker->optional() is only getting called ONE time per Seeder. So the results are either ALL filled or ALL empty instead of healthy mix of each.

Problem

Isolated example:

<?php // tests/factories/TimeEntryFactory.php

/** @var Closure $factory */
$factory('App\TimeEntry',
         [
             'user_id'    => 'factory:App\User',
             'comment'    => $faker->optional($weight = 0.5)->sentence()
         ]);

and

<?php // database/seeds/TimeEntryTableSeeder.php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Laracasts\TestDummy\Factory as TestDummy;


class TimeEntryTableSeeder extends Seeder
{

    public function run()
    {
        DB::table('time_entry')->delete();

        TestDummy::times(100)->create('App\TimeEntry');
    }
}

You would expect about 50/100 entries to have null "comments", instead it's randomly either 0 or 100.

Solution:

Using for loop instead of times() did not work.

Using a for loop, pulling in Faker, overriding the factory did.

Work around:

<?php // database/seeds/TimeEntryTableSeeder.php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
use Laracasts\TestDummy\Factory as TestDummy;

class TimeEntryTableSeeder extends Seeder
{

    protected $faker;

    function __construct(Faker $faker)
    {
        $this->faker = $faker->create();
    }

    public function run()
    {
        DB::table('time_entry')->delete();

        for ($i = 0; $i <= 100; $i++) {
            TestDummy::create(
                'App\TimeEntry',
                ['comment' => $this->faker->optional($weight = 0.5)->sentence()]
            );
        }
    }
}

With this solution, the results are no longer ALL or NOTHING, it looks 50/50.

@phroggyy
Copy link

What about using a closure instead? Would that not solve the issue or am I thinking in the wrong track?

@phroggyy
Copy link

I can't see why that'd make a difference though, since the create method runs a for loop over times

@ht2
Copy link

ht2 commented Mar 8, 2016

Hi @bionikspoon,

Your workaround was very helpful. Thanks for this

Pete

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants