denolfe
6/18/2013 - 2:42 PM

Mechanize, Webmock and VCR example

Mechanize, Webmock and VCR example

#!/usr/bin/env ruby

require 'mechanize'
require 'webmock'
require 'vcr'

username = 'someone@somewhere.com'
password = 'ReallyGoodPassword!'

# There exists an incompatibility between WebMock and net-http-persistent
# this hack works around that incompatibility. See link for more info.
# https://github.com/bblimke/webmock#connecting-on-nethttpstart
WebMock.allow_net_connect!(:net_http_connect_on_start => true)

VCR.configure do |c|
  c.cassette_library_dir = 'spec/cassettes'
  c.hook_into :webmock
  c.filter_sensitive_data('<USERNAME>') { username }
  c.filter_sensitive_data('<USERNAME>') { CGI::escape(username) }
  c.filter_sensitive_data('<PASSWORD>') { password }
  c.filter_sensitive_data('<PASSWORD>') { CGI::escape(password) }
end

auth_uri = 'https://domain.com'
block_uri = 'https://domain.com/feed'

agent = Mechanize.new do |a|
  a.verify_mode = OpenSSL::SSL::VERIFY_NONE
end

VCR.use_cassette('feed', record: :all, match_requests_on: [:method, :uri, :body]) do
  agent.get(auth_uri) do |page|
    page.form_with(action: /user/) do |form|
      form.field_with(name: /name/).value = username
      form.field_with(name: /pass/).value = password
      form.click_button
    end
  end

  feed_page = agent.get(block_uri)
  feed_str = feed_page.body.to_s.encode('US-ASCII')
end