2014-10-31 43 views
2

我想測試我能捕捉到這些AWS例外:Rspec的 - 如何存根第三方例外

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 ::錯誤:: SERVERERROR?如果是這樣,我該怎麼做?我正在使用aws-sdk-v1 gem。

謝謝。

+0

在哪一行,你得到'TypeError'? – 2014-10-31 00:48:20

+0

../gems/rspec-mocks-3.1.3/lib/rspec/mocks/message_expectation.rb:194 – Slowfib 2014-10-31 02:11:42

+0

你的代碼對我來說似乎很好。我唯一需要考慮的是s3client和AWS堆棧庫。只是爲了進行實驗,嘗試用默認的任何類路徑(例如任何模型)和標準錯誤的AWS :: Errors ...來替換S3Client,然後運行測試。 – Alexander 2014-10-31 02:29:43

回答

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