Skip to content

Testing with VCR

Dani Donisa edited this page Jan 11, 2024 · 11 revisions

In our CI environment, we don't want to run the OBS backend and therefore we are using VCR to replay previously recorded HTTP sessions between OBS frontend and OBS backend.

Backend::Api Configuration

  • In the test environment HTTP requests to the OBS backend are disabled by default
  • You can enable requests to the OBS backend by setting the environment variable GLOBAL_WRITE_THROUGH=true before running your spec
    GLOBAL_WRITE_THROUGH=true rspec spec/models/workflow_spec.rb
    

VCR configuration

VCR:

  • is disabled by default

  • can be enabled/disabled per example group (describe/context) or individual example with

      RSpec.describe Package, :vcr do
        context 'blah', vcr: false do
          ...
          it 'blubb', :vcr do
          end
        end
      end
    
  • will replay previously recorded HTTP sessions from cassette files

  • record new HTTP sessions if there is no cassette file

  • cause an error to be raised for new requests if there is a cassette file

  • compare the requested URL with the URL (request.uri) from cassette files. So if some part of the URL you request is random (like a Project.name string from Faker) it will be considered a new request every time you run the spec and it will fail.

  • VCR cassettes should NEVER be edited manually

Recording

New Cassette

If you have vcr enabled for an example/example group just run your spec and new cassettes will be created.

New Request to an existing Cassette

Set default_cassette_options to :new_episodes instead of :once, then enable vcr: true in the spec file and run:

GLOBAL_WRITE_THROUGH=true rspec spec/models/workflow_spec.rb

Re-Record Cassette

  • To re-record an example, remove the yml file that is called like your example from spec/cassettes
  • To re-record an example group, remove the directory called like it from spec/cassettes

Flushing the backend

In the process, of developing tests with cassettes, the backend doesn't get flushed between test runs. If cassettes are recorded without flushing the backend, they will contain responses from a backend filled up with previous data.

So, for example, when in your test you use a factory to create a package package1 with a file and run the test, a package with a file is created in the backend. If you modify the test to create a simple package package1 without a file, and run the test, the backend will keep the file attached to this package. And the rest of the code of your test will work as it was the first run, when it probably shouldn't.

To assure this doesn't happen when creating the cassettes, just delete the docker backend container, and wake up it again. This can be done with the following commands:

docker compose rm -s -f backend
docker compose up -d backend
Clone this wiki locally