Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@balvig
Copy link

@balvig balvig commented Jun 2, 2025

What

This allows saving and retrieving extra metadata using VCR::Cassette#metadata.

Its purpose is similar to that of VCR::Cassette#originally_recorded_at in storing and setting up state from the time of recording when replaying cassettes.

Why

The specific use case I had was related to writing tests against an API that required a unique email for every test run:

def setup
  VCR.insert_cassette("example")
end

def teardown
  VCR.eject_cassette
end

def create_user
  make_http_request("/users", email: "[email protected]")
end

test "First time works" do
  create_user # Works first time
end

test "Second time doesn't" do
  create_user #  => Error: Email has already been taken
end

I solved this by generating a unique postfix every time a test was run, something like this:

def create_user
  make_http_request("/users", email: "user+#{@email_postfix}@example.com")
end

def setup
  @user_email_postfix = SecureRandom.uuid
  cassette = VCR.insert_cassette("example")
  if cassette.recording?
    cassette.metadata["email_postfix"] = @email_postfix # store generated postfix when recording
  else
    @email_postfix = cassette.metadata["email_postfix"] # set postfix from metadata when replaying
  end
end

def teardown
  VCR.eject_cassette
end

test "First time works" do
  create_user # => Created [email protected]
end

test "Second time also works" do
  create_user # => Created [email protected]
end

To replay these tests with the original postfix, I needed a way to store the postfix that was in effect at the time of recording.

Anything else

Please let me know if I'm overlooking a more effective way to achieve this!
And thank you for creating VCR, it's been a massive help in my work. 🙂

@balvig balvig marked this pull request as ready for review June 2, 2025 08:09
Copy link
Member

@olleolleolle olleolleolle left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An interesting proposal!

balvig and others added 2 commits June 9, 2025 08:44
Co-authored-by: Olle Jonsson <[email protected]>
Co-authored-by: Olle Jonsson <[email protected]>
@balvig balvig requested a review from olleolleolle June 8, 2025 23:48
@balvig
Copy link
Author

balvig commented Jun 8, 2025

Thank you for the suggestions @olleolleolle! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants