gpt4 book ai didi

ruby-on-rails - 我如何在我的 rspec 测试中考虑随机数?

转载 作者:数据小太阳 更新时间:2023-10-29 08:23:21 26 4
gpt4 key购买 nike

我遇到一个问题,即这些测试仅在随机数低于 20 时通过,我如何在我的测试中考虑到这一点?

我的测试:

it 'a plane cannot take off when there is a storm brewing' do
airport = Airport.new [plane]
expect(lambda { airport.plane_take_off(plane) }).to raise_error(RuntimeError)
end

it 'a plane cannot land in the middle of a storm' do
airport = Airport.new []
expect(lambda { airport.plane_land(plane) }).to raise_error(RuntimeError)
end

我的代码摘录:

def weather_rand
rand(100)
end

def plane_land plane
raise "Too Stormy!" if weather_ran <= 20
permission_to_land plane
end

def permission_to_land plane
raise "Airport is full" if full?
@planes << plane
plane.land!
end

def plane_take_off plane
raise "Too Stormy!" if weather_ran <= 20
permission_to_take_off plane
end

def permission_to_take_off plane
plane_taking_off = @planes.delete_if {|taking_off| taking_off == plane }
plane.take_off!
end

最佳答案

您需要 stub weather_rand 方法以返回已知值以匹配您尝试测试的值。

https://www.relishapp.com/rspec/rspec-mocks/v/2-14/docs/method-stubs

例如:

it 'a plane cannot take off when there is a storm brewing' do
airport = Airport.new [plane]
airport.stub(:weather_rand).and_return(5)
expect(lambda { airport.plane_take_off(plane) }).to raise_error(RuntimeError)
end

关于ruby-on-rails - 我如何在我的 rspec 测试中考虑随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19451498/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com