laracasts / TestDummy

Easy factories for PHP integration testing.
https://laracasts.com/lessons/whats-new-in-testdummy
MIT License
456 stars 80 forks source link

Allow using closure for attributes #63

Closed swekaj closed 9 years ago

swekaj commented 9 years ago

The current method of passing in an array of attributes when defining a factory has a major limitation: you can only use scalars or single Faker calls unless you want to wrap them in complicated closures.

This aims to fix that. Now, instead of an array of attributes you can pass $factory() a closure that returns the array. The closure is passed an instance of the Faker generator that isn't wrapped, so there's no wonky closure business to deal with when using Faker. This allows the factory to create more complicated fields, such as $faker->randomElement([ null, $faker->dateTime ]) or $faker->name . "'s" . $faker->randomElement([ 'Bar', 'Grille' ]) (as mentioned in #59).

It also provides a way to conditionally fill fields based on data in other fields, which would currently be very cumbersome or impossible.

Some notes:

zoltanpeto commented 9 years ago

Hi,

I'd like to +1 this PR, seems to be a very handy addition.

One thing I'd add to it though, when you call the closure to get the fixtures array, you could pass in the overrides array too, along with the faker.

As a use case, in my project I need to create User and StaffMember models, where User contains the details for the site, and each user belongs to a StaffMember. I need the User dummy username field to be composed using StaffMember's surname and staff_number. Now this could be done easily if I create a new StaffMember dummy in the closure, by not if I want to pass in an existing StaffMember object as an override when creating the User dummy.

swekaj commented 9 years ago

@zoltanpeto That sound like a great idea, so I added it!

@laracasts / @JeffreyWay Any chance this can get merged?

phaza commented 9 years ago

+1. And I find it sad that it's been sitting here for nearly a month now. It has tests that pass and it adds great functionality.

vluzrmos commented 9 years ago

+1

williamoliveira commented 9 years ago

+1

vinicius73 commented 9 years ago

+1

JeffreyWay commented 9 years ago

Thanks for this! Sorry it took me a while to review and merge.

I'll update the docs.

swekaj commented 9 years ago

Awesome, thanks!