digitig
digitig

Reputation: 2140

Reusing FactoryGirl sequence results

If I have a fairly standard factory for a User class, like this:

FactoryGirl.define do
  sequence :username do |n|
    "User#{n}"
  end
  factory :user do
    username
    email '[email protected]'
    password 'password'
    password_confirmation 'password'
  end
end

then everything works as I'd expect, getting a unique username every time unless I override it. But I'd like the email to be based on the username, like this:

FactoryGirl.define do
  sequence :username do |n|
    "User#{n}"
  end
  factory :user do
    username
    email "#{username}@example.com" # doesn't work
    password 'password'
    password_confirmation 'password'
  end
end

When I try to build_stubbed a User, I get an error Attribute already defined: username.

I could always set up email as another sequence, of course, but for the tests where I override the username the messages will be clearer if the email matches it. Is there any way I can set up username to automatically increment and still use its value later on in the factory?

Upvotes: 1

Views: 196

Answers (1)

dgilperez
dgilperez

Reputation: 10796

Use a block to access your current object:

  FactoryGirl.define do
    sequence :username do |n|
      "User#{n}"
    end
    factory :user do
      username
      email { |u| "#{u.username}@example.com" }
      password 'password'
      password_confirmation 'password'
    end
  end

Upvotes: 1

Related Questions