Mark
Mark

Reputation: 6455

RSpec - stubbing an instance method

I've added the following method into the middle of a project:

def finishes_after_venue_shuts?
  return unless venue && finish
  day = regular_day ? regular_day : start.strftime('%a').downcase
  finish > venue.openingtimes.where(default_day: day).pluck(:finish)[0]
end

This has caused 1000+ tests to fail within the project. They're failing with the following error code:

ArgumentError:
  comparison of ActiveSupport::TimeWithZone with nil failed

I've tried to stub out the method as follows but am apparently doing something wrong:

before do
  allow(Event.any_instance).to receive(:finishes_after_venue_shuts?).and_return(false)
end

What is the correct syntax for stubbing out the method and simply returning false rather than performing the code?

Thanks in advance.

Upvotes: 4

Views: 3333

Answers (2)

Andrey Deineko
Andrey Deineko

Reputation: 52367

You were close :)

allow_any_instance_of(Event)
  .to receive(:finishes_after_venue_shuts?)
  .and_return(false)

But using allow_any_instance_of is considered a bad practice, so more appropriate would be using a double:

let(:event) { instance_double(Event, finishes_after_venue_shuts?: false) }

allow(Event).to receive(:new).and_return(event)

Upvotes: 8

Sapna Jindal
Sapna Jindal

Reputation: 422

You can also do:

Event.any_instance.stub(:finishes_after_venue_shuts).and_return(false)

Upvotes: 1

Related Questions