Skip to content

Instantly share code, notes, and snippets.

@burgalon
Last active September 25, 2020 15:34
Show Gist options
  • Save burgalon/e1e95c26f6e1bd762909 to your computer and use it in GitHub Desktop.
Save burgalon/e1e95c26f6e1bd762909 to your computer and use it in GitHub Desktop.
Testing client side app (like BackboneJS) with Capybara, VCR, webmock, factory girl
Testing client side app (like BackboneJS) with Capybara, VCR, webmock, factory girl
Capybara.register_driver :selenium_chrome do |app|
Capybara::Selenium::Driver.new app, browser: :chrome
end
Capybara.default_driver = :selenium_chrome
Capybara.app = SinatraProxy.new
# Grunt/Gulp server
Capybara.app_host = 'http://localhost:9000'
Capybara.default_wait_time = 8
source 'https://rubygems.org'
gem 'rspec'
gem 'capybara'
gem 'selenium-webdriver'
gem 'chromedriver-helper'
gem 'vcr'
gem 'webmock'
gem 'sinatra'
gem 'sinatra-contrib'
gem 'factory_girl'
require 'sinatra'
require "sinatra/reloader" if development?
require 'net/http'
HEADERS_NOT_TO_PROXY = %w(transfer-encoding)
HOST = 'localhost'
PORT = 9000
class SinatraProxy < Sinatra::Base
configure :development do
register Sinatra::Reloader
end
def request_headers
request.env.select {|k,v| k.start_with? 'HTTP_'}
.collect {|pair| [pair[0].sub(/^HTTP_/, ''), pair[1]]}
.to_h # Ruby 2.1
.merge('CONTENT-TYPE' => request.env['CONTENT_TYPE'] || 'application/json')
end
proxy = lambda do
# puts "REQUEST HEADERS #{request_headers}"
uri = URI.parse(request.url)
http = Net::HTTP.new(HOST, PORT)
response = http.send_request(
request.request_method.upcase,
uri.request_uri,
request.body.read,
request_headers)
response_headers = {}
response.to_hash.each{|k,v| response_headers[k]=v.join unless HEADERS_NOT_TO_PROXY.include?(k) }
# puts "RESPONSE HEADERS #{response_headers}"
status response.code
headers response_headers
headers 'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Headers' => 'Authorization,X-Requested-With'
body response.body
end
get '/*', &proxy
post '/*', &proxy
patch '/*', &proxy
put '/*', &proxy
delete '/*', &proxy
options "*" do
headers 'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Headers' => 'Authorization,Content-Type,X-Requested-With',
'Access-Control-Allow-Methods' => 'HEAD,GET,PUT,DELETE,OPTIONS'
halt 200
end
end
...
RSpec.configure do |config|
config.before :all do
VCR.use_cassette 'load' do
visit "/?origin=http://#{Capybara.current_session.server.host}:#{Capybara.current_session.server.port}"
# Used to wait for the page to have loaded
expect(page).to have_css '.SOME-CONTENT'
# Disable refreshing after each test
page.instance_variable_set(:@touched, false)
end
end
end
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment