依赖注入导致Rspec故障和IRB故障

时间:2019-02-02 15:24:17

标签: ruby dependency-injection rspec mocking rspec-mocks

注意:我是Ruby和编程新手。 我有一类称为JourneyLog我试图得到所谓的方法start实例化另一个类,称为的新实例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

当我进入irb时,遇到以下问题

    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 >

我也有以下Rspec的测试

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

我得到以下Rspec的故障;

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)>'

我完全不知道问题是什么,或者在哪里寻找答案。 我假设我没有正确注射Journey类,但多数民众赞成至于我能得到自己。 有人可以提供帮助吗?

1 个答案:

答案 0 :(得分:1)

journeylog.rb文件中,您需要加载Journey类:

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

在spec文件中,您需要将journey_class传递给JourneyLog构造函数:

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