我的一个模型中有一个返回随机行的方法
Intention.offset(rand(Intention.count)).first
它工作正常,但我怎样才能用Rspec测试它?
答案 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
该方法返回我们想要的内容。