rubydependency-injectionrspecmockingrspec-mocks

Dependency Injection causing both Rspec failure and IRB failure


Note: I am a Ruby and programming novice. I have a class called JourneyLog I am trying to get a method called start to instantiate a new instance of another class, called Journey

class JourneyLog
  attr_reader :journey_class

   def initialize(journey_class: Journey)
    @journey_class = journey_class
    @journeys = []
  end

  def start(station)
   journey_class.new(entry_station: station)
 end
end

When I go into irbi get the following issue

    2.2.3 :001 > require './lib/journeylog'
     => true
    2.2.3 :002 > journeylog = JourneyLog.new
    NameError: uninitialized constant JourneyLog::Journey
    from /Users/BartJudge/Desktop/Makers_2018/oystercard-challenge/lib/journeylog.rb:4:in `initialize'
    from (irb):2:in `new'
    from (irb):2
    from /Users/BartJudge/.rvm/rubies/ruby-2.2.3/bin/irb:15:in `<main>'
2.2.3 :003 >

I also have the following Rspec test

require 'journeylog'
describe JourneyLog do
  let(:journey) { double :journey, entry_station: nil, complete?: false, fare: 1}
  let(:station) { double :station }
  let(:journey_class) { double :journey_class, new: journey }

  describe '#start' do
    it 'starts a journey' do
      expect(journey_class).to receive(:new).with(entry_station: station)
      subject.start(station)
    end

  end
end

I get the following Rspec failure;

1) JourneyLog#start starts a journey
     Failure/Error: expect(journey_class).to receive(:new).with(entry_station: station)

       (Double :journey_class).new({:entry_station=>#<Double :station>})
           expected: 1 time with arguments: ({:entry_station=>#<Double :station>})
           received: 0 times
     # ./spec/jorneylog_spec.rb:9:in `block (3 levels) in <top (required)>'

I am at a total loss on what the problem is, or where to look for some answers. I'm assuming I'm not injecting the Journey class properly, but thats as far as I can get myself. Could someone provide some assistance?


Solution

  • In the journeylog.rb file you need to load the Journey class:

    require 'journey' # I guess the Journey class is defined in lib/journey.rb
    

    In the spec file you need to pass journey_class to the JourneyLog constructor:

    describe JourneyLog do
      subject { described_class.new(journey_class: journey_class) }
      # ...