How to get random number in FactoryGirl?

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

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

I would really like the ranked number to be a random value between 0-10.

I want to generate ratings with different numbers, but I do not want to explicitly define them in rspec. This will be used to display average and other statistics from the rating numbers. Example: How much is 10, How much is 0, average, etc.

+7
rspec factory-bot
source share
2 answers

Is something like this possible?

 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 

Link here

+4
source share

Starting with 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 

By creating multiple instances, you can see the name randomization and price randomization:

 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') ] ] 
+13
source share

All Articles