【问题标题】:Rspec - How to stub a 3rd party exceptionRspec - 如何存根第 3 方异常
【发布时间】:2014-10-31 00:05:58
【问题描述】:

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

谢谢。

【问题讨论】:

  • 你在哪一行得到TypeError
  • ../gems/rspec-mocks-3.1.3/lib/rspec/mocks/message_expectation.rb:194
  • 您的代码对我来说似乎很好。我唯一担心的是需要 s3client 和 AWS 堆栈库。只是为了实验,尝试将 S3Client 替换为默认知道的任何类 rails(例如任何模型)和 AWS::Errors... 由 StandardError 并运行您的测试。
  • @Alexander,是的,测试很好。如果我将 AWS::Errors::ServerError 替换为 AWS::Errors::RandomError(它不存在),那么我会得到:“未初始化的常量 AWS::Errors::RandomError”。所以听起来 AWS::Errors::ServerError 肯定包括在内。还有其他想法吗?或者也许是一种不同的测试方法?谢谢。
  • @Slowfib:你找到解决方案了吗?我遇到了类似的问题。

标签: ruby amazon-web-services rspec rspec3


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    那么你的expect 就可以了。

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

    【讨论】:

      猜你喜欢
      • 2014-09-23
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2014-01-12
      • 2015-08-31
      • 1970-01-01
      • 2013-03-01
      • 2013-02-18
      相关资源
      最近更新 更多