Posted almost 7 years ago. Visible to the public.

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 :

Copy
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:

Copy
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

Copy
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 sequences 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).

Owner of this card:

Avatar
Dominik Schöler
Last edit:
almost 7 years ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more