ruby - RSpec spy 在两个不同类别中的工作方式不同

标签 ruby amazon-s3 rspec rspec-mocks

我有一个类Uploader,它接受一个文件并将其上传到S3。我正在尝试测试在调用 upload_file@s3 是否实际接收文件正文。当我测试 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

最佳答案

我最终为这个特定的测试模拟了 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

关于ruby - RSpec spy 在两个不同类别中的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38110813/

相关文章:

ruby-on-rails - 功能规范和 View 规范之间有什么区别吗?

ruby-on-rails - Rspec 测试失败,当用户应该被授予访问他拥有的交易的权限时,用户被重定向

ruby-on-rails - 如何在 Ruby on Rails 中注册服务 worker ?

ruby - 在 Sinatra 中处理 POSTDATA

ruby-on-rails - Rails 实例变量在开发中显示,但在 Heroku 中不显示

ruby-on-rails - 带有 rails 的欧洲电话格​​式

mysql - Amazon S3 - 以编程方式创建目录结构

java - 如何从 amazon s3 获取文件大小、时间和 md5?

amazon-web-services - 如何一次从 Amazon S3 上的多个对象中删除删除标记

ruby-on-rails - rails - rspec - 为什么这个 "validates_inclusion_of :role, :in => %w[one, two, three ] }"不起作用