ruby - Rspec - 如何 stub 第 3 方异常

标签 ruby amazon-web-services rspec rspec3

我正在尝试测试我是否能够捕获这些 AWS 异常:

begin
  s3_client = S3Client.new
  s3_file = s3_client.write_s3_file(bucket, file_name, file_contents)
rescue AWS::Errors::ServerError, AWS::Errors::ClientError => e
  # do something
end

我的 Rspec 3 代码:

expect_any_instance_of(S3Client).to receive(:write_s3_file).and_raise(AWS::Errors::ServerError)

但是当我测试这个 stub 时,我得到一个类型错误:

exception class/object expected

我必须包括 AWS::Errors::ServerError 吗?如果是这样,我该怎么做?我正在使用 aws-sdk-v1 gem。

谢谢。

最佳答案

我会构建一个端口,然后注入(inject)一个即将向您抛出错误的 stub 对象。让我解释一下:

class ImgService
  def set_client(client=S3Client.new)
    @client = client
  end

  def client
    @client ||= S3Client.new
  end

  def write(bucket, file_name, file_contents)
    begin
      @client.write_s3_file(bucket, file_name, file_contents)
    rescue AWS::Errors::ServerError, AWS::Errors::ClientError => e
      # do something
    end
  end
end

测试:

describe "rescuing an AWS::Error" do
  before :each do
    @fake_client = double("fake client")
    allow(@fake_client).to receive(:write_s3_file).and_raise(AWS::Errors::ServerError)

    @img_service = ImgService.new
    @img_service.set_client(@fake_client)
  end
  # ...
end

关于ruby - Rspec - 如何 stub 第 3 方异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665520/

相关文章:

amazon-web-services - Jenkins amazon-ecr 插件问题

amazon-web-services - AWS-Elastic Beanstalk CLI-如何列出/更改配置文件

ruby-on-rails - 在 Rails 应用程序中测试 View 的最佳方法

ruby-on-rails - rails 5 : Render a div for each child object in a collection

ruby - Nokogiri 抓取带有格式和链接标签的文本,<em>、<strong>、<a> 等

amazon-web-services - 如何将文件从 Docker 镜像写入 EFS?

ruby-on-rails - 使用 Rspec 和 capybara 进行产品模型测试

ruby - Rspec——模拟另一个类中的方法

ruby - 检查 ActiveRecord::Base 实例的测试代码

Ruby:执行 bash 命令,捕获输出并同时转储到屏幕