Module: Sequent::Test::CommandHandlerHelpers

Defined in:
lib/sequent/test/command_handler_helpers.rb

Overview

Use in tests

This provides a nice DSL for event based testing of your CommandHandler like

given_events InvoiceCreatedEvent.new(args) when_command PayInvoiceCommand(args) then_events InvoicePaidEvent(args)

Example for Rspec config

RSpec.configure do |config|

config.include Sequent::Test::CommandHandlerHelpers

end

Then in a spec

describe InvoiceCommandHandler do

before :each do
  Sequent.configuration.event_store = Sequent::Test::CommandHandlerHelpers::FakeEventStore.new
  Sequent.configuration.command_handlers = [] # add your command handlers here
  Sequent.configuration.event_handlers = [] # add you event handlers (eg, workflows) here
end

it "marks an invoice as paid" do
  given_events InvoiceCreatedEvent.new(args)
  when_command PayInvoiceCommand(args)
  then_events InvoicePaidEvent(args)
end

end

Defined Under Namespace

Classes: FakeEventStore

Instance Method Summary collapse

Instance Method Details

#given_events(*events) ⇒ Object



132
133
134
# File 'lib/sequent/test/command_handler_helpers.rb', line 132

def given_events *events
  Sequent.configuration.event_store.given_events(events.flatten(1))
end

#then_events(*expected_events) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
# File 'lib/sequent/test/command_handler_helpers.rb', line 140

def then_events(*expected_events)
  expected_classes = expected_events.flatten(1).map { |event| event.class == Class ? event : event.class }
  expect(Sequent.configuration.event_store.stored_events.map(&:class)).to eq(expected_classes)

  Sequent.configuration.event_store.stored_events.zip(expected_events.flatten(1)).each_with_index do |(actual, expected), index|
    next if expected.class == Class
    _actual = Sequent::Core::Oj.strict_load(Sequent::Core::Oj.dump(actual.payload))
    _expected = Sequent::Core::Oj.strict_load(Sequent::Core::Oj.dump(expected.payload))
    expect(_actual).to eq(_expected), "#{index+1}th Event of type #{actual.class} not equal\nexpected: #{_expected.inspect}\n     got: #{_actual.inspect}" if expected
  end
end

#then_no_eventsObject



152
153
154
# File 'lib/sequent/test/command_handler_helpers.rb', line 152

def then_no_events
  then_events
end

#when_command(command) ⇒ Object



136
137
138
# File 'lib/sequent/test/command_handler_helpers.rb', line 136

def when_command command
  Sequent.configuration.command_service.execute_commands command
end