我有一个小型服务类,只需在S3周围复制一些图像。为了简化这个问题,它看起来有点但不完全是这样的:
class BadgeUpdateJob < Struct.new(:badge)
def perform
source_filename = generate_source_filename
dest_filename = generate_dest_filename
storage = Fog::Storage.new({:provider => 'AWS', :aws_access_key_id => ENV['S3_KEY'], :aws_secret_access_key => ENV['S3_SECRET'] })
dir = storage.directories.get(s3_bucket_key)
source_file = dir.files.get(source_filename)
if source_file
source_file.copy(dir.key, dest_filename)
else
# Notify dev team, something is horribly wrong.
end
end
end
我可以看到一些明显的错误 - 存储桶可能不存在,源文件可能不存在,但我知道我想如何测试这些 - 我只是设置模拟雾,导致这些错误发生自然。
我可以看到其他错误的是超时...上面的代码段中至少有4个网络操作,任何可能失败/超时。我想优雅地处理这个问题。
这样做有'正确'吗?有关“最佳”方式的任何建议,如果没有?
答案 0 :(得分:2)
如果它没有被Fog的模拟层实现,你可以随时使用老式的RSpec模拟。
describe 'BadgeUpdateJob' do
describe 'timeouts' do
it 'catches timeouts on authentication' do
Fog::Storage.stub(:new).and_raise(Excon::Errors::Timeout)
# ... expect(your code).to handle_it_properly
end
it 'catches timeouts on directories.get' do
Fog::Storage::AWS::Directories.any_instance.stub(:get).and_raise(Excon::Errors::Timeout)
# ...
end
end
end