ReqVCR.Test (ReqVCR v0.1.0)

View Source

ReqVCR testing conveniences.

This module provides utilities to mock HTTP requests and responses using VCR tapes. It integrates with Req.Test to allow recording and replaying HTTP interactions.

Usage

Recording a VCR Tape

To record a VCR tape, you need to set the :vcr option with :mode set to :record and specify a :tape_name. This will record the HTTP interaction to the specified tape.

opts = [vcr: [mode: :record, tape_name: "example-tape.json"]]
{:ok, response} = vcr_request("https://example.com", opts)
assert %{action: :record, recorded: true} = Req.Response.get_private(response, :vcr)

Replaying a VCR Tape

To replay a VCR tape, you can use the plug_vcr_replay/1 function. This function sets up a mock that will respond with the recorded interaction from the specified tape.

opts = [
  plug: plug_vcr_replay("example-tape.json"),
  vcr: [mode: :record, tape_name: "example-tape.json"]
]
{:ok, response} = vcr_request("https://example.com", opts)
assert %{action: :replay, source: :mock} = Req.Response.get_private(response, :vcr)

Replaying Multiple VCR Tapes

You can also replay multiple VCR tapes sequentially by passing a list of tape names to plug_vcr_replay/1.

vcr_configs = [
  {"https://example.com/endpoint1", "tape1.json"},
  {"https://example.com/endpoint2", "tape2.json"}
]

plug_vcr_replays =
  vcr_configs
  |> Enum.map(&elem(&1, 1))
  |> plug_vcr_replay()

for {endpoint, tape_name} <- vcr_configs do
  opts = [
    plug: plug_vcr_replays,
    vcr: [mode: :record, tape_name: tape_name]
  ]
  {:ok, response} = vcr_request(endpoint, opts)
  assert %{action: :replay, source: :mock} == Req.Response.get_private(response, :vcr)
end

Summary

Functions

plug_vcr_replay(tape, response_type \\ :json, mock \\ HTTPClientMock)

Replays a VCR tape as a Req.Test plug mock.

Responses can be :json, :text or :html as Req.Test would respond, and the mock used is HTTPClientMock by default.

  • tape: The name of the VCR tape or a list of VCR tape names to replay.
  • response_type: The type of response (:json, :text, or :html).
  • mock: The mock to use (defaults to HTTPClientMock).

with_vcr_tape(tape_name, fun)

(macro)

with_vcr_tape(tape_name, vcr_opts, fun)

(macro)

Convenience macro to run a function with a VCR tape.

This macro is useful for running a block of code with a VCR tape. It takes a tape_name and an optional list of VCR options.