2

我正在尝试测试我是否能够捕获这些 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)

但是当我测试这个存根时,我得到一个 TypeError:

exception class/object expected

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

谢谢。

4

2 回答 2

0

我会构建一个端口,然后注入一个存根的对象,该对象只是想给你一个错误。让我解释:

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
于 2014-11-01T02:34:35.847 回答
0

不必要求具有这些异常的特定文件,您可以在规范文件中存根异常:

stub_const("AWS::Errors::ServerError", StandardError)
stub_const("AWS::Errors::ClientError", StandardError)

然后你expect会工作。

这也适用于测试 Rails 异常,例如ActiveRecord::RecordNotUnique.

于 2019-01-22T18:59:34.133 回答