测试接收到的数组大小是否正确

Test the size of array received is correct

我想测试是否使用 特定长度的数组 调用了 class 的函数。

下面的示例我想验证函数 s3upload 是否使用数组大小​​为 2 的数组参数调用。

Project/lib/First/version.rb
  module Documentz
    class AwsUploader
      def s3upload(event_id:nil, docs: nil)
        puts("uploded")
      end
    end
  end
Project/lib/First.rb
  module Exporter
    class AnExporter
      def letsUpload
        Documentz::Uploader::AwsUploader.new.s3upload( docs :[1,2])
      end
    end
  end
ATest_spec.rb
  it 'helps in mocking a class' do
    exp=Exporter::AnExporter.new
    exp.letsUpLoad
    allow_any_instance_of(Documentz::Uploader::AwsUploader).to receive(:s3upload).with( {:docs=>[1,2]})
    ## how to check if the array size (:docs)==2
  end

正如您在 ATest_spec.rb 中注意到的那样,我能够测试参数是否为 [1,2],但我实际上想验证数组(接收到的参数)的大小实际上是否为 2。

你能告诉我怎么做吗?

这里你模拟了一个接收特定参数的方法,此外,你需要 return 一个文档 ID 数组(假设这就是你的 s3upload 方法 return )

allow_any_instance_of(Documentz::Uploader::AwsUploader).to receive(:s3upload).with( {:docs=>[1,2]}).and_return([1,2])
    
expect(exp.letsUpLoad.length).to eq 2

而不是 allow_any_instance_of 我会使用 new 方法的存根,并会 return 我监视预期方法调用的 instance_double 。为确保参数具有特定结构,请使用自定义匹配器,该匹配器可以根据需要进行复杂化,例如:

RSpec::Matchers.define :expected_data_structure do
  match { |actual| actual.is_a?(Hash)         &&
                   actual[:docs].is_a?(Array) && 
                   actual[:docs].size == 2    &&
                   actual[:docs].all?(Integer) 
  }
end

subject(:exporter) { Exporter::AnExporter.new }
let(:spy) { instance_double('Documentz::Uploader::AwsUploader') }

before do 
  allow(Documentz::Uploader::AwsUploader).to receive(:new).and_return(spy) 
end

it 'calls `s3upload` with the expected arguments' do
  exporter.letsUpLoad

  expect(spy).to have_received(:s3upload).with(expected_data_structure)
end

在 RSpec 文档中阅读有关 custom matches 的内容。

顺便说一句。在 Ruby 中,按照惯例,方法名称是用下划线而不是驼峰式书写的。按照该规则,您的方法应命名为 lets_up_load(或只是 upload)而不是 letsUpLoad