Testing Carrierwave with Fog for Amazon S3
Filed under: mocking, rails, rspec, carrierwave, fog, s3
Testing file upload using CarrierWave with Fog with S3 turns out to be difficult.
- CarrierWave/Fog need a non-empty file, otherwise the url to the S3 object will be nil and can’t be tested.
- Fog.mock! doesn’t work out of box. Some extra steps are needed to avoid uploading files to S3 when running tests.
First, create config/fog_credentials.yml
Next, put this to your config/initializers/carrier_wave.rb
Next, put this into spec/support/fog_helper.rb
Note, the :key value must match whats defined for fog_dir (dev-bucket) in carrier_wave.rb
Suppose you want to test this class:
Your rspec test can be something like this:
Now the test is complete. It uses fakefs to generate a fake file which is non-empty. Fog will pretent to upload the file
using the FileUploader under test. The upload url is the subject under test.