1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VCRで環境変数を扱いたい場合

Last updated at Posted at 2018-12-20

はじめに

VCRで環境変数を使いたいときにハマったので残しておきます。
なお、VCRなどの詳しい使い方については省きますのでご了承ください。
それと初投稿なので、記事の書き方も含めご指摘等ありましたらお願いします!!

環境

・ruby 2.5.1
・Rails 5.2.2
・VCR
・webmock

事前準備

今回使用するgem。

Gemfile
  gem 'vcr'
  gem 'webmock'

使いたい環境変数を追加。

~/.bash_profile
export API_KEY='VALUE'

本題

まずは、VCRで記録するための設定を追加します。

spec/spec_helper.rb
VCR.configure do |c|
    c.cassette_library_dir = 'spec/vcr_cassettes'
    c.allow_http_connections_when_no_cassette = true
    c.hook_into :webmock 
    c.filter_sensitive_data('<API_KEY>') { ENV['API_KEY'] } #ここで環境変数を設定します
end

この状態で何らかのAPIを叩いてください。

spec/sample_spec.rb
VCR.use_cassette("sample") do
    # ここでgetなりpostなりしてください
end

すると、下記のようなファイルが作られてると思います。仮にAPIを叩くときにAPIキーを含んだURLになっていた場合、下記のファイルにAPIキーが含まれてしまうため、この状態でgithubにアップロードするのは危険です。(レスポンスだけではなく、リクエスト時のデータも記録されてる)

spec/vcr_cassettes/sample.yml
---
http_interactions:
- request:
    method: get # or post
    uri: http://XXXXXX=VALUE  #ここにAPIキーが含まれる
...

end

そこでAPIキーを直接取得するのではなく、
環境変数経由で取得するように置き換えます。

spec/vcr_cassettes/sample.yml
---
http_interactions:
- request:
    method: get # or post
    uri: http://XXXXXX=<API_KEY> #APIキーを環境変数経由で取得
...

end

これでAPIキーがgithub上に晒されてしまうのを防ぐことができます。

参考

https://stackoverflow.com/questions/9042726/testing-a-web-api-using-rspec-and-vcr
[https://relishapp.com/vcr/vcr/docs/configuration/filter-sensitive-data]
(https://relishapp.com/vcr/vcr/docs/configuration/filter-sensitive-data)

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?