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

\Zenstruck\Foundry\ModelFactory::getDefaults() is called even if attributes are defined #377

Closed
syl20b opened this issue Dec 7, 2022 · 3 comments

Comments

@syl20b
Copy link

syl20b commented Dec 7, 2022

Hi,

and thank you for this library :)

I'm using it in a Symfony project, with Behat as test runner.

Given the following ModelFactory :

final class ServiceFactory extends ModelFactory
{
    /**
     * @return array<string, mixed>
     */
    protected function getDefaults(): array
    {
        return [
            'code' => self::faker()->unique()->word(),
            'label' => self::faker()->text(),
        ];
    }

    protected static function getClass(): string
    {
        return Service::class;
    }
}

I'have a couple of Behat Scenario that call that Factory to create new entities :

ServiceFactory::new(['code' => 'qwerty', 'label' => 'My label'])->create();

But I encounter this issue Maximum retries of 10000 reached without finding a unique value. even if I specify all attributes.

As I understand regarding to the source code of the \Zenstruck\Foundry\ModelFactory::new() method, the getDefaults() method is always called, even if attributes are passed to the method, which leads to call faker and reach the maximum retries to find a value.

Do I miss something?
Is there a way to not to call the getDefaults() methods when attributes are defined ?

Thank you,

Regards

@kbond
Copy link
Member

kbond commented Dec 7, 2022

Hey @syl20b,

Calling getDefaults is required to ensure the required attributes are always available if not overridden.

I think maybe your issue is not shutting down foundry after each scenario (calling Factory::shutdown()). This resets the faker unique "cache".

We are planning an official Behat Foundry Context (see #235). In the meantime, take a look at the example context in that issue: #235 (comment)

@syl20b
Copy link
Author

syl20b commented Dec 7, 2022

Thank you for the quick response @kbond
I will check this out ;)

Do you plan to add this context (#235) in the next release ?

@kbond
Copy link
Member

kbond commented Dec 7, 2022

Not sure yet, working on a draft PR.

@syl20b syl20b closed this as completed Dec 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants