RSpec间谍在两个不同的类别上的工作方式不同

时间:2016-06-29 22:03:23

标签: ruby amazon-s3 rspec rspec-mocks

我有一个类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

1 个答案:

答案 0 :(得分: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