如何获得FactoryGirl中的随机数?

时间:2013-10-02 16:22:28

标签: rspec factory-bot

FactoryGirl是否可以定义0-10的随机数?

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

我真的希望生成的排名数是0-10之间的随机值。

我想生成具有不同数字的评级,但不希望在rspec中明确定义它们。这将用于显示评级数字中的平均值和其他统计数据。例如:10多个,0个,平均等等。

2 个答案:

答案 0 :(得分:18)

从版本4.4开始,以下内容适用于我......

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

对于随机化的略有不同的用法:

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

创建一些实例,您可以看到名称的随机化以及价格的随机化:

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')
    ]
]

答案 1 :(得分:6)

这样的事可能吗?

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