FactoryGirl, WebMock, VCR, Fog and CarrierWave

In the interest of fast suite runs (amongst other reasons) you want to make sure that your specs are not dependent on remote servers as they do their thing. One of the more popular ways of achieving this noble aim is by using a gem called WebMock, a library for stubbing and setting expectations on HTTP requests in Ruby.

The first time you use WebMock, code that calls external servers will break.

WebMock::NetConnectNotAllowedError:
       Real HTTP connections are disabled. Unregistered request: GET https://nueprops.s3.amazonaws.com/test...

       You can stub this request with the following snippet:

       stub_request(:get, "https://nueprops.s3.amazonaws.com...

Now maintaining that stub code is often painful, so you probably want to use a gem called VCR to automate the process. VCR works really well. After instrumenting your spec correctly, you run it once to generate a cassette, which is basically a YAML file that captures the HTTP interaction(s) of your spec with the external servers. Subsequent test runs use the cassette file instead of issuing real network calls.

Creation and maintenance of cassettes that mock interaction with JSON-based web services is easy. Services that talk binary? Not so much. And almost every modern Rails project I've ever worked on uses CarrierWave (or Paperclip) to handle uploads to AWS. If you try to use VCR on those requests, you're in for a world of annoyance.

Enter Fog, the cloud-abstraction library that undergirds those uploader's interactions with AWS S3. It has a somewhat poorly documented, yet useful mock mode. Using this mode, I was able to make WebMock stop complaining about CarrierWave trying to upload fixture files to S3.

However, the GET requests generated in my specs were still failing. Given that I'm using the venerable FactoryGirl gem to generate my test data, I was able to eventually move the stub_request calls out of my spec and into a better abstraction level.

factory :standard_star do
  sequence(:name) { |n| "Cat Wrangler #{n}" }
  description "Excellence in project management of ADD people"
  icon { Rack::Test::UploadedFile.new('spec/support/stars/cat-wrangler.jpg') }
  image { Rack::Test::UploadedFile.new('spec/support/stars/cat-wrangler.jpg') }
  after(:create) do |s, e|
    WebMock.stub_request(:get, "https://nueprops.s3.amazonaws.com/test/uploads/standard_star/image/#{s.name.parameterize}/cat-wrangler.jpg").
             to_return(:status => 200, :body => s.image.file.read)

    WebMock.stub_request(:get, "https://nueprops.s3.amazonaws.com/test/uploads/standard_star/icon/#{s.name.parameterize}/cat-wrangler.jpg").
             to_return(:status => 200, :body => s.icon.file.read)

  end
end