Module: TestConstruct::Helpers

Extended by:
Helpers
Included in:
TestConstruct, Helpers
Defined in:
lib/test_construct/helpers.rb

Instance Method Summary collapse

Instance Method Details

#create_construct(opts = {}) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/test_construct/helpers.rb', line 20

def create_construct(opts = {})
  chdir_default = opts.delete(:chdir) { true }
  base_path     = Pathname(opts.delete(:base_dir) { TestConstruct.tmpdir })
  name          = opts.delete(:name) { "" }
  slug          = name.downcase.tr_s("^a-z0-9", "-")[0..63]
  if opts.any?
    raise "[TestConstruct] Unrecognized options: #{opts.keys}"
  end
  dir = "#{CONTAINER_PREFIX}-#{$PROCESS_ID}-#{rand(1_000_000_000)}"
  dir << "-" << slug unless slug.empty?
  path = base_path + dir
  path.mkpath
  path.extend(PathnameExtensions)
  path.construct__chdir_default = chdir_default
  path
end

#setup_construct(opts = {}) ⇒ Object

THIS METHOD MAY HAVE EXTERNAL SIDE-EFFECTS, including:

  • creating the container directory tree

  • changing the current working directory

It is intended to be paired with #teardown_construct



42
43
44
45
46
47
48
49
# File 'lib/test_construct/helpers.rb', line 42

def setup_construct(opts = {})
  opts  = opts.dup
  chdir = opts.fetch(:chdir, true)
  opts.delete(:keep_on_error) { false } # not used in setup
  container = create_construct(opts)
  container.maybe_change_dir(chdir)
  container
end

#teardown_construct(container, error = nil, opts = {}) ⇒ Object

THIS METHOD MAY HAVE EXTERNAL SIDE-EFFECTS, including:

  • removing the container directory tree

  • changing the current working directory

  • modifying any exception passed as ‘error`

It is intended to be paired with #setup_construct



57
58
59
60
61
62
63
# File 'lib/test_construct/helpers.rb', line 57

def teardown_construct(container, error = nil, opts = {})
  if error && opts[:keep_on_error]
    container.keep
    container.annotate_exception!(error)
  end
  container.finalize
end

#within_construct(opts = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/test_construct/helpers.rb', line 9

def within_construct(opts = {})
  container = setup_construct(opts)
  yield(container)
rescue Exception => error
  raise unless container
  teardown_construct(container, error, opts)
  raise error
else
  teardown_construct(container, nil, opts)
end