Module: ServiceObjects::RSpec

Includes:
RSpec::Mocks::ExampleMethods
Defined in:
lib/service_objects/rspec.rb

Overview

Collection of helpers and matchers for testing services

Examples:

require "service_objects/rspec"
describe MyService do
  include ServiceObjects::RSpec
end

Instance Method Summary collapse

Instance Method Details

#inject(dependency, with: {}, constructs: service_double) ⇒ undefined

Makes given dependency to construct object when called with params

Examples:

before { inject(:get_item, with: { name: :foo }, constructs: foo) }
service.get_item.new(name: :foo) # => foo

Returns:

  • (undefined)


44
45
46
47
48
# File 'lib/service_objects/rspec.rb', line 44

def inject(dependency, with: {}, constructs: service_double)
  klass = Class.new ServiceObjects::Base
  allow(klass).to receive(:new).with(with).and_return constructs
  allow(service).to receive(dependency).and_return klass
end

#listener::RSpec::Mocks::Double

The spy object to listen a service’s notifications

Returns:

  • (::RSpec::Mocks::Double)


33
34
35
# File 'lib/service_objects/rspec.rb', line 33

def listener
  spy
end

#paramsHash

Params to be given to service object constructor

Returns:

  • (Hash)


19
20
21
# File 'lib/service_objects/rspec.rb', line 19

def params
  @params ||= {}
end

#serviceServiceObjects::Base

The service object of described_class, that subscribed the listener



26
27
28
# File 'lib/service_objects/rspec.rb', line 26

def service
  @service ||= described_class.new(params).subscribe(listener)
end

#service_double(*args, &block) ⇒ ServiceObjects::Base

Mock for another services, the service under test depends from

The block contains the code to be executed on service #run.

Examples:

let(:another_service) { service_double(:foo) { |name| publish name } }
another_service.run
# another_service sends :foo to its listeners

Parameters:

  • args (Array<Object>)

    the list of arguments for the block

  • block (Proc)

    the block to be yielded by #run method

Returns:



65
66
67
68
69
70
71
# File 'lib/service_objects/rspec.rb', line 65

def service_double(*args, &block)
  object = ServiceObjects::Base.new
  allow(object).to receive(:run) do
    object.instance_exec(*args, &block) if block_given?
  end
  object
end