Class: SnapshotTesting::Recorder

Inherits:
Object
  • Object
show all
Defined in:
lib/snapshot_testing/recorder.rb

Instance Method Summary collapse

Constructor Details

#initialize(name:, path:, update:) ⇒ Recorder

Returns a new instance of Recorder.



6
7
8
9
10
11
# File 'lib/snapshot_testing/recorder.rb', line 6

def initialize(name:, path:, update:)
  @name   = name
  @path   = path
  @update = update
  @state  = {}
end

Instance Method Details

#commitObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/snapshot_testing/recorder.rb', line 45

def commit
  added   = @state.select { |k, _| !snapshots.key?(k) }
  changed = @state.select { |k, v| snapshots.key?(k) && snapshots[k] != v }
  removed = snapshots.keys.select do |k|
    k.match?(/^#{@name}\s\d+$/) && !@state.key?(k)
  end

  result = snapshots.merge(added)
  result = result.merge(changed) if @update
  result = result.reject { |k, _| removed.include?(k) } if @update

  write(result) if result != snapshots
  log(added.length, :written, :green) if added.any?
  log(changed.length, :updated, :green) if @update && changed.any?
  log(removed.length, :removed, :green) if @update && removed.any?
  log(removed.length, :obsolete, :yellow) if !@update && removed.any?
end

#record(actual) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/snapshot_testing/recorder.rb', line 29

def record(actual)
  key = "#{@name} #{@state.length + 1}"

  # keep track each encounter, so we can diff later
  @state[key] = actual

  # pass the test when updating snapshots
  return actual if @update

  # pass the test when the snapshot does not exist
  return actual unless snapshots.key?(key)

  # otherwise, compare actual to the snapshot
  snapshots[key]
end

#snapshot_dirObject



13
14
15
# File 'lib/snapshot_testing/recorder.rb', line 13

def snapshot_dir
  File.join(File.dirname(@path), "__snapshots__")
end

#snapshot_fileObject



17
18
19
# File 'lib/snapshot_testing/recorder.rb', line 17

def snapshot_file
  File.join(snapshot_dir, "#{File.basename(@path)}.snap")
end

#snapshotsObject



21
22
23
24
25
26
27
# File 'lib/snapshot_testing/recorder.rb', line 21

def snapshots
  @snapshots ||= begin
    Snapshot.load_file(snapshot_file)
  rescue Errno::ENOENT
    {}
  end
end