Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.