Sha256: 7d8f0ece63d5b7092c833e82f3804e7f41d85ca34ed0cbadecccb15f31931070

Contents?: true

Size: 1.53 KB

Versions: 18

Compression:

Stored size: 1.53 KB

Contents

# Allows easy mocking of global and class constants

# Inspired by:
# http://missingbit.blogspot.com/2011/07/stubbing-constants-in-rspec_20.html
# http://digitaldumptruck.jotabout.com/?p=551

def mock_constants(constants)
  saved_constants = {}
  constants.each do |constant, val|
    source_object, const_name = parse_constant(constant)
    saved_constants[constant] = source_object.const_get(const_name)
    with_warnings(nil) { source_object.const_set(const_name, val) }
  end

  begin
    yield
  ensure
    constants.each_key do |constant|
      source_object, const_name = parse_constant(constant)
      with_warnings(nil) { source_object.const_set(const_name, saved_constants[constant]) }
    end
  end
end

def parse_constant(constant)
  source, _, constant_name = constant.to_s.rpartition("::")
  [constantize(source), constant_name]
end

# Taken from ActiveSupport

# File activesupport/lib/active_support/core_ext/kernel/reporting.rb, line 3
#
# Sets $VERBOSE for the duration of the block and back to its original value afterwards.
def with_warnings(flag)
  old_verbose, $VERBOSE = $VERBOSE, flag
  yield
ensure
  $VERBOSE = old_verbose
end

# File activesupport/lib/active_support/inflector/methods.rb, line 209
def constantize(camel_cased_word)
  names = camel_cased_word.split("::")
  names.shift if names.empty? || names.first.empty?

  constant = Object
  names.each do |name|
    constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
  end
  constant
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
chef-14.13.11-universal-mingw32 spec/support/mock/constant.rb
chef-15.0.300-universal-mingw32 spec/support/mock/constant.rb
chef-15.0.298-universal-mingw32 spec/support/mock/constant.rb
chef-15.0.293-universal-mingw32 spec/support/mock/constant.rb
chef-14.12.9-universal-mingw32 spec/support/mock/constant.rb
chef-14.12.3-universal-mingw32 spec/support/mock/constant.rb
chef-14.11.21-universal-mingw32 spec/support/mock/constant.rb
chef-14.10.9-universal-mingw32 spec/support/mock/constant.rb
chef-14.9.13-universal-mingw32 spec/support/mock/constant.rb
chef-14.8.12-universal-mingw32 spec/support/mock/constant.rb
chef-14.7.17-universal-mingw32 spec/support/mock/constant.rb
chef-14.6.47-universal-mingw32 spec/support/mock/constant.rb
chef-14.5.33-universal-mingw32 spec/support/mock/constant.rb
chef-14.3.37-universal-mingw32 spec/support/mock/constant.rb
chef-14.2.0-universal-mingw32 spec/support/mock/constant.rb
chef-14.1.12-universal-mingw32 spec/support/mock/constant.rb
chef-14.1.1-universal-mingw32 spec/support/mock/constant.rb
chef-14.0.190-universal-mingw32 spec/support/mock/constant.rb