module FileSpec::Helpers

A set of helper methods for interacting with files

@example

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

Constants

IGNORE

Public Instance Methods

diff(before, after, exclude: [], **opts) click to toggle source

Get the diff between two files or directories @param before [String,Pathname] file path of inital file or files @param after [String,Pathname] file path of changed file or files @param exclude [Array<String>] list of paths to ignore

# 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) click to toggle source

Create a directories if they do not exist. @param path [String,Pathname]

# File lib/file_spec.rb, line 50
def mkdir(path)
  FileUtils.mkdir_p(path)
end
read(path) click to toggle source

Read a file. @param path [String,Pathname]

# File lib/file_spec.rb, line 64
def read(path)
  File.read(path)
end
record_changes(path, **opts) { || ... } click to toggle source

Record changes to a file or directory over time @param path [String,Pathname] the path to observe @param opts [Hash] additional options passed to {#diff}

# 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 = "") click to toggle source

Write a file. This will automatically create directories if necessary. @param path [String,Pathname] @param content [String]

# File lib/file_spec.rb, line 57
def write(path, content = "")
  mkdir(File.dirname(path))
  File.write(path, content)
end