Class: RSpec::Snapshot::FileOperator

Inherits:
Object
  • Object
show all
Defined in:
lib/rspec/snapshot/file_operator.rb

Overview

Handles File IO for snapshots

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(snapshot_name, metadata) ⇒ FileOperator

Initializes the class instance, and creates the snapshot directory for the current test if needed.

Parameters:

  • snapshot_name (String) —

    The name of the snapshot to read/write.

  • metadata (Hash) —

    The RSpec metadata for the current test.



16
17
18
19
20
# File 'lib/rspec/snapshot/file_operator.rb', line 16

def initialize(snapshot_name, )
  snapshot_dir = snapshot_dir()
  @snapshot_path = File.join(snapshot_dir, "#{snapshot_name}.snap")
  create_snapshot_dir(@snapshot_path)
end

Instance Attribute Details

#snapshot_path ⇒ Object (readonly)

Returns the value of attribute snapshot_path.



9
10
11
# File 'lib/rspec/snapshot/file_operator.rb', line 9

def snapshot_path
  @snapshot_path
end

Instance Method Details

#read ⇒ String

Returns The snapshot file contents.

Returns:

  • (String) —

    The snapshot file contents.



37
38
39
40
41
42
# File 'lib/rspec/snapshot/file_operator.rb', line 37

def read
  file = File.new(@snapshot_path)
  value = file.read
  file.close
  value
end

#write(value) ⇒ Object

Writes the value to file, overwriting the file contents if either of the following is true:

  • The snapshot file does not already exist.
  • The UPDATE_SNAPSHOTS environment variable is set.

TODO: Do not write to file if running in CI mode.

Parameters:

  • snapshot_name (String) —

    The snapshot name.

  • value (String) —

    The value to write to file.



53
54
55
56
57
58
59
60
61
62
# File 'lib/rspec/snapshot/file_operator.rb', line 53

def write(value)
  return unless should_write?

  file = File.new(@snapshot_path, 'w+')
  file.write(value)
  RSpec.configuration.reporter.message(
    "Snapshot written: #{@snapshot_path}"
  )
  file.close
end