ruby - FactoryBot 的随机特征
问题描述
我想使用 FactoryBot 像这样随机返回特征:
FactoryBot.define do
factory :user do
[:active, inactive].sample
trait :active do
active { true }
...
end
trait :inactive do
active { false }
...
end
end
end
要做到这一点:
(1..5).map{ |e| FactoryBot.build(:user) }.map(&:active?)
=> [true, false, false, true, false]
其实是这样的:
FactoryBot.define do
factory :user do
active { [true, false].Sample }
name { "name-#{SecureRandom.uuid}" }
birthday { active == true ? rand(18..99).years.ago - rand(0..365).days.ago : nil }
preferred_contact_method { active == true ? %w(phone email).sample : nil }
activated_at { active == true ? rand(1..200).days.ago : nil }
contact_phone_number { preferred_contact_method == "phone" ? "+33XXXXXXXXX" : nil }
contact_email { preferred_contact_method == "email" ? "toto@tati.com" : nil }
end
end
有可能这样做吗?
解决方案
这是一个相当古老的问题,但与 OP 有相同的需求,我想我找到了解决方案,唉,它并不漂亮:
FactoryBot.define do
factory :user do
active { nil }
initialize_with do
if active.nil?
build :user, %i[active inactive].sample, attributes
else
User.new(attributes)
end
end
trait :active do
active { true }
...
end
trait :inactive do
active { false }
...
end
end
end
FactoryBot.create_list(:user, 5).map(&:active) #=> random array of booleans
FactoryBot.create_list(:user, 5, :active).all?(&:active?) #=> true
推荐阅读
- php - 是否可以进行服务器重定向并同时将引用者更改为重定向域的引用者?
- jetty - JettyConnectionMetrics 算什么?
- ios - 从js调用swift函数
- python - 使用 python 并行化 MatLab 函数时,使用射线进行 cloudpickle 酸洗时出错
- dpdk - 多队列可以与 DPDK vdev rx_pcap 一起使用吗
- arrays - 根据列中的公共字符串合并两个文件,并填写不匹配的缺失值
- apache-nifi - 如何更新断开连接的 NiFi-Registry?
- html - 在 react.js(next.js) 中未应用 css 比例
- javascript - 有没有办法判断 POST(正文)请求是格式化为 URL 编码的查询字符串还是 JSON 数据?
- python - Pandas:按最大值分组并在组上求和的最快方法