Search code examples
ruby-on-rails-3cucumberdelayed-jobwebmockvcr

Test response of Rails 3 background job (API-Request) with VCR in Cucumber feature


I have a Rails 3 background job (delayed_job) which sends a hipchat / Campfire message to their API and I want to check the response in my Cucumber feature. Is there a way to get the last HTTP response(s) which VCR have recorded?

The feature looks like this

    @vcr
    Scenario: Send hipchat message when task created
      Given an hipchat_sample integration exists with app: app "teamway"
      When I create an "ActionMailer::Error" task to "Teamway"
      And all jobs are worked off # invoke Delayed::Worker.new.work_off
      Then a hipchat message should be sent "ActionMailer::Error"

In my step definition I want to check the response body:

    Then /^a hipchat message should be sent "(.*?)"$/ do |arg1|
      # Like this:
      # VCR::Response.body.should == arg1
    end

VCR already records the request and response, but I do not know how to take them. I think of something similar to catching the emails sent with Pickle's steps. Does anybody have an idea how to do this?

I use rails 3.2.8, cucumber-rails 1.3 and vcr 2.2.4 (with webmock).

Best regards Torsten


Solution

  • You can use VCR.current_cassette to get the current cassette, and then interrogate that to get the [VCR::HTTPInteraction][1] object you're looking for, but it'll be a bit complex--the VCR cassette stores the newly recorded HTTP interactions separately from the ones it has available for playback and from the ones it has already played back...so you'll need some complex conditionals to ensure things work properly both when your tests are recording and when they are playing back.

    Instead, I recommend you use an after_http_request hook:

    module HipmunkHelpers
      extend self
      attr_accessor :last_http_response
    end
    
    Before { HipmunkHelpers.last_http_response = nil }
    
    VCR.configure do |c|
      c.after_http_request(lambda { |req| URI(req.uri).host == 'hipmunk.com' }) do |request, response|
        HipmunkHelpers.last_http_response = response
      end
    end
    

    Then, in your cucumber step, you can access HipmunkHelpers.last_http_response.

    For more details on the after_http_request hook, check out the relish docs.