LoginSignup
21
21

More than 3 years have passed since last update.

Paperclip with S3な画像アップロードをRSpec+WebMockな環境でテストする

Last updated at Posted at 2014-02-05

タイトルの通りです。
幾つかやり方はあるみたいですが、自分の環境下(WebMock+RSpecでテスト。Paperclip+S3でファイルアップロード)では

AWS.config(:access_key_id => "TESTKEY", :secret_access_key => "TESTSECRET", :stub_requests => true)
Image.any_instance.stub(:save_attached_files).and_return(true)
@image = fixture_file_upload('/files/test.gif', 'image/gif')

で可能になりました。
追記:この記述はコントローラー向けです。下にモデルでテストを書く時の記述をしています。
テスト用のファイルはspec/fixtures/files/以下に置きます。
Imageは利用しているファイルを所有するモデルです。

後は@imageを適当な所で使えばおkです。

AWSの設定部分が記述されていないと

     WebMock::NetConnectNotAllowedError:
       Real HTTP connections are disabled. Unregistered request: PUT https://...

となってしまいました。

追記

fixture_file_uploadはモデルのテストを行う時利用できませんでした。
ので

stub_request(:get, "http://example.com/image.gif").
  with(:headers => {'Accept'=>'*/*', 'User-Agent'=>'Ruby'}).
  to_return(:status => 200, :body => File.read('spec/fixtures/image.gif'), :headers => {"Content-Type" => 'image/gif'})

webmockの時点でファイルを読みこませればOKです。
その際@image = fixture_file_upload('/files/test.gif', 'image/gif')
の記述は不要です。

21
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
21