RSpec 测试方法是否在方法内部被调用

RSpec test if method is being called inside a method

所以,我有以下几行代码,我想用 RSpec 进行模拟测试。

class BaseService
  MAX_BODY_SIZE = 100000.freeze

  def translate(body, language, account)
    return body if body.blank?

    translate_body_in_chunks(body, language, account) if body.size > MAX_BODY_SIZE
  end

  def translate_body_in_chunks(body, language, account)
    # some API call that I don't want to call while testing
  end
end

我想测试translate_body_in_chunks是否被调用。

RSpec 目前实施

body = 'a' * 10000000
mock = double(described_class)
allow(mock).to receive(:translate).with(body, 'en', '')

expect(mock).to receive(:translate_body_in_chunks)

我知道这个测试行不通。我只是将它添加到此处,以提示您我要测试的内容。

像这样的东西应该可以工作:

describe BaseService do
  describe '#translate' do
    context 'with a body exceeding MAX_BODY_SIZE' do
      let(:body) { 'a' * (BaseService::MAX_BODY_SIZE + 1) }

      it 'calls translate_body_in_chunks' do
        expect(subject).to receive(:translate_body_in_chunks)

        subject.translate(body, 'en', '')
      end
    end
  end
end

subject指的是通过BaseService.new创建的实例。

请注意,一般而言,您不应测试方法的实现 细节。相反,尝试测试该方法的 行为 .