carrierwave

Mocking Fog with CarrierWave and Minitest

I kept getting the  error

Expected(200) <=> Actual(404 Not Found)

while trying to use Fog.mock! in unit tests.  I followed the guidelines in Fog and Carrierwave, but no luck.  Here’s the trick:  Fog uses credentials to segregate mock data, so be sure the controllers and tests are using the same credentials.

Final setup:

carrierwave.rb

CarrierWave.configure do |config|
  s3_config = YAML::load(File.read(Rails.root.join('config','s3.yml')))[Rails.env]

  config.fog_credentials = {
    :provider => 'AWS',
    :aws_access_key_id => s3_config['access_key_id'],
    :aws_secret_access_key => s3_config['secret_access_key'],
  }
  config.fog_directory = s3_config['bucket_name']
  config.fog_public = false
  config.fog_authenticated_url_expiration = 1800 # (in seconds) => 30 minutes

  if Rails.env.test?
    config.enable_processing = false
  end
end

s3.yml

test:
  bucket_name: testbucket
  access_key_id: secretkeyid
  secret_access_key: secretaccesskey

test_helper.rb

Fog.mock!
service = Fog::Storage.new({
  :provider                 => 'AWS',
  :aws_access_key_id        => 'secretkeyid',
  :aws_secret_access_key    => 'secretaccesskey'
})
service.directories.create(:key => 'testbucket')

Helpful links:

Version Info:

  • Rails 4.2.6, Ruby 2.2.4
  • carrierwave 0.11.0
  • fog 1.38.0
  • fog-aws 0.9.2