我正在尝试测试我是否能够捕获这些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。
感谢。
答案 0 :(得分: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
答案 1 :(得分:0)
无需要求具有这些例外的特定文件,您可以在规范文件中存入例外:
stub_const("AWS::Errors::ServerError", StandardError)
stub_const("AWS::Errors::ClientError", StandardError)
然后您的expect
将起作用。
这对于测试ActiveRecord::RecordNotUnique
之类的Rails异常也很有效。