Allow more control over factory definitions #333
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Closes: #309, #272, #271
Description
Currently
build(:user)
will grab the struct/map defined inuser_factory/0
and merge any attributes passed into it viastruct!/2
orMap.merge/2
.It would be nice to allow users to have more control of factories if they want to, while maintaining the ease of use for the majority of cases. It seems this can be done by allowing users to change the
user_factory/0
to a factory that takes in the attributes being passed in.We can do so by checking if they have defined a factory with
/1
arity (meaning they allow parameters to be passed).Example
Let's take a look at a scenario where this might be wanted:
As we can see the issue is that since we derive the
email
from thename
, the email has the old name in it, even when we pass "James" as the name. It would be nice to be able to get thename
from the attributes before we create the email.So we could define this instead,
Note the inclusion of
merge_attributes/2
in our example above. We need that so thatage
gets properly overridden from20
to30
.The
merge_attributes/2
function is a new function we expose to make it easier for users to merge attributes regardless of whether it is a struct or a map. It essentially delegates tostruct!/2
orMap.merge/2
.Non-map factories
Because it provides full control over the factory, we can also now define non-map factories.