重用 FactoryGirl 序列结果

Reusing FactoryGirl sequence results

如果我有一个 User class 的相当标准的工厂,就像这样:

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

然后一切如我所料,每次都获得一个唯一的用户名,除非我覆盖它。但我希望电子邮件基于用户名,如下所示:

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

当我尝试 build_stubbed a User 时,出现错误 Attribute already defined: username

我总是可以将 email 设置为另一个序列,当然,但是对于我覆盖用户名的测试,如果电子邮件匹配它,消息将更加清晰。有什么方法可以设置 username 自动递增并稍后在工厂中使用它的值吗?

使用块访问您当前的对象:

  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