class Capyspy::Spy

Attributes

method[R]
page[R]

Public Class Methods

new(page, method) click to toggle source
# File lib/capyspy/spy.rb, line 5
def initialize(page, method)
  @page = page
  @method = method.to_s
  
  init
end

Public Instance Methods

and_call_fake(function) click to toggle source
# File lib/capyspy/spy.rb, line 22
def and_call_fake(function)
  with_spy 'callThrough = false', "fake = #{function}"
  self
end
and_call_through() click to toggle source
# File lib/capyspy/spy.rb, line 12
def and_call_through
  with_spy 'callThrough = true'
  self
end
and_return(value) click to toggle source
# File lib/capyspy/spy.rb, line 17
def and_return(value)
  with_spy 'callThrough = false', "fake = function() { return #{value.to_json}; }"
  self
end
calls() click to toggle source
# File lib/capyspy/spy.rb, line 27
def calls
  with_spy 'calls'
end
to_s() click to toggle source
# File lib/capyspy/spy.rb, line 31
def to_s
  method
end

Private Instance Methods

init() click to toggle source
# File lib/capyspy/spy.rb, line 37
      def init
        page.evaluate_script <<JS
(function() {
  window._capyspy = window._capyspy || {};
  if (!window._capyspy['#{method}']) {
    window._capyspy['#{method}'] = {
      callThrough: false,
      calls: [],
      fake: function() {},
      original: window.#{method}
    };
  
    window.#{method} = function() {
      var spy = window._capyspy['#{method}'];
      spy.calls.push(Array.prototype.slice.call(arguments, 0));
      if (spy.callThrough) {
        return spy.original.apply(this, arguments);
      } else {
        return spy.fake.apply(this, arguments);
      }
    }
  }
})();
JS
      end
with_spy(*expressions) click to toggle source
# File lib/capyspy/spy.rb, line 63
def with_spy(*expressions)
  raise ArgumentError if expressions.empty?
  expressions.each do |expression|
    page.evaluate_script "window._capyspy['#{method}'].#{expression};"
  end
end