如何使用 RSpec 测试 `rand()`? [英] How do I test `rand()` with RSpec?
问题描述
我有一个方法可以做这样的事情:
I have a method that does something like this:
def some_method
chance = rand(4)
if chance == 1 do
# logic here
else
# another logic here
end
end
当我使用 RSpec 测试这个方法时,里面的 rand(4)
总是生成 0.我不是在测试 Rails 的 rand
方法,我是在测试我的方法.测试我的方法的常见做法是什么?
When I use RSpec to test this method, rand(4)
inside it always generates 0. I am not testing rand
method of Rails, I am testing my method.
What is a common practice to test my method?
推荐答案
我会考虑两种方法:
方法 1:
在 before :each
块中使用 srand( seed )
中的已知种子值:
Use a known value of seed in srand( seed )
in a before :each
block:
before :each do
srand(67809)
end
这适用于 Ruby 版本,并在您想要涵盖特定组合时为您提供控制权.我经常使用这种方法 - 仔细想想,那是因为我正在测试的代码主要使用 rand()
作为数据源,其次(如果有的话)用于分支.它也被大量调用,因此对返回值进行逐个调用控制会适得其反,我最终会在大量看起来随机"的测试数据中进行铲除,可能首先通过调用生成它 <代码>rand()!
This works across Ruby versions, and gives you control in case you want to cover particular combinations. I use this approach a lot - thinking about it, that's because the code I was testing uses rand()
primarily as a data source, and only secondarily (if at all) for branching. Also it gets called a lot, so exerting call-by-call control over returned values would be counter-productive, I would end up shovelling in lots of test data that "looked random", probably generating it in the first place by calling rand()
!
您可能希望在至少一个测试场景中多次调用您的方法,以确保您拥有合理的组合覆盖率.
You may wish to call your method multiple times in at least one test scenario to ensure you have reasonable coverage of combinations.
方法 2:
如果由于 rand()
输出的值而有分支点,并且断言是如果它选择 X,那么 Y 应该发生"的类型,那么它也是合理的测试套件模拟 rand( n )
并返回您想要断言的值:
If you have branch points due to values output from rand()
and your assertions are of the type "if it chooses X, then Y should happen", then it is also reasonable in the same test suite to mock out rand( n )
with something that returns the values you want to make assertions about:
require 'mocha/setup'
Kernel.expects(:rand).with(4).returns(1)
# Now run your test of specific branch
本质上,这些都是白盒"测试方法,它们都要求您知道您的例程在内部使用 rand()
.
In essence these are both "white box" test approaches, they both require you to know that your routine uses rand()
internally.
黑盒"测试要困难得多 - 您需要断言行为在统计上是正确的,并且您还需要接受非常广泛的可能性,因为有效的随机行为可能导致幻像测试失败.
A "black box" test is much harder - you would need to assert that behaviour is statistically OK, and you would also need to accept a very wide range of possibilities since valid random behaviour could cause phantom test failures.
这篇关于如何使用 RSpec 测试 `rand()`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!