VCRで外部APIとのやりとりを記録する (original) (raw)
Go to list of users who liked
46
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.
Railsなどでtestを書く場合、外部APIとのやりとりのあるテストは書きにくい。スピード的にも毎回外部APIにアクセスさせることは避けたい。
VCRを使うとHTTPのリクエストとレスポンスをYAMLファイルに保存してくれ、次回のテスト時にはそのリスクエスト結果が再現される
記録するYAMLが吐かれるディレクトリをtest/vcr_cassettesとすると下記のようにtest_helperで設定する
test/test_helper.rb
VCR.configure do |c|
c.cassette_library_dir = 'test/vcr_cassettes'
c.allow_http_connections_when_no_cassette = true #VCRブロック外のHTTP通信は許可する
c.hook_into :webmock # or :fakeweb
end
testファイルにて外部アクセスが走る処理のところをVCR.use_cassetteブロックで囲む。
例えば検索APIにアクセスするメソッドがあったとすると下記のようになる
test/unit/search_test.rb
test "search query" do
VCR.use_cassette('search_query',:record => :new_episodes) do
# このブロックで発生するHTTPリスエスト/レスポンスが記録され、次回以降は再生される
@s = Search.query("foobar")
end
assert_equal "foorbar",@s.keyword
end
初回実行時に test/vcr_cassettes/search_query.yml が生成され、次回以降はその内容が再現される。
外部APIの結果をキープしておいて、それをもとにメソッドを追加していくような時に有用である。
Go to list of users who liked
46
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
What you can do with signing up
Go to list of users who liked
46
Deleted articles cannot be recovered.
Draft of this article would be also deleted.
Are you sure you want to delete this article?