2

任何人都可以通过代码向我展示我们如何factory_girl在使用中转换此特定代码Fabrication吗?

factory :user do
  name "Friendly User"
  login { name }

  trait :male do
    name   "John Doe"
    gender "Male"
    login { "#{name} (M)" }
  end

  trait :female do
    name   "Jane Doe"
    gender "Female"
    login { "#{name} (F)" }
  end

  trait :admin do
    admin true
    login { "admin-#{name}" }
  end

  factory :male_admin,   traits: [:male, :admin]   # login will be "admin-John Doe"
  factory :female_admin, traits: [:admin, :female] # login will be "Jane Doe (F)"
end

如果你看到这个Trait in Fabrication inheritance是这里的方法之一,但问题是我们不能定义Fabricator它,因为它们不是models。谁能告诉我我们如何将属性分组Fabrication

4

1 回答 1

3

你在虚构中这样表达:

Fabricator :user do
  admin false
  gender 'Female'
  name "Friendly User"
  login do |attrs|
    if attrs[:admin]
      "admin-#{attrs[:name]}"
    else
      "#{attrs[:name]} (#{attrs[:gender][0]})"
    end
  end
end

Fabricator(:female_admin, from: :user) do
  admin true
end

Fabricator(:male_admin, from: :female_admin) do
  gender 'Male'
end
于 2016-03-21T13:04:54.217 回答