0

我有一个类Uploader,它需要一个文件并将其上传到 S3。我正在尝试测试在被调用@s3时实际上是在接收文件正文。upload_file当我测试File正在发送消息时,测试通过了。然而,试图窥探Aws::S3::Client是行不通的。

class Uploader
  def initialize(tmp_dir_name, bucket)
    @base_tmp_dir = tmp_dir_name
    @s3 = Aws::S3::Client.new(region: 'us-east-1')
    @bucket = bucket
    @uploaded_assets = []
  end

  def upload_file(key, file_path)
    file = File.new(file_path)
    @s3.put_object(bucket: @bucket, key: key.to_s, body: file.read)
  end
end

RSpec.describe Uploader do
  let(:bucket) { 'test_bucket' }
  let(:base_temp_dir) { 'test_temp_dir' }
  let(:uploader) { Uploader.new(base_temp_dir, bucket) }

  describe "#upload_file" do
    let(:file) { double('file') }
    before { allow(File).to receive(:new) { file } }
    before { allow(file).to receive(:read).and_return('text') }
    before { allow(Aws::S3::Client).to receive(:put_object) }

    it "uses one file" do
      uploader.upload_file('test_key', 'file_path')
      expect(File).to have_received(:new).with('file_path')
    end

    it "sends data to s3" do
      uploader.upload_file('test_key', 'file_path')
      expect(Aws::S3::Client).to have_received(:put_object)
    end
  end
end
4

1 回答 1

0

我最终为这个特定的测试模拟了 s3。

    it "sends data to s3" do
      test_key = 'test_key'
      bucket = 'test_bucket'
      fake_s3 = instance_double(Aws::S3::Client)
      allow(Aws::S3::Client).to receive(:new).and_return(fake_s3)
      allow(fake_s3).to receive(:put_object)

      uploader.upload_file(test_key, 'file_path', record=true)
      expect(fake_s3).to have_received(:put_object).with(
        {bucket: bucket, key: test_key, body: 'text'})
    end
于 2016-06-30T15:09:55.697 回答