How to get a random number in FactoryGirl?
Asked Answered
M

2

18

Is it possible for FactoryGirl to define a random number say from 0-10?

    factory :rating do
       ranking 1 #random number?
       recipe
    end

I'd really like the ranking number generated to be a random value between 0-10.

I want to generate ratings with different numbers, but don't want to explicitly define them in rspec. This would be used to display the average and other stats from the rating numbers. Ex: How many 10's, How many 0's, average etc.

Merari answered 2/10, 2013 at 16:22 Comment(0)
B
23

As of version 4.4, the following works for me...

factory :rating do
   ranking {rand(1..10)}
   recipe
end

And for a slightly different use of randomization:

FactoryGirl.define do
  factory :plan do
    name {["Free", "Standard", "Enterprise"].sample}
    price {Faker::numerify('$##')}
  end
end

Creating a few instances, you can see the randomization of name, and the randomization of the price:

2.0.0-p247 :010 > 4.times.each {FactoryGirl.create(:plan)}
2.0.0-p247 :011 > ap Plan.to_list
[
    [0] [
        [0] "Free: $48",
        [1] BSON::ObjectId('549f6da466e76c8f5300000e')
    ],
    [1] [
        [0] "Standard: $69",
        [1] BSON::ObjectId('549f6da466e76c8f5300000f')
    ],
    [2] [
        [0] "Enterprise: $52",
        [1] BSON::ObjectId('549f6da466e76c8f53000010')
    ],
    [3] [
        [0] "Free: $84",
        [1] BSON::ObjectId('549f6da466e76c8f53000011')
    ]
]
Bromeosin answered 28/12, 2014 at 2:48 Comment(1)
Good solution, however I would suggest using the sample method in the Array Class instead. name {["Free", "Standard", "Enterprise"].sample}Plural
C
6

Something like this possibly?

FactoryGirl.define do
  sequence(:random_ranking) do |n|
    @random_rankings ||= (1..10).to_a.shuffle
    @random_rankings[n]
  end

  factory :user do
    id { FactoryGirl.generate(:random_ranking) }
  end
end

Reference here

Cellist answered 2/10, 2013 at 16:30 Comment(1)
This works, I wasn't aware of the generate command. Looking it up you can drop the FactoryGirl part and just have id { generate(:random_ranking) }Merari

© 2022 - 2024 — McMap. All rights reserved.