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