Skip to content

Instantly share code, notes, and snippets.

@rchampourlier
Created April 16, 2017 21:29
Show Gist options
  • Save rchampourlier/952547bf635a9c6c90154523195ea698 to your computer and use it in GitHub Desktop.
Save rchampourlier/952547bf635a9c6c90154523195ea698 to your computer and use it in GitHub Desktop.
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