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

Extra unwanted entities created when testing #29

Closed
DessyRascal opened this issue Aug 9, 2020 · 4 comments
Closed

Extra unwanted entities created when testing #29

DessyRascal opened this issue Aug 9, 2020 · 4 comments

Comments

@DessyRascal
Copy link

Hi All,

Probably being a moron but how do I get my factory to stop creating new entities when passing in the entity I want via the create function.

i.e

$reply = ReplyFactory::new()->create(['thread' => $thread, 'body' => 'Test Body']);

Still creates a new thread despite me passing the specific thread instance to the create function

   protected function getDefaults(): array
    {
        return [
            'body' => self::faker()->paragraph(3, true),
            'thread' => ThreadFactory::new()->create()
        ];
    }

I presumed (rightly or wrongly) that the thread would only create when newing up a reply if not overridden.

@kbond
Copy link
Member

kbond commented Aug 10, 2020

Ah, I think I see the issue but want to clarify:

When creating the reply from your example above, the proper thread is created and connected to the reply but an "extra" one is created as well (that is not connected to the reply)?

If I understand correctly, then the issue is in your getDefaults() you are returning an array with a created random thread. This is always created when calling getDefaults(). The solution would be to change your getDefaults to:

protected function getDefaults(): array
{
    return [
        'body' => self::faker()->paragraph(3, true),
        'thread' => ThreadFactory::new(), // NOTE: I removed the ->create()
    ];
}

This way, getDefaults() returns an array containing an unpersisted ThreadFactory which Foundry will create and persist only if it isn't overridden.

Does that make sense?

@DessyRascal
Copy link
Author

Thanks - thats exactly what I was doing wrong - had to rewrite my AppFixtures slightly but all now working as I need.

Said I was likely just being a moron :)

@kbond
Copy link
Member

kbond commented Aug 10, 2020

Great and thanks for bringing this to light for me!

It isn't clear in the docs that getDefaults() can also return factories (to avoid this problem). I'll update the docs.

@DessyRascal
Copy link
Author

No worries - glad my stumbling can be of service :)

This issue was closed.
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