FactoryGirl: How to easily create users with first and last name
In most of our applications, users have their first and last name stored in separate columns. However, specifying them separately quickly gets annoying, especially when proxying them from cucumber_factory Show archive.org snapshot :
Given there is a user with the first name "Dominik" and the last name "Schöler"
Wouldn't it be nice if you could just say:
Given there is a user with the name "Dominik Schöler"
and have FactoryGirl assign first and last name automatically? The code below achieves that!
Solution
factory :user do
transient do
name nil
end
sequence(:first_name) { |i| "First name #{i}" }
sequence(:last_name) { |i| "Last name #{i}" }
after(:build) do |instance, evaluator|
if evaluator.name
instance.first_name, instance.last_name = evaluator.name.split(' ')
end
end
end
Explanation: transient
attributes behave like attributes, except that they aren't assigned to the record. By defining the transient name
, we have a bucket to put the name in. The sequence
s just generate first and last name, they are a basic feature.
after(:build)
we try whether the factory was passed a name
value. If so, we assign first and last (actually, "second") name.