Read more

FactoryGirl: How to easily create users with first and last name

Dominik Schöler
July 07, 2015Software engineer at makandra GmbH

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"
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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 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.

Posted by Dominik Schöler to makandra dev (2015-07-07 17:54)