LoginSignup
4
3

More than 5 years have passed since last update.

vcrでレコーディング時かカセットからの再生かを判断して処理を変える

Last updated at Posted at 2015-02-11

参考: 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|

その他vcr関連TIPS

4
3
0

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
4
3