Module: Uses::InjectDouble

Defined in:
lib/uses/inject_double.rb

Overview

Convienience methods for test to inject mocks/doubles into a class under test.

An advantage of “injecting” dependencies is that you can provide alternate implementations for testing that simplify your tests. While Ruby doesn’t strictly require that you make dependencies injectible, it is nice to have a bit of help in doing to so for a test.

If using RSpec, use ‘inject_rspec_double`.

Instance Method Summary collapse

Instance Method Details

#inject_double(subject, injections) ⇒ Object

Inject an instantiated double into subject, returing the double.

subject

the instance of the class under test where you want a double injected

injectsion

a hash of size 1 where the key is the class given to ‘uses` and the value is the doubled object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/uses/inject_double.rb', line 15

def inject_double(subject, injections)
  if injections.size != 1
    raise "expected a single key/value to inject_double, but got #{injections.size}"
  end

  klass    = injections.first[0]
  instance = injections.first[1]

  subject_must_use_uses!(subject)
  injected_class_must_be_class!(klass)

  name = dependency_method_name!(subject, klass)

  subject.__uses_dependent_instances[name] = instance

  instance
end

#inject_rspec_double(subject, klass) ⇒ Object

For Rspec users, you might do:

dependent_service = instance_doule(DependentService)
allow(DependentService).to receive(:new).and_return(dependent_service)

The problem is that it would be nice to know if your class under test actually uses the dependent service, plus it’s annoying to have to write two lines of code.

Instead:

dependent_service = instance_double(object_under_test, DependentService)

If you depend in DependentService, this will replace the real instance with yours. If you do not it will raise an error.



48
49
50
# File 'lib/uses/inject_double.rb', line 48

def inject_rspec_double(subject, klass)
  self.inject_double(subject, klass => instance_double(klass))
end