Module: Plumbum::RSpec::StubProvider

Extended by:
SleepingKingStudios::Tools::Toolbox::Mixin
Defined in:
lib/plumbum/rspec/stub_provider.rb

Overview

Helper methods for stubbing the values of Plumbum providers in RSpec tests.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.validate_key(provider, key) ⇒ Object

Verifies the provider has the given key.

Parameters:

  • provider (Plumbum::Provider)

    the provider to stub.

  • key (String, Symbol)

    the key to verify.

Returns:

  • void

Raises:



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/plumbum/rspec/stub_provider.rb', line 31

def validate_key(provider, key)
  SleepingKingStudios::Tools::Toolbelt
    .instance
    .assertions
    .validate_name(key, as: :key)

  return if provider.has?(key)

  return if provider.send(:raw_value, key.to_s) == Plumbum::UNDEFINED

  provider_name =
    provider.respond_to?(:name) ? provider.name : provider.class.name

  raise Plumbum::Errors::InvalidKeyError,
    "invalid key #{key.inspect} for #{provider_name}"
end

Instance Method Details

#stub_provider(provider, key, value) ⇒ Symbol

Stubs the value of a specific key for a provider for the current spec.

Parameters:

  • provider (Plumbum::Provider)

    the provider to stub.

  • key (String, Symbol)

    the key to stub.

  • value (Object)

    the temporary value to assign for the key.

Returns:

  • (Symbol)

    the stubbed key.

Raises:



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/plumbum/rspec/stub_provider.rb', line 59

def stub_provider(provider, key, value) # rubocop:disable Metrics/AbcSize
  StubProvider.validate_key(provider, key)

  unless RSpec::Mocks.space.registered?(provider)
    allow(provider).to receive(:get).and_call_original
    allow(provider).to receive(:has?).and_call_original
  end

  presence = value != Plumbum::UNDEFINED

  allow(provider).to receive(:get).with(key.to_s).and_return(value)
  allow(provider).to receive(:get).with(key.to_sym).and_return(value)
  allow(provider).to receive(:has?).with(key.to_s).and_return(presence)
  allow(provider).to receive(:has?).with(key.to_sym).and_return(presence)
end