Alex Takitani
Alex Takitani

Reputation: 501

Testing for random values with Rspec

I have a method in one of my models that returns a random row

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

It works fine, but how can I test it with Rspec?

Upvotes: 0

Views: 444

Answers (1)

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

You can do this in your code:

Kernel.rand(Intention.count)

and in your spec:

let(:intention_count) { 3 }

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

Basically, we are calling rand using the Kernel class to be able to stub that method to return what we want.

Upvotes: 1

Related Questions