0

I have a User and UserProfile models. Currently both models have the attributes first_name, last_name, and email and they must be the same. Later on I will remove these attributes from User but currently I want it that way. A UserProfile belongs_to a User. I have defined the UserProfile fabricator like so:

Fabricator(:user_profile) do
  first_name { Faker::Name.first_name }
  last_name  { Faker::Name.last_name }
  email      { Faker::Internet.email }
  user       { Fabricate :user }
end

and the User fabricator:

Fabricator(:user) do
  email         { Faker::Internet.email }
  first_name    { Faker::Name.first_name }
  last_name     { Faker::Name.last_name }
  last_login_at { Time.now }
  organization  { Fabricate :organization }
end

The problem is that now, when I fabricate a user profile the attributes are not the same:

user_profile.first_name == user_profile.user.first_name # => false

In the definition of the user profile fabricator I tried this, but it didn't work:

user       { Fabricate :user, first_name: first_name, last_name: last_name, email: email }

How can I fabricate a user and a user profile with same attributes without having to replace Faker with hard coded values?

Alexander Popov
  • 23,073
  • 19
  • 91
  • 130

1 Answers1

0

I think the easiest way is to reorganize your user profile a bit and use the data from the user to populate its fields.

Fabricator(:user_profile) do
  user
  first_name { |attrs| attrs[:user].first_name }
  last_name  { |attrs| attrs[:user].last_name }
  email      { |attrs| attrs[:user].email }
end

Fabricator(:user) do
  email         { Faker::Internet.email }
  first_name    { Faker::Name.first_name }
  last_name     { Faker::Name.last_name }
  last_login_at { Time.now }
  organization
end
Paul Elliott
  • 1,174
  • 8
  • 9