FactoryGirl 是否可以定义一个从 0 到 10 的随机数?
factory :rating do
ranking 1 #random number?
recipe
end
我真的希望生成的排名数字是 0-10 之间的随机值。
我想用不同的数字生成评级,但不想在 rspec 中明确定义它们。这将用于显示评级数字的平均值和其他统计数据。例如:多少个 10、多少个 0、平均值等。
最佳答案
从 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')
]
]
关于rspec - 如何在 FactoryGirl 中获取随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19141836/