Falko
Falko

Reputation: 1035

Mocking an instance method in Rspec

I'm testing a ruby class using Rspec in Rails

class VolumeAnalysis

That class has a method that makes calls to active record

returned_volumes

This method grabs an array of items from active record and returns something like:

[
    <struct volumeAnalysis::Entry date="2019-12-03", volume=0.3864511633501078e4, predicted=0.143488366498922e3>,
    <struct volumeAnalysis::Entry date="2019-12-04", volume=0.3699056933789016e4, predicted=0.165454699712062e3>,
....
....
....
.... ]

Other methods in the class which I wish to test depend on this method, how do mock this methods return value?

Upvotes: 0

Views: 401

Answers (1)

BenKoshy
BenKoshy

Reputation: 35595

Try something like this:

allow(volume_analysis).to receive(:returned_volumes) { and_then_create_your_entry_structs_here }

def and_then_create_your_entry_structs_here
  [VolumeAnalysis::Entry.new(DateTime.current, 0.123, 0.123)] 
  # this is quick and dirty - you'll have to create the Entry objects properly
end

Upvotes: 2

Related Questions