rspec 测试一个 class 方法给出对象未被侦测或存根错误

rspec testing a class method giving object not spied or stubbed error

Rspec 测试

我有 class 呼叫客户。

class Client
  class << self
    def shutdown
      puts 'shutting down the producer gracefully'

      @producer ||= k_producer.producer(opts)
      @producer.shutdown
    end

    private
    def k_producer
      Kafka.new([127.0.0.1:9092], { required_acks: :all })
    end
  end
end

我想测试关机 class 方法,但我不明白存根或间谍的概念。

我正在尝试这种方式

RSpec.describe Client do
  describe "Client.shutdown" do
    it "calls shutdown" do
      described_class.shutdown
      expect(described_class).to have_received(:shutdown)
    end
  end
end

我收到此错误,我不知道如何告诉 rspec 我的 class 中有 @producer 并调用了它关闭。

Client (class)> expected to have received shutdown, but that object is not a spy or method has not been stubbed

您从未将 described_class 设置为间谍。您可以将其设为 partial double with allow.

RSpec.describe Client do
  describe "Client.shutdown" do
    it "calls shutdown" do
      allow(described_class).to receive(:shutdown)
      described_class.shutdown
      expect(described_class).to have_received(:shutdown)
    end
  end
end

但是,这个测试是同义反复。您只是在测试名为 Client.shutdown 的测试。测试调用 @producer.shutdown 更有用。

@producer 获取有点麻烦。通过为其内部对象添加访问器,我们可以使 Client 更易于测试,总体上更灵活。

class Client
  class << self
    # Define only the writers: producer= and kafka=
    attr_writer :producer, :kafka

    # Define the readers ourselves with our defaults.
    def producer
      @producer ||= kafka.producer(opts)
    end

    def kafka
      @kafka ||= Kafka.new(["127.0.0.1:9092"], { required_acks: :all })
    end

    def shutdown
      puts 'shutting down the producer gracefully'

      producer.shutdown
    end
  end
end

现在我们制作一个间谍,并将其设置为生产者。

RSpec.describe Client do
  describe "Client.shutdown" do
    it "calls @producer.shutdown" do
      producer = spy("producer")
      described_class.producer = producer
      
      described_class.shutdown

      expect(producer).to have_received(:shutdown)
    end
  end
end