class RSpecRcv::Handler

Attributes

data[R]
file_path[R]
opts[R]

Public Class Methods

new(file_path, data, metadata: {}) click to toggle source
# File lib/rspec-rcv/handler.rb, line 6
def initialize(file_path, data, metadata: {})
  @file_path = file_path
  @opts = RSpecRcv.config(metadata)
  @data = data.call(@opts)
end

Public Instance Methods

call() click to toggle source
# File lib/rspec-rcv/handler.rb, line 12
def call
  return :no_change if existing_data && existing_data["file"] == file_path && existing_data["data"] == data

  output = { recorded_at: Time.now, file: file_path, data: data }
  output = opts[:codec].export_with(output) + "\n"

  if existing_data
    existing_data_comparison = opts.fetch(:parse_existing).call(existing_data)
    eq = opts[:compare_with].call(existing_data_comparison, data, opts)

    if !eq && opts[:fail_on_changed_output]
      raise_error!(output, JsonCompare.get_diff(existing_data_comparison, data, opts.fetch(:ignore_keys, [])))
    end

    return :same if eq
  end

  FileUtils.mkdir_p(File.dirname(path))
  File.open(path, 'w') do |file|
    file.write(output)
  end

  return :to_disk
end

Private Instance Methods

existing_data() click to toggle source
# File lib/rspec-rcv/handler.rb, line 55
def existing_data
  @existing_data ||= if File.exists?(path)
                       opts[:codec].decode_with(File.read(path))
                     end
end
existing_file() click to toggle source
# File lib/rspec-rcv/handler.rb, line 49
def existing_file
  @existing_file ||= if File.exists?(path)
                       File.read(path)
                     end
end
path() click to toggle source
# File lib/rspec-rcv/handler.rb, line 41
def path
  if opts[:base_path]
    File.join(opts[:base_path], opts[:fixture])
  else
    opts[:fixture]
  end
end
raise_error!(output, json_compare_output) click to toggle source
# File lib/rspec-rcv/handler.rb, line 61
    def raise_error!(output, json_compare_output)
      diff = Diffy::Diff.new(existing_file, output).to_s

      combined = JsonOutputCombiner.new(json_compare_output).combine
      removed = combined[:remove]
      added = combined[:append]
      updated = combined[:update]

      raise RSpecRcv::DataChangedError.new(<<-EOF)
Existing data will be overwritten. Turn off this feature with fail_on_changed_output=false

#{diff}

The following keys were added: #{added.uniq.map(&:to_s)}
The following keys were removed: #{removed.uniq.map(&:to_s)}
The following keys were updated: #{updated.uniq.map(&:to_s)}

This fixture is located at #{path}
      EOF
    end