Ruby rspec中简单随机行为的测试问题
我在测试rspec中的一些随机行为时遇到了一些问题。我在一个类上有一个方法,如果随机生成的数字等于10,它应该更改一个类实例变量。我找不到任何方法来正确测试rspec 这是这个类的代码Ruby rspec中简单随机行为的测试问题,ruby,rspec,Ruby,Rspec,我在测试rspec中的一些随机行为时遇到了一些问题。我在一个类上有一个方法,如果随机生成的数字等于10,它应该更改一个类实例变量。我找不到任何方法来正确测试rspec 这是这个类的代码 class Airport DEFAULT_CAPACITY = 20 attr_reader :landed_planes, :capacity attr_accessor :weather def initialize(capacity=DEFAULT_CAPACITY,we
class Airport
DEFAULT_CAPACITY = 20
attr_reader :landed_planes, :capacity
attr_accessor :weather
def initialize(capacity=DEFAULT_CAPACITY,weather = "clear")
@landed_planes = []
@capacity = capacity
@weather = weather
end
def stormy
if rand(10) == 10 then @weather = "stormy" end
end
end
有人知道我可以为stormy方法编写测试的方法吗?一个选项是使用rspec--seed 123启动rspec这将确保您的随机数始终是可预测的。但这将影响对rand、shuffle、sample等的所有后续调用 另一种方法是更改类以注入randnumber生成器:
class Airport
DEFAULT_CAPACITY = 20
attr_reader :landed_planes, :capacity
attr_accessor :weather
def initialize(capacity=DEFAULT_CAPACITY,weather = "clear", randomizer = ->(n) { rand(n)})
@landed_planes = []
@capacity = capacity
@weather = weather
@randomizer = randomizer
end
def stormy
if @randomizer.call(10) == 10 then @weather = "stormy" end
end
end