16

FactoryGirl 是否可以定义一个从 0 到 10 的随机数?

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

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

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

4

2 回答 2

21

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')
    ]
]
于 2014-12-28T02:48:37.833 回答
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

参考这里

于 2013-10-02T16:30:10.870 回答