重用FactoryGirl序列结果

时间:2015-02-18 12:02:33

标签: ruby factory-bot

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

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 User时,我收到错误Attribute already defined: username

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

1 个答案:

答案 0 :(得分:1)

使用块来访问当前对象:

  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