Posted over 6 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 :

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!


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 instance.first_name, instance.last_name =' ') 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.

Flaky tests are tests that sometimes fail for no obvious reason. They are the plague of many end-to-end (E2E) test suites that automate the browser through tools like Capybara and Selenium.

Join our free training event and learn to fix any flaky test suite, even in large legacy applications.

Owner of this card:

Dominik Schöler
Last edit:
over 6 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