What is the proper way to select an item randomly from an array when writing factories with factory_girl?
Asked Answered
X

1

22

If I have types defined in a module inside a model, and an array of these types also defined in the same model, how can I call a value from this array randomly when defining a new factory?

Thanks!

John

Xylophone answered 22/11, 2011 at 6:53 Comment(0)
D
43

Checkout this answer - use Array#sample:

FactoryGirl.define do
  factory :user do
    name "Foo Bar"
    foo { [:a, :list, :of, :values].sample }
  end
end
Discolor answered 22/11, 2011 at 8:10 Comment(1)
Easy to use for integers: ` FactoryGirl.define do factory :foo do bar { (1..99).to_a.sample(3) } end end `Ridiculous

© 2022 - 2024 — McMap. All rights reserved.