Ruby Rspec-如何存根第三方异常

Ruby Rspec-如何存根第三方异常,ruby,amazon-web-services,rspec,rspec3,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(S

我正在尝试测试是否能够捕获这些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)
但是当我测试这个存根时,我得到一个类型错误:

exception class/object expected
我必须包括AWS::Errors::ServerError吗?如果是的话,我会怎么做?我正在使用aws-sdk-v1 gem


谢谢。

我将构建一个端口,然后注入一个存根对象,该对象非常希望抛出一个错误。让我解释一下:

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
测试:


不必要求包含这些异常的特定文件,您可以在等级库文件中存根这些异常:

stub_const("AWS::Errors::ServerError", StandardError)
stub_const("AWS::Errors::ClientError", StandardError)
然后您的
expect
就可以工作了


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

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