Module: PercyCapybara

Defined in:
lib/percy/version.rb,
lib/percy/capybara.rb

Constant Summary collapse

VERSION =
'5.0.1.pre.3'.freeze
PERCY_DEBUG =
ENV['PERCY_LOGLEVEL'] == 'debug'
PERCY_SERVER_ADDRESS =
ENV['PERCY_SERVER_ADDRESS'] || 'http://localhost:5338'
PERCY_LABEL =
"[\u001b[35m" + (PERCY_DEBUG ? 'percy:capybara' : 'percy') + "\u001b[39m]"

Instance Method Summary collapse

Instance Method Details

#percy_snapshot(name, options = {}) ⇒ Object

Take a DOM snapshot and post it to the snapshot endpoint



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
72
73
74
75
76
77
78
79
80
# File 'lib/percy/capybara.rb', line 25

def percy_snapshot(name, options = {})
  return unless percy_enabled?

  page = Capybara.current_session

  begin
    percy_dom_script = fetch_percy_dom
    page.evaluate_script(percy_dom_script)
    dom_snapshot = get_serialized_dom(page, options, percy_dom_script)
    page.evaluate_script(fetch_percy_dom)

    # Readiness gate -- runs before serialize when CLI supports it.
    # Uses evaluate_async_script with a callback signal so the SDK can block
    # on PercyDOM.waitForReady. In-browser typeof guard makes this a no-op on
    # older CLIs that lack waitForReady.
    readiness_diagnostics = wait_for_ready(page, options)

    # Merge .percy.yml config options with snapshot options (snapshot options take priority).
    # Deep merge with consistent string keys at all levels: nested Hashes merge
    # recursively, per-call wins at leaves, arrays/scalars replace.
    config_options = @cli_config&.dig('snapshot') || {}
    merged_options = deep_merge_options(config_options, deep_stringify(options))

    dom_snapshot = page
      .evaluate_script("(function() { return PercyDOM.serialize(#{merged_options.to_json}) })()")

    if readiness_diagnostics && dom_snapshot.is_a?(Hash)
      dom_snapshot['readiness_diagnostics'] = readiness_diagnostics
    end

    response = fetch('percy/snapshot',
      name: name,
      url: page.current_url,
      dom_snapshot: dom_snapshot,
      client_info: CLIENT_INFO,
      environment_info: ENV_INFO,
      **options,)

    data =
      begin
        JSON.parse(response.body)
      rescue JSON::ParserError => e
        log("Could not parse snapshot response for '#{name}': invalid JSON")
        if PERCY_DEBUG then log(e) end
        return
      end

    unless data['success']
      raise StandardError, data['error']
    end
  rescue StandardError => e
    log("Could not take DOM snapshot '#{name}'")

    if PERCY_DEBUG then log(e) end
  end
end