Module: Bearcat::SpecHelpers

Extended by:
ActiveSupport::Concern
Defined in:
lib/bearcat/spec_helpers.rb

Overview

Bearcat RSpec Helpers Can be included in your spec_helper.rb file by using:

  • ‘require ’bearcat/spec_helpers’‘

And

  • ‘config.include Bearcat::SpecHelpers`

This helper requires ‘gem ’method_source’‘ in your test group

Constant Summary collapse

SOURCE_REGEX =
/(?<method>get|post|delete|put)\((?<quote>\\?('|"))(?<url>.*)\k<quote>/

Instance Method Summary collapse

Instance Method Details

#stub_bearcat(endpoint, prefix: nil, method: :auto, **kwargs) ⇒ Object

Helper method to Stub Bearcat requests. Automagically parses the Bearcat method source to determine the correct URL to stub. Accepts optional keyword parameters to interpolate specific values into the URL. Returns a mostly-normal Webmock stub (:to_return has been overridden to allow :body to be set to a Hash)



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/bearcat/spec_helpers.rb', line 18

def stub_bearcat(endpoint, prefix: nil, method: :auto, **kwargs)
  url = case endpoint
  when Symbol
    ruby_method = Bearcat::Client.instance_method(endpoint)
    match = SOURCE_REGEX.match(ruby_method.source)
    bits = []
    url = match[:url].gsub(/\/$/, '')
    lend = 0
    url.scan(/#\{(?<key>.*?)\}/) do |key|
      m = Regexp.last_match
      between = url[lend..m.begin(0)-1]
      bits << between if between.present? && (m.begin(0) > lend)
      lend = m.end(0)
      bits << (kwargs[m[:key].to_sym] || /\w+/)
    end
    between = url[lend..-1]
    bits << between if between.present?

    bits.map do |bit|
      next bit.source if bit.is_a?(Regexp)
      bit = bit.canvas_id if bit.respond_to?(:canvas_id)
      Regexp.escape(bit.to_s)
    end.join
  when String
    Regexp.escape(endpoint)
  when Regexp
    endpoint.source
  end

  url = Regexp.escape(resolve_prefix(prefix)) + url
  stub = stub_request(method == :auto ? (match ? match[:method].to_sym : :get) : method, Regexp.new(url))

  # Override the to_return method to accept a Hash as body:
  stub.define_singleton_method(:to_return, ->(*resps, &blk) {
    if blk
      super do |*args|
        resp = blk.call(*args)
        resp[:headers] ||= {}
        resp[:headers]["Content-Type"] ||= "application/json"
        resp[:body] = resp[:body].to_json
        resp
      end
    else
      resps.map do |resp|
        resp[:headers] ||= {}
        resp[:headers]["Content-Type"] ||= "application/json"
        resp[:body] = resp[:body].to_json
      end
      super(*resps)
    end
  })

  stub
end