5

I'm using VCR with RSpec to unit test a section of API code, and I've hit a small challenge.

My client code uses sleep to rate limit API requests. Thanks to this elegant solution, I can now intercept the sleep message with a stub from my unit tests:

expect(subject).to receive(:sleep)

The problem is that while I'm developing this code, I've got to delete my cassettes frequently, but since I've stubbed sleep, there's no rate limit on the real API requests and the spec blows up.

What [I think] I want to do is something like the following:

expect(subject).to receive(:sleep) if !vcr.real_request?

So that I don't interfere with the subjects sleep when I'm recording a cassette.

I see interesting related discussion, but it seems like a different case and I don't see how I can leverage it directly. However, that did lead me to discover VCR hooks (esp. before_playback) but it's not clear to me how I would export subject into the scope of the block, or else proxy block execution into the scope of my test to make the stub.

Any thoughts?

NB: I'm using the config.configure_rspec_metadata! feature in my spec_helper.rb to automatically capture/name my cassettes, if that makes any difference (i.e. I'm not wrapping each individual API method explicitly in its own VCR block).

1 Answer 1

12

It turns out that this is possible without any trickery.

According to this Google Groups thread:

You can use VCR.http_stubbing_adapter.http_connections_allowed?

However (as the author explained) this method isn't publicly documented, and (as the author accurately predicted) is not available in the 2.x codeline. However, this did cause me to review the VCR source directly out of a mixture of curiosity and desperation. I found the following in lib/vcr.rb:294:

  def real_http_connections_allowed?
    return current_cassette.recording? if current_cassette
    !!(configuration.allow_http_connections_when_no_cassette? || @turned_off)
  end

Since current_cassette.recording? is publicly accessible, it does exactly what I need without any hacking:

expect(subject).to receive(:sleep) if !VCR.current_cassette.recording?
1
  • 2
    I'm using VCR 2.9.3 and VCR::Cassette.recording? only really works if the record_mode is :once.
    – pduey
    Mar 31, 2015 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.