achalk
achalk

Reputation: 3449

RSpec: How to test init methods

I want to test whether a certain method is called when I initialize a new instance of a class. In my project, I have the following code:

class Journey
  def initialize(entry_station)
    @journey_complete = false
    @entry_station = entry_station
    self.start_journey
  end

  def start_journey
    ...
  end
end

I want to write an RSpec test that checks start_journey is called on all new journey instances at initialisation. Usually, to check a method has run, I expect an object to receive a certain message, then run the code that I expect to send it. e.g.

expect(journey).to receive(:start_journey)
Journey.new(station)

I can't do this here, as the journey instance I want to test doesn't exist until I run the code on line two. Does RSpec have a solution to this for testing init methods?

Upvotes: 1

Views: 649

Answers (1)

You are searching for it:

expect_any_instance_of(Journey).to receive(:start_journey)

https://github.com/rspec/rspec-mocks#settings-mocks-or-stubs-on-any-instance-of-a-class

Upvotes: 1

Related Questions