Module: FileSpec::Helpers

Defined in:
lib/file_spec.rb

Overview

A set of helper methods for interacting with files

Examples:

RSpec.configure do |config|
  config.include FileSpec::Helpers
end

Constant Summary collapse

IGNORE =
%w[.git .svn .venv .DS_Store node_modules *.o *.pyc *.class *.lock *.log]

Instance Method Summary collapse

Instance Method Details

#diff(before, after, exclude: [], **opts) ⇒ Object

Get the diff between two files or directories

Parameters:

  • before (String, Pathname)

    file path of inital file or files

  • after (String, Pathname)

    file path of changed file or files

  • exclude (Array<String>) (defaults to: [])

    list of paths to ignore



72
73
74
75
76
77
78
79
80
# File 'lib/file_spec.rb', line 72

def diff(before, after, exclude: [], **opts)
  cmd = %w[diff --unified --new-file --recursive]
  cmd += (exclude + IGNORE).flat_map { |path| ["--exclude", path] }
  cmd += [before.to_s, after.to_s]

  diff, _status = Open3.capture2e(*cmd, **opts)
  diff = diff.gsub(/^diff --unified.*\n/, "")
  diff.gsub(/^([+-]{3})\s(.*)\t\d{4}-.*$/, "\\1 \\2")
end

#mkdir(path) ⇒ Object

Create a directories if they do not exist.

Parameters:

  • path (String, Pathname)


50
51
52
# File 'lib/file_spec.rb', line 50

def mkdir(path)
  FileUtils.mkdir_p(path)
end

#read(path) ⇒ Object

Read a file.

Parameters:

  • path (String, Pathname)


64
65
66
# File 'lib/file_spec.rb', line 64

def read(path)
  File.read(path)
end

#record_changes(path, **opts) ⇒ Object

Record changes to a file or directory over time

Parameters:

  • path (String, Pathname)

    the path to observe

  • opts (Hash)

    additional options passed to #diff



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/file_spec.rb', line 85

def record_changes(path, **opts)
  tmp_path = Dir.mktmpdir("file_spec")
  before_path = File.join(tmp_path, "a")
  after_path = File.join(tmp_path, "b")

  if File.file?(path)
    mkdir before_path
    mkdir after_path
  end

  FileUtils.cp_r(path, before_path)
  yield
  FileUtils.cp_r(path, after_path)

  diff("a", "b", chdir: tmp_path, **opts)
ensure
  FileUtils.rm_rf(tmp_path)
end

#write(path, content = "") ⇒ Object

Write a file. This will automatically create directories if necessary.

Parameters:

  • path (String, Pathname)
  • content (String) (defaults to: "")


57
58
59
60
# File 'lib/file_spec.rb', line 57

def write(path, content = "")
  mkdir(File.dirname(path))
  File.write(path, content)
end