Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 221
Mark Avatar asked Jan 05 '23 14:01

Mark


1 Answers

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)
like image 139
Andrey Deineko Avatar answered Jan 13 '23 10:01

Andrey Deineko