Last active
November 9, 2021 13:49
-
-
Save tombh/b45e86788620435adc5a to your computer and use it in GitHub Desktop.
Use .env file to filter sensitive data from VCR cassettes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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
no probs 😁 wow, that must be like 10 years old now