测试是否在外来类上调用方法

问题描述 投票:-2回答:1

如何测试MyModel.all是否被调用?

以下代码无法正常运行:

class MyClass
  def call
    cached_records
  end

  private

  def cached_records
    Rails.cache.fetch(self.class.name.underscore) do
      MyModel.all
    end
  end 
end

RSpec.describe MyClass do
  subject { MyClass.new }

  describe '#call' do
    it 'only queries the database the first time' do
      expect(MyModel).to receive(:all).once

      MyClass.call
      MyClass.call
    end
  end

end

ruby-on-rails ruby rspec stub
1个回答
0
投票

显然,我通过调整期望值找到了答案。

expect(MyModel).to receive(:all).once.and_call_original

为什么需要指定调用原始方法?

© www.soinside.com 2019 - 2024. All rights reserved.