在FactoryGirl中生成随机浮点数

3

我需要在我的测试代码中生成随机的纬度和经度值,但是使用Random类会产生重复的值导致测试失败,有什么方法可以在FactoryGirl中生成随机的浮点数值吗?

编辑:相关的代码片段如下:

factory :location do
  lat rand(-90.0..90.0)
  lng rand(-180.0..180.0)
end
2个回答

4

不确定为什么会出现重复值,但这个方法可能会起作用:

lat = rand(-90.0..90.0)
lng = rand(-180.0..180.0)

你可以使用固定值来为数字生成器seed提供种子,以便在测试中获得一致的随机数。
在factory_girl中:
factory :location do
  lat { rand(-90.0..90.0) }
  lng { rand(-180.0..180.0) }
end

在 FactoryGirl 中这样做,我会得到“Attribute already defined: rand”的错误。 - 8vius
@8vius,您能否请在您的问题中添加相关代码? - Stefan
@8vius 我已经更新了我的答案,你必须使用惰性属性 - Stefan

3
使用 faker 宝石。
factory :address do
  latitude { Faker::Address.latitude }
  longitude { Faker::Address.longitude }
end

这个可行,谢谢。同时还有其他领域的一些很不错的功能。 - 8vius

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接