使用Rspec测试随机值

时间:2013-07-15 17:30:32

标签: ruby-on-rails-3 rspec

我的一个模型中有一个返回随机行的方法

Intention.offset(rand(Intention.count)).first

它工作正常,但我怎样才能用Rspec测试它?

1 个答案:

答案 0 :(得分:1)

您可以在代码中执行此操作:

Kernel.rand(Intention.count)

并在您的规范中:

let(:intention_count) { 3 }

Intention.stub(:count).and_return(intention_count)
Kernel.stub(:rand).with(intention_count).and_return(0) # will return 0

基本上,我们使用Kernel类调用rand,以便能够stub该方法返回我们想要的内容。