Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ENV["TEST"] = "1"
- ENV["JETS_ENV"] ||= "test"
- # Ensures aws api never called. Fixture home folder does not contain ~/.aws/credentails
- ENV['HOME'] = "spec/fixtures/home"
- require "byebug"
- require "fileutils"
- require "jets"
- require "uri"
- abort("The Jets environment is running in production mode!") if Jets.env == "production"
- Jets.boot
- require 'capybara/rspec'
- Capybara.app = Jets.application
- # Capybara.current_driver = :selenium
- # Capybara.app_host = 'http://localhost:8888'
- module Helpers
- def payload(name)
- JSON.load(IO.read("spec/fixtures/payloads/#{name}.json"))
- end
- def post(path, **params)
- http_call(method: :post, path: path, **params)
- end
- def get(path, **params)
- http_call(method: :get, path: path, **params)
- end
- Response = Struct.new(:status, :body)
- def http_call(method:, path:, **params)
- json = JSON.load(IO.read("spec/fixtures/payloads/posts-index.json"))
- id_params = path.scan(%r{:([^/]+)}).flatten
- expanded_path = path.dup
- path_parameters = {}
- id_params.each do |id_param|
- raise "missing param: :#{id_param}" unless params.include? id_param.to_sym
- expanded_path.gsub!(":#{id_param}", params[id_param.to_sym])
- path_parameters = { id_param => params[id_param.to_sym] }
- end
- json['resource'] = path
- json['path'] = expanded_path
- json['httpMethod'] = method.to_s.upcase
- json['pathParameters'] = path_parameters
- if method != :get
- json['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
- json['body'] = params.to_a.map { |e| "#{URI.encode(e[0].to_s)}=#{URI.encode(e[1].to_s)}" }.join('&')
- end
- route = find_route(path, method.to_sym)
- controller = Object.const_get(route.controller_name).new(json, {}, route.action_name)
- response = controller.dispatch!
- unless response.is_a? Array
- raise "Expected response to be an array. Are you rendering correctly?"
- end
- if response.size != 3
- raise "Expected response to be an array of size 3. Are you rendering correctly?"
- end
- @_response = Response.new(response[0].to_i, response[2].read)
- end
- def response
- @_response
- end
- def find_route(path, method)
- path = path[0..-2] if path.end_with? '/'
- path = path[1..-1] if path.start_with? '/'
- route = Jets::Router.routes.find { |r| r.path == path && r.method == method.to_s.upcase }
- raise "Route not found: #{method.to_s.upcase} #{path}" if route.blank?
- route
- end
- def json(str)
- JSON.parse(str, symbolize_names: true)
- end
- end
- RSpec.configure do |c|
- c.include Helpers
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement