Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SessionMock: a small module to help mocking sessions within Hanami in feature specs
# Session mocking may be used in feature tests to mock a session
# since it's not possible to inject the session through params or
# direct injection.
#
# SessionMock is a module that may be included
# in `Hanami::Web::Action` to override the session
# in feature specs.
#
# Usage (in the controller action):
#
# module Web::Controllers::Home::Index
# include Web::Action
# include SessionMock
# end
#
# Usage (in the spec):
#
# before { SessionMock.enable_and_set!(session }
# after { SessionMock.disable! }
# let(:session) { { key: value } }
#
# TODO: see if it can be added automatically to
# `Web::Action` modules.
#
module SessionMock
@enabled = false
if ENV['HANAMI_ENV'] == 'test'
def session
return super unless SessionMock.enabled?
SessionMock.get
end
end
def self.enabled?
@enabled
end
def self.get
@value
end
def self.set(session)
@value = session
end
# TODO: see how to enable/disable session mock for feature
# tests automatically.
def self.enable_and_set!(session)
@enabled = true
set(session)
end
def self.disable!
@enabled = false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment