Skip to content

Instantly share code, notes, and snippets.

@tombh
Last active November 9, 2021 13:49
Show Gist options
  • Save tombh/b45e86788620435adc5a to your computer and use it in GitHub Desktop.
Save tombh/b45e86788620435adc5a to your computer and use it in GitHub Desktop.
Use .env file to filter sensitive data from VCR cassettes
# Assuming that you're using .env to store your sensitive app credentials, then you can
# use VCR's `filter_sensitive_data` method to convert occurrences of those credentials
# to `<%= ENV['#{key}'] %>` in your recorded VCR cassettes.
require 'vcr'
# Use the .env file to compile the list of sensitive data that should not be recorded in
# cassettes
def sensitive_strings
contents = File.read "#{Rails.root}/.env"
words = contents.split(/\s+/)
# Only interested in words with an '=' in them
words.reject! { |w| !w.include? '=' }
# Create a list of key/value pairs
words.map! { |w| w.split('=') }
# Turn the key/value pairs into an actual hash
Hash[words]
end
VCR.configure do |c|
c.hook_into :webmock
c.cassette_library_dir = 'spec/cassettes'
c.configure_rspec_metadata!
# Filter out sensitive data and replace with ERB interpolation
sensitive_strings.each do |key, sensitive_string|
# NB: intentionally not interpolating ENV[] as #{ENV[]}. We actually *want* '<%= ENV[*] %>' to
# appear in VCR's ERB-enabled YML files
manifestations = {
CGI.escape(sensitive_string) => "<%= CGI.escape ENV['#{key}'] %>",
sensitive_string => "<%= ENV['#{key}'] %>"
}
manifestations.each_pair do |string, replacement|
c.filter_sensitive_data(replacement) { string }
end
end
# You must set ERB-enabled cassettes
c.default_cassette_options = { record: :new_episodes, erb: :true }
end
@guilhermeteodoro
Copy link

thanks so much for this!

@tombh
Copy link
Author

tombh commented Nov 9, 2021

no probs 😁 wow, that must be like 10 years old now

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