class RSpec::Mocks::ConstantStubber

Provides a means to stub constants.

Public Class Methods

ensure_registered_with_mocks_space() click to toggle source

Ensures the constant stubbing is registered with rspec-mocks space so that stubbed constants can be restored when examples finish.

@api private

# File lib/rspec/mocks/stub_const.rb, line 232
def self.ensure_registered_with_mocks_space
  return if @registered_with_mocks_space
  ::RSpec::Mocks.space.add(self)
  @registered_with_mocks_space = true
end
find(name) click to toggle source
# File lib/rspec/mocks/stub_const.rb, line 261
def self.find(name)
  stubbers.find { |s| s.full_constant_name == name }
end
raise_on_invalid_const() click to toggle source

Used internally by the constant stubbing to raise a helpful error when a constant like "A::B::C" is stubbed and A::B is not a module (and thus, it's impossible to define "A::B::C" since only modules can have nested constants).

@api private

# File lib/rspec/mocks/stub_const.rb, line 271
def self.raise_on_invalid_const
  lambda do |const_name, failed_name|
    raise "Cannot stub constant #{failed_name} on #{const_name} " +
          "since #{const_name} is not a module."
  end
end
rspec_reset() click to toggle source

Resets all stubbed constants. This is called automatically by rspec-mocks when an example finishes.

@api private

# File lib/rspec/mocks/stub_const.rb, line 242
def self.rspec_reset
  @registered_with_mocks_space = false

  # We use reverse order so that if the same constant
  # was stubbed multiple times, the original value gets
  # properly restored.
  stubbers.reverse.each { |s| s.rspec_reset }

  stubbers.clear
end
stub(constant_name, value, options = {}) click to toggle source

Stubs a constant.

@param (see RSpec::Mocks::ExampleMethods#stub_const) @option (see RSpec::Mocks::ExampleMethods#stub_const) @return (see RSpec::Mocks::ExampleMethods#stub_const)

@see RSpec::Mocks::ExampleMethods#stub_const @note It's recommended that you use `stub_const` in your

examples. This is an alternate public API that is provided
so you can stub constants in other contexts (e.g. helper
classes).
# File lib/rspec/mocks/stub_const.rb, line 95
def self.stub(constant_name, value, options = {})
  stubber = if recursive_const_defined?(constant_name, &raise_on_invalid_const)
    DefinedConstantReplacer
  else
    UndefinedConstantSetter
  end

  stubber = stubber.new(constant_name, value, options[:transfer_nested_constants])
  stubbers << stubber

  stubber.stub
  ensure_registered_with_mocks_space
  value
end
stubbers() click to toggle source

The list of constant stubbers that have been used for the current example.

@api private

# File lib/rspec/mocks/stub_const.rb, line 257
def self.stubbers
  @stubbers ||= []
end