Ruby API Testing With VCR

The days of isolated websites and apps are over. Applications interact with one another through APIs to access each others specialization. You should write a Ruby GEM for the task. But how are you going to mock API calls. Answer is vcr will and you don’t!

A simple example would be as follows. The API is written using HTTParty but should work with any thing…

it "fetches price trends" do
  VCR.use_cassette "zumper/san-frasisco-ca/lower-haight" do
    price_trends = Zumper::API.get_price_trends(
      city: "san-frasisco",
      neighborhood: "lower-haight",
    )
    # do some thing with price_trends
  end
end

Here, on your first call, the response will be recorded by you VCR in to a file. This file will be used to replay the API call making it fast and deterministic.

If you are wondering why…

I was asked what if the API changes…

Firstly and most importantly, APIs shouldn’t implement breaking changes. End points need to be thoroughly tested and changes shouldn’t break tests. Breaking changes can come from a new version ex: v1 -> v2. But it is not under your control.

Secondly, vcr is for you when developing, so the tests run faster. I normally have a VPS that momentarily deletes vcr cassettes and run tests again.

I am out! Happy & snappy testing!