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 Archive :
CopyGiven 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:
CopyGiven 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
Copyfactory :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.
Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).