Using VCR with RSpec to Record External HTTP Requests

Sdílet
Vložit
  • čas přidán 19. 05. 2024
  • When your Ruby code makes network requests to external APIs, it can lead to tricky scenarios in your test suite. You likely don't want to make actual HTTP requests because they may fail due to a variety of reasons like CI not supporting external network requests or due to rate limiting. Network requests are generally slow compared to loading data from files. Plus, you want your tests to be deterministic and reliable. If the response from the API returns an error due to rate limiting, you wouldn't want your entire test suite to fail.
    Enter VCR. A tool for recording your network requests and saving them as YAML files. It has a simple interface and the ability to work automatically with some Ruby test frameworks.
    In this episode I go over building out a simple app in Ruby using Sinatra to fetch the Studio Ghibli films from ghibliapi.herokuapp.com/, return a subset of the data, and sort it. I configure VCR to record that request. From there, I show how one could unit test the HTTP request so that there are both end-to-end and unit tests for this simple scenario.
    I'll follow this episode up with one on using just Webmock since it's my preferred way of working!
    View the source from this episode: github.com/brettchalupa/scree...
    API used in the episode: ghibliapi.herokuapp.com/
    Blog post I found during the episode: fabioperrella.github.io/10_ti...
    VCR docs: github.com/vcr/vcr#vcr
    Versions used in this screencast:
    - Ruby 2.7.3
    - RSpec 3.10.0
    - Sinatra 2.1.0
    - VCR 6.0.0
    - Webmock 3.13.0
    Chapters:
    00:00 - Intro
    01:41 - Setting up the simple app
    12:00 - Adding & using VCR
    20:48 - Unit testing network requests
    27:46 - Closing thoughts
    Support my screencasts by buying me a coffee: www.buymeacoffee.com/brettcha...
  • Věda a technologie

Komentáře • 4

  • @JuanVqz
    @JuanVqz Před 2 lety

    Cool! I personally feel like we tested the same in two places, is this usually what we should do? or it was just in terms of teaching how to test an HTTP call in end-to-end and unit-test?
    Great video! thank you

    • @brettcodes
      @brettcodes  Před 2 lety +1

      Thanks for the kind words! I think it depends really... In a more complex example, there may be value in have an end-to-end test that exercises the whole system but then having some unit tests to cover edge cases and alternate paths through the code. It ultimately comes down to what feels right or what your team prefers-as in how much confidence you have with the tests and ensuring the different paths are covered!

  • @al-mokhtar_
    @al-mokhtar_ Před 2 lety +1

    man thank you so much