参考: How to check if VCR uses the cassette or is recording
ユースケースとしては
- HTTP通信発生時(録画時)のみ処理を加える
- 通信先への負荷を調整 (sleepする)
- リクエストの内容を覗く (ログ出力)
方法はvcrのモンキーパッチかbefore_record
フック
録画時の処理をモンキーパッチする
この方法はHTTP通信発生時(録画時)のみ呼ばれる
まず、ファイルの置き場所に困るが、個人的にはspec配下にsupportというディレクトリを作りそこに置いている
spec_helper.rb, rails_helper.rb から読み込む
spec_helper.rb
Dir[File.join(File.dirname(__FILE__), "support/**/*.rb")].each {|f| require f}
sleep する
vcr_monkey_patch.rb
def VCR.record_http_interaction(interaction)
super
sleep 5
end
リクエストの内容を覗く(ログ出力)
vcr_monkey_patch.rb
def VCR.record_http_interaction(interaction)
super
puts "#{interaction.request.to_hash}"
end
sleepして、URLをログする
def VCR.record_http_interaction(interaction)
super
unless interaction.request.uri =~ /localhost/ || interaction.request.uri =~ /127\.0\.0\.1/
print "#{interaction.request.uri} "
puts "Sleeping..."
sleep 2
end
end
留意点として、Selenium使用時に余計なログが出た
urlのパターンとしては/hub/session/
や__identity__
などがあった
それらのログを無視する場合は特定のパターンでputs
をとばす
puts "..." unless interaction.request.to_hash["uri"] =~ %r{/session}
# OR
puts "..." unless ["/session", "/__identity__"].any?{|pattern| interaction.request.to_hash["uri"] =~ %r{#{pattern}} }
Example of log of Chrome
"uri"=>"http://127.0.0.1:9515/session/a5ac957aabc15a2114f2fefca3165258/element/...
"uri"=>"http://127.0.0.1:9515/session"
"uri"=>"http://127.0.0.1:49378/__identify__"
録画時のフックを使う
VCR.config do |c|
-> c.before_record do |i|