简体   繁体   中英

How to group attributes in Fabrication like using trait in Factory_Girl

Could you anyone through code show me how we can convert this particular factory_girl code in using 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

If you see this Trait in Fabrication inheritance is one of the method here but the problem is we cannot define Fabricator for it since they are not models . Can anyone show me how can we group attributes in Fabrication ?

You express it like this in fabrication:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM