title: Testing rate-limited external API calls with VCR and RSpec
body: <p>In my Rails project, I'm using <a href="https://github.com/myronmarston/vcr" rel="nofollow">VCR</a> and RSpec to test HTTP interactions against an external REST web service that only allows calls to it <em>once per second</em>.  </p>
  
  <p>What this means so far is that I end up running my test suite until it fails due to a "number of calls exceeded" error from the web service.  At that stage though, at least some cassettes get recorded, so I just continually run the test suite until eventually I get them all recorded and the suite can run using only cassettes (my <code>default_cassette_options = { record: :new_episodes }</code>).  This doesn't seem like an optimal way to do things, especially if I find I need to re-record my cassettes in the future often, and I worry that constant calls could land me on a blacklist with the web service (there's no test server they have that I know about).</p>
  
  <p>So, I ended up trying putting calls to <code>sleep(1)</code> in my Rspec <code>it</code> blocks directly before the call to the web service is made, and then refactored those calls up into the VCR configuration:</p>
  
  <p><strong>spec/support/vcr.rb</strong></p>
  
  <pre><code>VCR.configure do |c|
    # ...
    c.after_http_request do |request, response|
      sleep(1)
    end
  end
  </code></pre>
  
  <p>Although this seems to work fine, is there a better way to do this?  At the moment, if a call to an external service that doesn't have a cassette already is the final test in the suite, then the suite sleeps unnecessarily for 1 second.  Likewise, if the time between 2 web service calls without cassettes in the test suite is more than once second, then there's another unnecessary pause.  Has anyone made any kind of logic to test for these kinds of conditions, or is there a way to elegantly do this in the VCR configuration?</p>