repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
realm/jazzy | https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/symbol_graph/symbol.rb | lib/jazzy/symbol_graph/symbol.rb | # frozen_string_literal: true
# rubocop:disable Metrics/ClassLength
module Jazzy
module SymbolGraph
# A Symbol is a tidied-up SymbolGraph JSON object
class Symbol
attr_accessor :usr
attr_accessor :path_components
attr_accessor :declaration
attr_accessor :kind
attr_accessor :acl
attr_accessor :spi
attr_accessor :location # can be nil, keys :filename :line :character
attr_accessor :constraints # array, can be empty
attr_accessor :doc_comments # can be nil
attr_accessor :attributes # array, can be empty
attr_accessor :generic_type_params # set, can be empty
attr_accessor :parameter_names # array, can be nil
def name
path_components[-1] || '??'
end
def full_name
path_components.join('.')
end
def initialize(hash)
self.usr = hash[:identifier][:precise]
self.path_components = hash[:pathComponents]
raw_decl, keywords = parse_decl_fragments(hash[:declarationFragments])
init_kind(hash[:kind][:identifier], keywords)
init_declaration(raw_decl)
if func_signature = hash[:functionSignature]
init_func_signature(func_signature)
end
init_acl(hash[:accessLevel])
self.spi = hash[:spi]
if location = hash[:location]
init_location(location)
end
init_constraints(hash, raw_decl)
if comments_hash = hash[:docComment]
init_doc_comments(comments_hash)
end
init_attributes(hash[:availability] || [])
init_generic_type_params(hash)
end
def parse_decl_fragments(fragments)
decl = ''
keywords = Set.new
fragments.each do |frag|
decl += frag[:spelling]
keywords.add(frag[:spelling]) if frag[:kind] == 'keyword'
end
[decl, keywords]
end
# Repair problems with SymbolGraph's declprinter
def init_declaration(raw_decl)
# Too much 'Self.TypeName'; omitted arg labels look odd;
# duplicated constraints; swift 5.3 vs. master workaround
self.declaration = raw_decl
.gsub(/\bSelf\./, '')
.gsub(/(?<=\(|, )_: /, '_ arg: ')
.gsub(/ where.*$/, '')
if kind == 'source.lang.swift.decl.class'
declaration.sub!(/\s*:.*$/, '')
end
end
# Remember pieces of methods for later markdown parsing
def init_func_signature(func_signature)
self.parameter_names =
(func_signature[:parameters] || []).map { |h| h[:name] }
end
# Mapping SymbolGraph's declkinds to SourceKit
KIND_MAP = {
'class' => 'class',
'struct' => 'struct',
'enum' => 'enum',
'enum.case' => 'enumelement', # intentional
'protocol' => 'protocol',
'init' => 'function.constructor',
'deinit' => 'function.destructor',
'func.op' => 'function.operator',
'type.method' => 'function.method.class',
'static.method' => 'function.method.static',
'method' => 'function.method.instance',
'func' => 'function.free',
'type.property' => 'var.class',
'static.property' => 'var.static',
'property' => 'var.instance',
'var' => 'var.global',
'subscript' => 'function.subscript',
'type.subscript' => 'function.subscript',
'static.subscript' => 'function.subscript',
'typealias' => 'typealias',
'associatedtype' => 'associatedtype',
'actor' => 'actor',
'macro' => 'macro',
'extension' => 'extension',
}.freeze
# We treat 'static var' differently to 'class var'
# We treat actors as first-class entities
def adjust_kind_for_declaration(kind, keywords)
if kind == 'swift.class' && keywords.member?('actor')
return 'swift.actor'
end
return kind unless keywords.member?('static')
kind.gsub('type', 'static')
end
def init_kind(kind, keywords)
adjusted = adjust_kind_for_declaration(kind, keywords)
sourcekit_kind = KIND_MAP[adjusted.sub('swift.', '')]
raise "Unknown symbol kind '#{kind}'" unless sourcekit_kind
self.kind = "source.lang.swift.decl.#{sourcekit_kind}"
end
def extension?
kind.end_with?('extension')
end
# Mapping SymbolGraph's ACL to SourceKit
def init_acl(acl)
self.acl = "source.lang.swift.accessibility.#{acl}"
end
# Symbol location - only available for public+ decls
def init_location(loc_hash)
self.location = {}
location[:filename] = loc_hash[:uri].sub(%r{^file://}, '')
location[:line] = loc_hash[:position][:line]
location[:character] = loc_hash[:position][:character]
end
# Generic constraints: in one or both of two places.
# There can be duplicates; these are removed by `Constraint`.
def init_constraints(hash, raw_decl)
raw_constraints = %i[swiftGenerics swiftExtension].flat_map do |key|
next [] unless container = hash[key]
container[:constraints] || []
end
constraints =
Constraint.new_list_for_symbol(raw_constraints, path_components)
if raw_decl =~ / where (.*)$/
constraints +=
Constraint.new_list_from_declaration(Regexp.last_match[1])
end
self.constraints = constraints.sort.uniq
end
# Generic type params
def init_generic_type_params(hash)
self.generic_type_params = Set.new(
if (generics = hash[:swiftGenerics]) &&
(parameters = generics[:parameters])
parameters.map { |p| p[:name] }
else
[]
end,
)
end
def init_doc_comments(comments_hash)
self.doc_comments = comments_hash[:lines]
.map { |l| l[:text] }
.join("\n")
end
# Availability
# Re-encode this as Swift. Should really teach Jazzy about these,
# could maybe then do something smarter here.
def availability_attributes(avail_hash_list)
avail_hash_list.map do |avail|
str = '@available('
if avail[:isUnconditionallyDeprecated]
str += '*, deprecated'
elsif domain = avail[:domain]
str += domain
%i[introduced deprecated obsoleted].each do |event|
if version = avail[event]
str += ", #{event}: #{decode_version(version)}"
end
end
else
warn "Found confusing availability: #{avail}"
next nil
end
str += ", message: \"#{avail[:message]}\"" if avail[:message]
str += ", renamed: \"#{avail[:renamed]}\"" if avail[:renamed]
str + ')'
end.compact
end
def decode_version(hash)
str = hash[:major].to_s
str += ".#{hash[:minor]}" if hash[:minor]
str += ".#{hash[:patch]}" if hash[:patch]
str
end
def spi_attributes
spi ? ['@_spi(Unknown)'] : []
end
def init_attributes(avail_hash_list)
self.attributes =
availability_attributes(avail_hash_list) + spi_attributes
end
# SourceKit common fields, shared by extension and regular symbols.
# Things we do not know for fabricated extensions.
def add_to_sourcekit(hash)
unless doc_comments.nil?
hash['key.doc.comment'] = doc_comments
hash['key.doc.full_as_xml'] = ''
end
hash['key.accessibility'] = acl
unless location.nil?
hash['key.filepath'] = location[:filename]
hash['key.doc.line'] = location[:line] + 1
hash['key.doc.column'] = location[:character] + 1
end
hash
end
# Sort order
include Comparable
def <=>(other)
# Things with location: order by file/line/column
# (pls tell what wheel i am reinventing :/)
if location && other_loc = other.location
if location[:filename] == other_loc[:filename]
if location[:line] == other_loc[:line]
return location[:character] <=> other_loc[:character]
end
return location[:line] <=> other_loc[:line]
end
return location[:filename] <=> other_loc[:filename]
end
# Things with a location before things without a location
return +1 if location.nil? && other.location
return -1 if location && other.location.nil?
# Things without a location: by name and then USR
return usr <=> other.usr if name == other.name
name <=> other.name
end
end
end
end
# rubocop:enable Metrics/ClassLength
| ruby | MIT | 8852cdba0fd95acab32bb121fc495abe2fbe5fc8 | 2026-01-04T15:39:34.502623Z | false |
realm/jazzy | https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/symbol_graph/ext_key.rb | lib/jazzy/symbol_graph/ext_key.rb | # frozen_string_literal: true
module Jazzy
module SymbolGraph
# An ExtKey identifies an extension of a type, made up of the USR of
# the type and the constraints of the extension. With Swift 5.9 extension
# symbols, the USR is the 'fake' USR invented by symbolgraph to solve the
# same problem as this type, which means less merging takes place.
class ExtKey
attr_accessor :usr
attr_accessor :constraints_text
def initialize(usr, constraints)
self.usr = usr
self.constraints_text = constraints.map(&:to_swift).join
end
def hash_key
usr + constraints_text
end
def eql?(other)
hash_key == other.hash_key
end
def hash
hash_key.hash
end
end
class ExtSymNode
def ext_key
ExtKey.new(usr, all_constraints.ext)
end
end
end
end
| ruby | MIT | 8852cdba0fd95acab32bb121fc495abe2fbe5fc8 | 2026-01-04T15:39:34.502623Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require "pathname"
SPEC_ROOT = File.expand_path(__dir__).freeze
LOG_DIR = Pathname(SPEC_ROOT).join("..").join("log")
require_relative "support/coverage" if ENV["COVERAGE"].eql?("true")
require "hanami"
begin; require "byebug"; rescue LoadError; end
require "hanami/utils/file_list"
require "hanami/devtools/unit"
Hanami::Utils::FileList["./spec/support/**/*.rb"].each do |file|
next if file.include?("hanami-plugin")
require file
end
RSpec.configure do |config|
config.after(:suite) do
# TODO: Find out what causes logger to create this dir when running specs.
# There's probably a test app class being created somewhere with root
# not pointing to a tmp dir.
FileUtils.rm_rf(LOG_DIR) if LOG_DIR.exist?
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/support/matchers.rb | spec/support/matchers.rb | # frozen_string_literal: true
module RSpec
module Support
module Matchers
module HTML
def squish_html(str)
str
.gsub(/^[[:space:]]+/, "")
.gsub(/>[[:space:]]+</m, "><")
.strip
end
end
end
end
end
RSpec::Matchers.define :eq_html do |expected_html|
include RSpec::Support::Matchers::HTML
match do |actual_html|
squish_html(actual_html) == squish_html(expected_html)
end
end
RSpec::Matchers.define :include_html do |expected_html|
include RSpec::Support::Matchers::HTML
match do |actual_html|
squish_html(actual_html).include?(squish_html(expected_html))
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/support/coverage.rb | spec/support/coverage.rb | require "hanami/devtools/unit/support/coverage"
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/support/app_integration.rb | spec/support/app_integration.rb | # frozen_string_literal: true
require "hanami/devtools/integration/files"
require "hanami/devtools/integration/with_tmp_directory"
require "json"
require "tmpdir"
require "zeitwerk"
module RSpec
module Support
module WithTmpDirectory
private
def make_tmp_directory
Pathname(Dir.mktmpdir).tap do |dir|
(@made_tmp_dirs ||= []) << dir
end
end
end
module App
def self.included(base)
super
base.class_eval do
let!(:node_modules_path) { File.join(Dir.pwd, "node_modules") }
end
end
private
# TODO: make slice-aware
def stub_assets(*assets)
manifest_hash = assets.each_with_object({}) { |source_path, hsh|
hsh[source_path] = {url: File.join("/assets", source_path)}
}
write "public/assets/assets.json", JSON.generate(manifest_hash)
# An assets dir is required to load the assets provider
write "app/assets/.keep", ""
end
def compile_assets!
link_node_modules
generate_assets_config
require "hanami/cli/command"
require "hanami/cli/commands/app/command"
require "hanami/cli/commands/app/assets/compile"
assets_compile = Hanami::CLI::Commands::App::Assets::Compile.new(
config: Hanami.app.config.assets,
out: File.new(File::NULL, "w"),
err: File.new(File::NULL, "w"),
)
with_directory(Hanami.app.root) { assets_compile.call }
end
def link_node_modules
root = Hanami.app.root
return if File.exist?(File.join(root, "node_modules", "hanami-assets", "dist", "hanami-assets.js"))
FileUtils.ln_s(node_modules_path, root)
rescue Errno::EEXIST # rubocop:disable Lint/SuppressedException
end
def generate_assets_config
root = Hanami.app.root
with_directory(root) do
write("config/assets.js", <<~JS) unless root.join("config", "assets.js").exist?
import * as assets from "hanami-assets";
await assets.run();
JS
write("package.json", <<~JSON) unless root.join("package.json").exist?
{
"type": "module"
}
JSON
end
end
end
end
end
RSpec.shared_context "App integration" do
let(:app_modules) { %i[TestApp Admin Main Search] }
end
def autoloaders_teardown!
ObjectSpace.each_object(Zeitwerk::Loader) do |loader|
loader.unregister if loader.dirs.any? { |dir|
dir.include?("/spec/") || dir.include?(Dir.tmpdir) ||
dir.include?("/slices/") || dir.include?("/app")
}
end
end
RSpec.configure do |config|
config.include RSpec::Support::Files, :app_integration
config.include RSpec::Support::WithTmpDirectory, :app_integration
config.include RSpec::Support::App, :app_integration
config.include_context "App integration", :app_integration
config.before :each, :app_integration do
# Conditionally assign these in case they have been assigned earlier for specific
# example groups (e.g. container/prepare_container_spec.rb)
@load_paths ||= $LOAD_PATH.dup
@loaded_features ||= $LOADED_FEATURES.dup
end
config.after :each, :app_integration do
autoloaders_teardown!
Hanami.instance_variable_set(:@_bundled, {})
Hanami.remove_instance_variable(:@_app) if Hanami.instance_variable_defined?(:@_app)
# Disconnect and clear cached DB gateways across slices
Hanami::Providers::DB.cache.values.map(&:disconnect)
Hanami::Providers::DB.cache.clear
$LOAD_PATH.replace(@load_paths)
# Remove example-specific LOADED_FEATURES added when running each example
new_features_to_keep = ($LOADED_FEATURES - @loaded_features).tap { |feats|
feats.delete_if do |path|
path =~ %r{hanami/(setup|prepare|boot|application/container/providers)} ||
path.include?(SPEC_ROOT.to_s) ||
path.include?(Dir.tmpdir)
end
}
$LOADED_FEATURES.replace(@loaded_features + new_features_to_keep)
app_modules.each do |app_module_name|
next unless Object.const_defined?(app_module_name)
Object.const_get(app_module_name).tap do |mod|
mod.constants.each do |name|
mod.send(:remove_const, name)
end
end
Object.send(:remove_const, app_module_name)
end
end
config.after :all do
if instance_variable_defined?(:@made_tmp_dirs)
Array(@made_tmp_dirs).each do |dir|
FileUtils.remove_entry dir
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/support/rspec.rb | spec/support/rspec.rb | # frozen_string_literal: true
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.before :suite do
require "hanami/devtools/integration"
Pathname.new(Dir.pwd).join("tmp").mkpath
end
config.shared_context_metadata_behavior = :apply_to_host_groups
config.filter_run_when_matching :focus
config.disable_monkey_patching!
config.warnings = false
config.default_formatter = "doc" if config.files_to_run.one?
config.order = :random
Kernel.srand config.seed
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/setup_spec.rb | spec/integration/setup_spec.rb | # frozen_string_literal: true
RSpec.describe "Hanami setup", :app_integration do
describe "Hanami.setup" do
shared_examples "hanami setup" do
it "requires the app file when found" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
expect { setup }.to change { Hanami.app? }.to true
expect(Hanami.app).to be TestApp::App
end
end
it "requires the app file when found in a parent directory" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "lib/foo/bar/.keep"
Dir.chdir("lib/foo/bar") do
expect { setup }.to change { Hanami.app? }.to true
expect(Hanami.app).to be TestApp::App
end
end
end
it "raises when the app file is not found" do
with_tmp_directory(Dir.mktmpdir) do
expect { setup }.to raise_error Hanami::AppLoadError, /Could not locate your Hanami app file/
end
end
it "doesn't raise when the app file is not found but the app is already set" do
require "hanami"
module TestApp
class App < Hanami::App
end
end
expect { setup }.not_to raise_error
end
%w[hanami-view hanami-actions hanami-router].each do |gem_name|
it "works when #{gem_name} gem is not bundled" do
allow(Hanami).to receive(:bundled?).and_call_original
expect(Hanami).to receive(:bundled?).with("hanami-router").and_return(false)
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
expect { setup }.to change { Hanami.app? }.to true
end
end
end
end
describe "using hanami/setup require" do
def setup
require "hanami/setup"
end
it_behaves_like "hanami setup"
end
describe "using Hanami.setup method" do
def setup(...)
require "hanami"
Hanami.setup(...)
end
it_behaves_like "hanami setup"
it "returns the loaded app when the app file is found" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
# Multiple calls return the same app
expect(setup).to be(Hanami.app)
expect(setup).to be(Hanami.app)
end
end
it "returns nil when given `raise_exception: false` and the app file is not found" do
with_tmp_directory(Dir.mktmpdir) do
expect(setup(raise_exception: false)).to be nil
end
end
end
end
describe "Hanami.app_path" do
subject(:app_path) { Hanami.app_path }
context "config/app.rb exists in current directory" do
it "returns its absolute path" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb"
expect(app_path.to_s).to match(%r{^/.*/config/app.rb$})
end
end
end
context "config/app.rb exists in a parent directory" do
it "returns its absolute path" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb"
write "lib/foo/bar/.keep"
Dir.chdir("lib/foo/bar") do
expect(app_path.to_s).to match(%r{^/.*/config/app.rb$})
end
end
end
end
context "no app file in any directory" do
it "returns nil" do
with_tmp_directory(Dir.mktmpdir) do
expect(app_path).to be(nil)
end
end
end
context "directory exists with same name as the app file" do
it "returns nil" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb/.keep"
expect(app_path).to be(nil)
end
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/slices_spec.rb | spec/integration/slices_spec.rb | # frozen_string_literal: true
RSpec.describe "Slices", :app_integration do
specify "Loading a slice from a slice class in the app's config dir" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/main.rb", <<~RUBY
module Main
class Slice < Hanami::Slice
end
end
RUBY
write "slices/main/lib/foo.rb", <<~RUBY
module Main
class Foo; end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main]).to be Main::Slice
end
end
specify "Loading a slice from a slice class in the app's config dir, even when no slice dir exists" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/main.rb", <<~RUBY
module Main
class Slice < Hanami::Slice
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main]).to be Main::Slice
end
end
specify "Loading a nested slice from a slice class in its parent's config dir" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/config/slices/nested.rb", <<~RUBY
module Main
module Nested
class Slice < Hanami::Slice
end
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main].slices[:nested]).to be Main::Nested::Slice
end
end
specify "Loading a slice from a slice class in its own config dir" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/config/slice.rb", <<~RUBY
module Main
class Slice < Hanami::Slice
def self.loaded_from = "own config dir"
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main]).to be Main::Slice
expect(Hanami.app.slices[:main].loaded_from).to eq "own config dir"
end
end
specify "Loading a slice from a slice class in the app's config dir, in preference to a slice class in its own config dir" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/main.rb", <<~RUBY
require "hanami"
module Main
class Slice < Hanami::Slice
def self.loaded_from = "app config dir"
end
end
RUBY
write "slices/main/config/slice.rb", <<~RUBY
raise "This should not be loaded"
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main]).to be Main::Slice
expect(Hanami.app.slices[:main].loaded_from).to eq "app config dir"
end
end
specify "Loading a nested slice from a slice class in its own config dir" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/slices/nested/config/slice.rb", <<~RUBY
module Main
module Nested
class Slice < Hanami::Slice
def self.loaded_from = "own config dir"
end
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main]).to be Main::Slice
expect(Hanami.app.slices[:main].slices[:nested].loaded_from).to eq "own config dir"
end
end
specify "Loading a deeply nested slice from a slice class in its own config dir" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
# It does NOT look up "grandparent" (or above) configs; only the parent and the app
write "slices/main/config/slices/deeply/nested.rb", <<~RUBY
raise "This should not be loaded"
RUBY
write "slices/main/slices/deeply/slices/nested/config/slice.rb", <<~RUBY
module Main
module Deeply
module Nested
class Slice < Hanami::Slice
def self.loaded_from = "own config dir"
end
end
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main].slices[:deeply].slices[:nested]).to be Main::Deeply::Nested::Slice
expect(Hanami.app.slices[:main].slices[:deeply].slices[:nested].loaded_from).to eq "own config dir"
end
end
specify "Loading a nested slice from a slice class in its parent's config dir, in preference to a slice class in its own config dir" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/config/slices/nested.rb", <<~RUBY
require "hanami"
module Main
module Nested
class Slice < Hanami::Slice
def self.loaded_from = "parent config dir"
end
end
end
RUBY
write "slices/main/slices/nested/config/slice.rb", <<~RUBY
raise "This should not be loaded"
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main]).to be Main::Slice
expect(Hanami.app.slices[:main].slices[:nested].loaded_from).to eq "parent config dir"
end
end
specify "Loading a deeply nested slice from a slice class in its parent's config dir, in preference to a slice class in its own config dir" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
# It does NOT look up "grandparent" (or above) configs; only the parent and the app
write "slices/main/config/slices/deeply/nested.rb", <<~RUBY
raise "This should not be loaded"
RUBY
write "slices/main/slices/deeply/config/slices/nested.rb", <<~RUBY
module Main
module Deeply
module Nested
class Slice < Hanami::Slice
def self.loaded_from = "parent config dir"
end
end
end
end
RUBY
write "slices/main/slices/deeply/slices/nested/config/slice.rb", <<~RUBY
raise "This should not be loaded"
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main].slices[:deeply].slices[:nested]).to be Main::Deeply::Nested::Slice
expect(Hanami.app.slices[:main].slices[:deeply].slices[:nested].loaded_from).to eq "parent config dir"
end
end
specify "Loading a nested slice from a slice class in the app's config dir, in preference to a slice class in the slice's parent config dir or the slice's own config dir" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/main/nested.rb", <<~RUBY
require "hanami"
module Main
module Nested
class Slice < Hanami::Slice
def self.loaded_from = "app config dir"
end
end
end
RUBY
write "slices/main/config/slices/nested.rb", <<~RUBY
raise "This should not be loaded"
RUBY
write "slices/main/slices/nested/config/slice.rb", <<~RUBY
raise "This should not be loaded"
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main]).to be Main::Slice
expect(Hanami.app.slices[:main].slices[:nested].loaded_from).to eq "app config dir"
end
end
specify "Loading a deeply nested slice from a slice class in the app's config dir, in preference to a slice class in the slice's parent config dir or the slice's own config dir" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/main/deeply/nested.rb", <<~RUBY
module Main
module Deeply
module Nested
class Slice < Hanami::Slice
def self.loaded_from = "app config dir"
end
end
end
end
RUBY
write "slices/main/config/slices/deeply/nested.rb", <<~RUBY
raise "This should not be loaded"
RUBY
write "slices/main/slices/deeply/slices/nested/config/slice.rb", <<~RUBY
raise "This should not be loaded"
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main].slices[:deeply].slices[:nested]).to be Main::Deeply::Nested::Slice
expect(Hanami.app.slices[:main].slices[:deeply].slices[:nested].loaded_from).to eq "app config dir"
end
end
specify "Loading a slice generates a slice class if none is defined" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/lib/foo.rb", <<~RUBY
module Main
class Foo; end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main]).to be Main::Slice
end
end
specify "Registering a slice on the app creates a slice class with a top-level namespace" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
register_slice :main
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main]).to be Main::Slice
expect(Main::Slice.ancestors).to include(Hanami::Slice)
end
end
specify "Registering a nested slice creates a slice class within the parent's namespace" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/main.rb", <<~RUBY
module Main
class Slice < Hanami::Slice
register_slice :nested
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main].slices[:nested]).to be Main::Nested::Slice
end
end
specify "Registering a nested slice with an existing class uses that class' own namespace" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/main.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
end
end
module Main
class Slice < Hanami::Slice
register_slice :nested, Admin::Slice
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main].slices[:nested]).to be Admin::Slice
end
end
specify "Registering a slice with a block creates a slice class and evals the block" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
register_slice :main do
register "greeting", "hello world"
end
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:main]).to be Main::Slice
expect(Main::Slice["greeting"]).to eq "hello world"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/dotenv_loading_spec.rb | spec/integration/dotenv_loading_spec.rb | # frozen_string_literal: true
# rubocop:disable Style/FetchEnvVar
RSpec.describe "Dotenv loading", :app_integration do
before do
@orig_env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@orig_env)
end
context "dotenv gem is available" do
before do
require "dotenv"
end
context "hanami env is development" do
it "loads .env.development.local, .env.local, .env.development and .env (in this order) into ENV", :aggregate_failures do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write ".env.development.local", <<~'TEXT'
FROM_SPECIFIC_ENV_LOCAL="from .env.development.local"
TEXT
write ".env.local", <<~'TEXT'
FROM_BASE_LOCAL="from .env.local"
FROM_SPECIFIC_ENV_LOCAL=nope
TEXT
write ".env.development", <<~'TEXT'
FROM_SPECIFIC_ENV="from .env.development"
FROM_SPECIFIC_ENV_LOCAL=nope
FROM_BASE_LOCAL=nope
TEXT
write ".env", <<~'TEXT'
FROM_BASE="from .env"
FROM_SPECIFIC_ENV_LOCAL=nope
FROM_BASE_LOCAL=nope
FROM_SPECIFIC_ENV=nope
TEXT
ENV["HANAMI_ENV"] = "development"
require "hanami/setup"
expect(ENV["FROM_SPECIFIC_ENV_LOCAL"]).to eq "from .env.development.local"
expect(ENV["FROM_BASE_LOCAL"]).to eq "from .env.local"
expect(ENV["FROM_SPECIFIC_ENV"]).to eq "from .env.development"
expect(ENV["FROM_BASE"]).to eq "from .env"
end
end
end
context "hanami env is test" do
it "loads .env.development.local, .env.development and .env (in this order) into ENV", :aggregate_failures do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write ".env.test.local", <<~'TEXT'
FROM_SPECIFIC_ENV_LOCAL="from .env.test.local"
TEXT
write ".env.local", <<~'TEXT'
FROM_BASE_LOCAL="from .env.local"
TEXT
write ".env.test", <<~'TEXT'
FROM_SPECIFIC_ENV="from .env.test"
FROM_SPECIFIC_ENV_LOCAL=nope
TEXT
write ".env", <<~'TEXT'
FROM_BASE="from .env"
FROM_SPECIFIC_ENV_LOCAL=nope
FROM_SPECIFIC_ENV=nope
TEXT
ENV["HANAMI_ENV"] = "test"
require "hanami/prepare"
expect(ENV["FROM_SPECIFIC_ENV_LOCAL"]).to eq "from .env.test.local"
expect(ENV["FROM_BASE_LOCAL"]).to be nil
expect(ENV["FROM_SPECIFIC_ENV"]).to eq "from .env.test"
expect(ENV["FROM_BASE"]).to eq "from .env"
end
end
end
end
context "dotenv gem is unavailable" do
before do
allow_any_instance_of(Object).to receive(:gem).and_call_original
allow_any_instance_of(Object).to receive(:gem).with("dotenv").and_raise(Gem::LoadError)
end
it "does not load from .env files" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write ".env", <<~'TEXT'
FOO=bar
TEXT
expect { require "hanami/prepare" }.not_to(change { ENV.to_h })
expect(ENV.key?("FOO")).to be false
end
end
end
end
# rubocop:enable Style/FetchEnvVar
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/rake_tasks_spec.rb | spec/integration/rake_tasks_spec.rb | # frozen_string_literal: true
require "rake"
require "hanami/cli/bundler"
RSpec.describe "Rake tasks", :app_integration do
describe "assets:precompile" do
before do
allow(Hanami).to receive(:bundled?)
allow(Hanami).to receive(:bundled?).with("hanami-assets").and_return(hanami_assets_bundled)
end
context "when hanami-assets is bundled" do
let(:hanami_assets_bundled) { true }
xit "compiles assets" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "Rakefile", <<~RUBY
# frozen_string_literal: true
require "hanami/rake_tasks"
RUBY
write "app/assets/js/app.js", <<~JS
console.log("Hello from index.js");
JS
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
expect_any_instance_of(Hanami::CLI::Bundler).to receive(:hanami_exec).with("assets compile").and_return(true)
Rake::Task["assets:precompile"].invoke
end
end
it "doesn't list the task" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "Rakefile", <<~RUBY
# frozen_string_literal: true
require "hanami/rake_tasks"
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
output = `bundle exec rake -T`
expect(output).to_not include("assets:precompile")
end
end
end
context "when hanami-assets is not bundled" do
let(:hanami_assets_bundled) { false }
it "raises error" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "Rakefile", <<~RUBY
# frozen_string_literal: true
require "hanami/rake_tasks"
RUBY
write "app/assets/js/app.js", <<~JS
console.log("Hello from index.js");
JS
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
expect { Rake::Task["assets:precompile"].invoke }.to raise_error do |exception|
expect(exception).to be_a(RuntimeError)
expect(exception.message).to match(/Don't know how to build task 'assets:precompile'/)
end
end
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/logging/notifications_spec.rb | spec/integration/logging/notifications_spec.rb | # frozen_string_literal: true
require "rack/test"
RSpec.describe "Logging / Notifications", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
specify "Request logging continues even when notifications bus has already been used" do
dir = Dir.mktmpdir
with_tmp_directory(dir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.actions.format :json
config.logger.options = {colorize: true}
config.logger.stream = config.root.join("test.log")
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
post "/users", to: "users.create"
end
end
RUBY
write "app/actions/users/create.rb", <<~RUBY
module TestApp
module Actions
module Users
class Create < Hanami::Action
def handle(req, resp)
resp.body = req.params.to_h.keys
end
end
end
end
end
RUBY
require "hanami/prepare"
# Simulate any component interacting with the notifications bus such that it creates its
# internal bus with a duplicate copy of all currently registered events. This means that the
# class-level Dry::Monitor::Notification events implicitly registered by the
# Dry::Monitor::Rack::Middleware activated via the rack provider are ignored, unless our
# provider explicitly re-registers them on _instance_ of the notifications bus.
#
# See Hanami::Providers::Rack for more detail.
Hanami.app["notifications"].instrument(:sql)
logs = -> { Pathname(dir).join("test.log").realpath.read }
post "/users", JSON.generate(name: "jane", password: "secret"), {"CONTENT_TYPE" => "application/json"}
expect(logs.()).to match %r{POST 200 \d+(µs|ms) 127.0.0.1 /}
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/logging/request_logging_spec.rb | spec/integration/logging/request_logging_spec.rb | # frozen_string_literal: true
require "json"
require "rack/test"
require "stringio"
RSpec.describe "Logging / Request logging", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
let(:logger_stream) { StringIO.new }
let(:logger_level) { nil }
let(:root) { make_tmp_directory }
def configure_logger
Hanami.app.config.logger.stream = logger_stream
Hanami.app.config.logger.level = logger_level if logger_level
end
def logs
@logs ||= (logger_stream.rewind and logger_stream.read)
end
def generate_app
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
end
before do
with_directory(root) do
generate_app
require "hanami/setup"
configure_logger
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "app router" do
def before_prepare
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
root to: ->(env) { [200, {}, ["OK"]] }
end
end
RUBY
end
it "logs the requests" do
get "/"
expect(logs.split("\n").length).to eq 1
expect(logs).to match %r{GET 200 \d+(µs|ms) 127.0.0.1 /}
end
context "production env" do
around do |example|
@prev_hanami_env = ENV["HANAMI_ENV"]
ENV["HANAMI_ENV"] = "production"
example.run
ensure
ENV["HANAMI_ENV"] = @prev_hanami_env
end
it "logs the requests as JSON" do
get "/"
expect(logs.split("\n").length).to eq 1
json = JSON.parse(logs, symbolize_names: true)
expect(json).to include(
verb: "GET",
path: "/",
ip: "127.0.0.1",
elapsed: Integer,
elapsed_unit: a_string_matching(/(µs|ms)/),
)
end
end
context "log level error" do
let(:logger_level) { :error }
before do
expect_any_instance_of(Hanami::Web::RackLogger).to_not receive(:data)
end
it "does not log info" do
get "/"
expect(logs.split("\n").length).to eq 0
end
end
end
describe "slice router" do
let(:app) { Main::Slice.rack_app }
def before_prepare
write "slices/main/config/routes.rb", <<~RUBY
module Main
class Routes < Hanami::Routes
root to: ->(env) { [200, {}, ["OK"]] }
end
end
RUBY
end
it "logs the requests" do
get "/"
expect(logs.split("\n").length).to eq 1
expect(logs).to match %r{GET 200 \d+(µs|ms) 127.0.0.1 /}
end
context "production env" do
around do |example|
@prev_hanami_env = ENV["HANAMI_ENV"]
ENV["HANAMI_ENV"] = "production"
example.run
ensure
ENV["HANAMI_ENV"] = @prev_hanami_env
end
it "logs the requests as JSON" do
get "/"
expect(logs.split("\n").length).to eq 1
json = JSON.parse(logs, symbolize_names: true)
expect(json).to include(
verb: "GET",
path: "/",
ip: "127.0.0.1",
elapsed: Integer,
elapsed_unit: a_string_matching(/(µs|ms)/),
)
end
end
end
context "when using ::Logger from Ruby stdlib" do
def generate_app
write "config/app.rb", <<~RUBY
require "logger"
require "pathname"
module TestApp
class App < Hanami::App
stream = Pathname.new(#{root.to_s.inspect}).join("log").tap(&:mkpath).join("test.log").to_s
config.logger = ::Logger.new(stream, progname: "custom-logger-app")
end
end
RUBY
end
def before_prepare
with_directory(root) do
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
root to: ->(env) { [200, {}, ["OK"]] }
end
end
RUBY
end
end
let(:logs) do
Pathname.new(root).join("log", "test.log").readlines
end
it "logs the requests with the payload serialized as JSON" do
get "/"
request_log = logs.last
# Expected log line follows the standard Logger structure:
#
# I, [2023-10-14T14:55:16.638753 #94836] INFO -- custom-logger-app: {"verb":"GET", ...}
expect(request_log).to match(%r{INFO -- custom-logger-app:})
# The log message should be JSON, after the progname
log_message = request_log.split("custom-logger-app: ").last
log_payload = JSON.parse(log_message, symbolize_names: true)
expect(log_payload).to include(
verb: "GET",
status: 200
)
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/logging/exception_logging_spec.rb | spec/integration/logging/exception_logging_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Logging / Exception logging", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
let(:logger_stream) { StringIO.new }
def configure_logger
Hanami.app.config.logger.stream = logger_stream
end
def logs
@logs ||= (logger_stream.rewind and logger_stream.read)
end
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
# Disable framework-level error rendering so we can test the raw action behavior
config.render_errors = false
config.render_detailed_errors = false
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
root to: "test"
end
end
RUBY
require "hanami/setup"
configure_logger
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "unhandled exceptions" do
def before_prepare
write "app/actions/test.rb", <<~RUBY
module TestApp
module Actions
class Test < Hanami::Action
UnhandledError = Class.new(StandardError)
def handle(request, response)
raise UnhandledError, "unhandled"
end
end
end
end
RUBY
end
it "logs a 500 error and full exception details when an exception is raised" do
# Make the request with a rescue so the raised exception doesn't crash the tests
begin
get "/"
rescue TestApp::Actions::Test::UnhandledError # rubocop:disable Lint/SuppressedException
end
expect(logs.lines.length).to be > 10
expect(logs).to match %r{GET 500 \d+(µs|ms) 127.0.0.1 /}
expect(logs).to include("unhandled (TestApp::Actions::Test::UnhandledError)")
if RUBY_VERSION < "3.4"
expect(logs).to include("app/actions/test.rb:7:in `handle'")
else
expect(logs).to include("app/actions/test.rb:7:in 'TestApp::Actions::Test#handle'")
end
end
it "re-raises the exception" do
expect { get "/" }.to raise_error(TestApp::Actions::Test::UnhandledError)
end
end
describe "errors handled by handle_exception" do
def before_prepare
write "app/actions/test.rb", <<~RUBY
module TestApp
module Actions
class Test < Hanami::Action
NotFoundError = Class.new(StandardError)
handle_exception NotFoundError => :handle_not_found_error
def handle(request, response)
raise NotFoundError
end
private
def handle_not_found_error(request, response, exception)
halt 404
end
end
end
end
RUBY
end
it "does not log an error" do
get "/"
expect(logs).to match %r{GET 404 \d+(µs|ms) 127.0.0.1 /}
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/settings/access_in_slice_class_body_spec.rb | spec/integration/settings/access_in_slice_class_body_spec.rb | # frozen_string_literal: true
RSpec.describe "Settings / Access within slice class bodies", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
context "app class" do
it "provides access to the settings inside the class body" do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
@some_flag = settings.some_flag
end
end
RUBY
write ".env", <<~'TEXT'
SOME_FLAG=true
TEXT
write "config/settings.rb", <<~'RUBY'
module TestApp
class Settings < Hanami::Settings
setting :some_flag
end
end
RUBY
require "hanami/setup"
expect(Hanami.app.instance_variable_get(:@some_flag)).to eq "true"
end
end
end
context "slice class" do
it "provides access to the settings inside the class body" do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/main.rb", <<~'RUBY'
module Main
class Slice < Hanami::Slice
@some_flag = settings.some_flag
end
end
RUBY
write ".env", <<~'TEXT'
SOME_FLAG=true
TEXT
write "slices/main/config/settings.rb", <<~'RUBY'
module Main
class Settings < Hanami::Settings
setting :some_flag
end
end
RUBY
require "hanami/prepare"
expect(Main::Slice.instance_variable_get(:@some_flag)).to eq "true"
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/settings/settings_component_loading_spec.rb | spec/integration/settings/settings_component_loading_spec.rb | # frozen_string_literal: true
RSpec.describe "Settings / Component loading", :app_integration do
describe "Settings are loaded from a class defined in config/settings.rb" do
specify "in app" do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/settings.rb", <<~'RUBY'
module TestApp
class Settings < Hanami::Settings
setting :foo
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app["settings"]).to be_an_instance_of TestApp::Settings
expect(Hanami.app["settings"]).to respond_to :foo
end
end
specify "in slice" do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/config/settings.rb", <<~'RUBY'
module Main
class Settings < Hanami::Settings
setting :foo
end
end
RUBY
require "hanami/prepare"
expect(Main::Slice["settings"]).to be_an_instance_of Main::Settings
expect(Main::Slice["settings"]).to respond_to :foo
end
end
end
describe "Settings are loaded from a `Settings` class if already defined" do
specify "in app" do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
require "hanami/settings"
module TestApp
class App < Hanami::App
end
class Settings < Hanami::Settings
setting :foo
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app["settings"]).to be_an_instance_of TestApp::Settings
expect(Hanami.app["settings"]).to respond_to :foo
end
end
specify "in slice" do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/main.rb", <<~'RUBY'
require "hanami/settings"
module Main
class Slice < Hanami::Slice
end
class Settings < Hanami::Settings
setting :foo
end
end
RUBY
require "hanami/prepare"
expect(Main::Slice["settings"]).to be_an_instance_of Main::Settings
expect(Main::Slice["settings"]).to respond_to :foo
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/settings/using_types_spec.rb | spec/integration/settings/using_types_spec.rb | # frozen_string_literal: true
require "hanami/settings"
RSpec.describe "Settings / Using types", :app_integration do
before do
@env = ENV.to_h
end
after do
ENV.replace(@env)
end
specify "types from a provided types module can be used as setting constructors to coerce values" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/settings.rb", <<~RUBY
module TestApp
class Settings < Hanami::Settings
Bool = Types::Params::Bool
setting :numeric, constructor: Types::Params::Integer
setting :flag, constructor: Bool
end
end
RUBY
ENV["NUMERIC"] = "42"
ENV["FLAG"] = "true"
require "hanami/prepare"
expect(Hanami.app["settings"].numeric).to eq 42
expect(Hanami.app["settings"].flag).to be true
end
end
specify "errors raised from setting constructors are collected and re-raised in aggregate, and will prevent the app from booting" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/settings.rb", <<~RUBY
module TestApp
class Settings < Hanami::Settings
setting :numeric, constructor: Types::Params::Integer
setting :flag, constructor: Types::Params::Bool
end
end
RUBY
ENV["NUMERIC"] = "never gonna"
ENV["FLAG"] = "give you up"
numeric_error = "numeric: invalid value for Integer"
flag_error = "flag: give you up cannot be coerced"
expect {
require "hanami/prepare"
}.to raise_error(
Hanami::Settings::InvalidSettingsError,
/#{numeric_error}.+#{flag_error}|#{flag_error}.+#{numeric_error}/m
)
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/settings/access_to_constants_spec.rb | spec/integration/settings/access_to_constants_spec.rb | # frozen_string_literal: true
RSpec.describe "Settings / Access to constants", :app_integration do
before do
@env = ENV.to_h
end
after do
ENV.replace(@env)
end
specify "Settings can not access autoloadable constants" do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/settings.rb", <<~'RUBY'
module TestApp
class Settings < Hanami::Settings
setting :some_flag, constructor: TestApp::Types::Params::Bool
end
end
RUBY
write "app/types.rb", <<~'RUBY'
# auto_register: false
require "dry/types"
module TestApp
Types = Dry.Types()
end
RUBY
require "hanami/setup"
expect { Hanami.app.settings }.to raise_error(NameError, /TestApp::Types/)
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/settings/loading_from_env_spec.rb | spec/integration/settings/loading_from_env_spec.rb | # frozen_string_literal: true
RSpec.describe "Settings / Access to constants", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
specify "settings are loaded from ENV" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/settings.rb", <<~'RUBY'
module TestApp
class Settings < Hanami::Settings
setting :database_url
end
end
RUBY
ENV["DATABASE_URL"] = "postgres://localhost/database"
require "hanami/prepare"
expect(Hanami.app["settings"].database_url).to eq "postgres://localhost/database"
end
end
describe "settings are loaded from .env files" do
context "hanami env is development" do
it "loads settings from .env.development.local, .env.local, .env.development and .env (in this order)" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/settings.rb", <<~'RUBY'
module TestApp
class Settings < Hanami::Settings
setting :from_specific_env_local
setting :from_base_local
setting :from_specific_env
setting :from_base
end
end
RUBY
write ".env.development.local", <<~'TEXT'
FROM_SPECIFIC_ENV_LOCAL="from .env.development.local"
TEXT
write ".env.local", <<~'TEXT'
FROM_BASE_LOCAL="from .env.local"
FROM_SPECIFIC_ENV_LOCAL=nope
TEXT
write ".env.development", <<~'TEXT'
FROM_SPECIFIC_ENV="from .env.development"
FROM_SPECIFIC_ENV_LOCAL=nope
FROM_BASE_LOCAL=nope
TEXT
write ".env", <<~'TEXT'
FROM_BASE="from .env"
FROM_SPECIFIC_ENV_LOCAL=nope
FROM_BASE_LOCAL=nope
FROM_SPECIFIC_ENV=nope
TEXT
ENV["HANAMI_ENV"] = "development"
require "hanami/prepare"
expect(Hanami.app["settings"].from_specific_env_local).to eq "from .env.development.local"
expect(Hanami.app["settings"].from_base_local).to eq "from .env.local"
expect(Hanami.app["settings"].from_specific_env).to eq "from .env.development"
expect(Hanami.app["settings"].from_base).to eq "from .env"
end
end
context "hanami env is test" do
it "loads settings from .env.development.local, .env.development and .env (in this order)" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/settings.rb", <<~'RUBY'
module TestApp
class Settings < Hanami::Settings
setting :from_specific_env_local
setting :from_base_local
setting :from_specific_env
setting :from_base
end
end
RUBY
write ".env.test.local", <<~'TEXT'
FROM_SPECIFIC_ENV_LOCAL="from .env.test.local"
TEXT
write ".env.local", <<~'TEXT'
FROM_BASE_LOCAL="from .env.local"
TEXT
write ".env.test", <<~'TEXT'
FROM_SPECIFIC_ENV="from .env.test"
FROM_SPECIFIC_ENV_LOCAL=nope
TEXT
write ".env", <<~'TEXT'
FROM_BASE="from .env"
FROM_SPECIFIC_ENV_LOCAL=nope
FROM_SPECIFIC_ENV=nope
TEXT
ENV["HANAMI_ENV"] = "test"
require "hanami/prepare"
expect(Hanami.app["settings"].from_specific_env_local).to eq "from .env.test.local"
expect(Hanami.app["settings"].from_base_local).to be nil
expect(Hanami.app["settings"].from_specific_env).to eq "from .env.test"
expect(Hanami.app["settings"].from_base).to eq "from .env"
end
end
end
end
end
it "prefers ENV values are preferred over .env files" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/settings.rb", <<~'RUBY'
module TestApp
class Settings < Hanami::Settings
setting :database_url
end
end
RUBY
write ".env", <<~'TEXT'
DATABASE_URL=nope
TEXT
ENV["DATABASE_URL"] = "postgres://localhost/database"
require "hanami/prepare"
expect(Hanami.app["settings"].database_url).to eq "postgres://localhost/database"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/settings/slice_registration_spec.rb | spec/integration/settings/slice_registration_spec.rb | # frozen_string_literal: true
RSpec.describe "Settings / Slice registration", :app_integration do
specify "Settings are registered for each slice with a settings file" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
# n.b. no app-level settings file
# The main slice has settings
write "slices/main/config/settings.rb", <<~RUBY
# frozen_string_literal: true
require "hanami/settings"
module Main
class Settings < Hanami::Settings
setting :main_session_secret
end
end
RUBY
# The admin slice has none
write "slices/admin/.keep", ""
require "hanami/prepare"
expect(Main::Slice.key?("settings")).to be true
expect(Main::Slice["settings"]).to respond_to :main_session_secret
expect(Admin::Slice.key?("settings")).to be false
end
end
describe "App settings are shared with slices if no local settings are defined" do
context "prepared" do
specify do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/settings.rb", <<~'RUBY'
# frozen_string_literal: true
require "hanami/settings"
module TestApp
class Settings < Hanami::Settings
setting :app_session_secret
end
end
RUBY
write "slices/main/config/settings.rb", <<~RUBY
# frozen_string_literal: true
require "hanami/settings"
module Main
class Settings < Hanami::Settings
setting :main_session_secret
end
end
RUBY
write "slices/admin/.keep", ""
require "hanami/prepare"
expect(TestApp::App.key?("settings")).to be true
expect(Main::Slice.key?("settings")).to be true
expect(Admin::Slice.key?("settings")).to be true
expect(TestApp::App["settings"]).to respond_to :app_session_secret
expect(Main::Slice["settings"]).to respond_to :main_session_secret
expect(Admin::Slice["settings"]).to respond_to :app_session_secret
end
end
end
context "booted" do
specify do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/settings.rb", <<~'RUBY'
# frozen_string_literal: true
require "hanami/settings"
module TestApp
class Settings < Hanami::Settings
setting :app_session_secret
end
end
RUBY
write "slices/main/config/settings.rb", <<~RUBY
# frozen_string_literal: true
require "hanami/settings"
module Main
class Settings < Hanami::Settings
setting :main_session_secret
end
end
RUBY
write "slices/admin/.keep", ""
require "hanami/boot"
expect(TestApp::App.key?("settings")).to be true
expect(Main::Slice.key?("settings")).to be true
expect(Admin::Slice.key?("settings")).to be true
expect(TestApp::App["settings"]).to respond_to :app_session_secret
expect(Main::Slice["settings"]).to respond_to :main_session_secret
expect(Admin::Slice["settings"]).to respond_to :app_session_secret
end
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/container/standard_providers_spec.rb | spec/integration/container/standard_providers_spec.rb | RSpec.describe "Container / Standard providers", :app_integration do
specify "Standard components are available on booted container" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
require "hanami/setup"
Hanami.boot
expect(Hanami.app.key?(:settings)).to be false
expect(Hanami.app["inflector"]).to eql Hanami.app.inflector
expect(Hanami.app["logger"]).to be_a_kind_of(Dry::Logger::Dispatcher)
expect(Hanami.app["rack.monitor"]).to be_a_kind_of(Dry::Monitor::Rack::Middleware)
end
end
specify "Standard components are resolved lazily on non-booted container" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
require "hanami/setup"
Hanami.prepare
expect(Hanami.app.key?(:settings)).to be false
expect(Hanami.app["inflector"]).to eql Hanami.app.inflector
expect(Hanami.app["logger"]).to be_a_kind_of(Dry::Logger::Dispatcher)
expect(Hanami.app["rack.monitor"]).to be_a_kind_of(Dry::Monitor::Rack::Middleware)
end
end
specify "Settings component is available when settings are defined" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/settings.rb", <<~RUBY
require "hanami/settings"
module TestApp
class Settings < Hanami::Settings
setting :session_secret
end
end
RUBY
require "hanami/setup"
Hanami.boot
expect(Hanami.app.key?(:settings)).to be true
expect(Hanami.app[:settings]).to respond_to :session_secret
end
end
specify "Standard components can be replaced by custom bootable components (on booted container)" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/providers/logger.rb", <<~RUBY
Hanami.app.register_provider :logger do
start do
register :logger, "custom logger"
end
end
RUBY
require "hanami/setup"
Hanami.boot
expect(Hanami.app[:logger]).to eq "custom logger"
end
end
specify "Standard components can be replaced by custom bootable components resolved lazily (on non-booted container)" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/providers/logger.rb", <<~RUBY
Hanami.app.register_provider :logger do
start do
register :logger, "custom logger"
end
end
RUBY
require "hanami/setup"
Hanami.prepare
expect(Hanami.app[:logger]).to eq "custom logger"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/container/application_routes_helper_spec.rb | spec/integration/container/application_routes_helper_spec.rb | # frozen_string_literal: true
require "stringio"
RSpec.describe "App routes helper", :app_integration do
specify "Routing to actions based on their container identifiers" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
root to: "home.index"
end
end
RUBY
write "app/actions/home/index.rb", <<~RUBY
require "hanami/action"
module TestApp
module Actions
module Home
class Index < Hanami::Action
def handle(*, res)
res.body = "Hello world"
end
end
end
end
end
RUBY
require "hanami/prepare"
expect(TestApp::App["routes"].path(:root)).to eq "/"
expect(TestApp::App["routes"].url(:root).to_s).to match /http:\/\/.*\//
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/container/autoloader_spec.rb | spec/integration/container/autoloader_spec.rb | RSpec.describe "App autoloader", :app_integration do
specify "Classes are autoloaded through direct reference, including through components resolved from the container" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
# Use a custom inflection to ensure this is respected by the autoloader
config.inflections do |inflections|
inflections.acronym "NBA"
end
end
end
RUBY
write "lib/non_app/thing.rb", <<~RUBY
module NonApp
class Thing
end
end
RUBY
write "lib/test_app/nba_jam/get_that_outta_here.rb", <<~RUBY
module TestApp
module NBAJam
class GetThatOuttaHere
end
end
end
RUBY
write "slices/admin/lib/operations/create_game.rb", <<~RUBY
module Admin
module Operations
class CreateGame
def call
Entities::Game.new
end
end
end
end
RUBY
write "slices/admin/lib/entities/game.rb", <<~RUBY
# auto_register: false
module Admin
module Entities
class Game
end
end
end
RUBY
write "slices/admin/lib/entities/quarter.rb", <<~RUBY
# auto_register: false
module Admin
module Entities
class Quarter
end
end
end
RUBY
require "hanami/prepare"
expect(require("non_app/thing")).to be true
expect(NonApp::Thing).to be
expect(TestApp::NBAJam::GetThatOuttaHere).to be
expect(TestApp::App.autoloader.tag).to eq("hanami.app.test_app")
expect(Admin::Slice["operations.create_game"]).to be_an_instance_of(Admin::Operations::CreateGame)
expect(Admin::Slice["operations.create_game"].call).to be_an_instance_of(Admin::Entities::Game)
expect(Admin::Entities::Quarter).to be
expect(Admin::Slice.autoloader.tag).to eq("hanami.slices.admin")
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/container/imports_spec.rb | spec/integration/container/imports_spec.rb | # frozen_string_literal: true
RSpec.describe "Container imports", :app_integration do
xspecify "App container is imported into slice containers by default" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
end
end
RUBY
require "hanami/setup"
Hanami.prepare
shared_service = Object.new
TestApp::App.register("shared_service", shared_service)
Hanami.boot
expect(Admin::Slice["shared_service"]).to be shared_service
end
end
specify "Slices can import other slices" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
import from: :search
end
end
RUBY
write "slices/search/lib/index_entity.rb", <<~RUBY
module Search
class IndexEntity
end
end
RUBY
require "hanami/boot"
expect(Admin::Slice["search.index_entity"]).to be_a Search::IndexEntity
# Ensure a slice's imported components (e.g. from "app") are not then
# exported again when that slice is imported, which would result in redundant
# components
expect(Search::Slice.key?("logger")).to be true
expect(Admin::Slice.key?("logger")).to be true
expect(Admin::Slice.key?("search.logger")).to be false
end
end
specify "Slices can import specific components from other slices" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
import(
keys: ["query"],
from: :search
)
end
end
RUBY
write "slices/search/lib/index_entity.rb", <<~RUBY
module Search
class IndexEntity; end
end
RUBY
write "slices/search/lib/query.rb", <<~RUBY
module Search
class Query; end
end
RUBY
require "hanami/setup"
Hanami.boot
expect(Admin::Slice["search.query"]).to be_a Search::Query
end
end
specify "Slices can import from other slices with a custom import key namespace" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
import(
keys: ["query"],
from: :search,
as: :search_engine
)
end
end
RUBY
write "slices/search/lib/index_entity.rb", <<~RUBY
module Search
class IndexEntity; end
end
RUBY
write "slices/search/lib/query.rb", <<~RUBY
module Search
class Query; end
end
RUBY
require "hanami/boot"
expect(Admin::Slice["search_engine.query"]).to be_a Search::Query
end
end
specify "Imported components from another slice are lazily resolved in unbooted apps" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
import from: :search
end
end
RUBY
write "slices/admin/lib/admin/test_op.rb", <<~RUBY
module Admin
class TestOp
end
end
RUBY
write "slices/search/lib/index_entity.rb", <<~RUBY
module Search
class IndexEntity
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app).not_to be_booted
expect(Admin::Slice.keys).not_to include "search.index_entity"
expect(Admin::Slice["search.index_entity"]).to be_a Search::IndexEntity
expect(Admin::Slice.keys).to include "search.index_entity"
expect(Admin::Slice).not_to be_booted
expect(Admin::Slice.container).not_to be_finalized
expect(Search::Slice).not_to be_booted
expect(Search::Slice.container).not_to be_finalized
end
end
specify "Slices can configure specific exports" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
import(
keys: %w[index_entity query],
from: :search
)
end
end
RUBY
write "config/slices/search.rb", <<~RUBY
module Search
class Slice < Hanami::Slice
export(%w[query])
end
end
RUBY
write "slices/search/lib/index_entity.rb", <<~RUBY
module Search
class IndexEntity; end
end
RUBY
write "slices/search/lib/query.rb", <<~RUBY
module Search
class Query; end
end
RUBY
require "hanami/setup"
Hanami.boot
expect(Admin::Slice.key?("search.query")).to be true
expect(Admin::Slice.key?("search.index_entity")).to be false
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/container/auto_injection_spec.rb | spec/integration/container/auto_injection_spec.rb | # frozen_string_literal: true
RSpec.describe "Container auto-injection (aka \"Deps\") mixin", :app_integration do
# rubocop:disable Metrics/MethodLength
def with_app
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/some_service.rb", <<~'RUBY'
module TestApp
class SomeService
end
end
RUBY
write "app/some_operation.rb", <<~'RUBY'
module TestApp
class SomeOperation
include Deps["some_service"]
end
end
RUBY
yield
end
end
# rubocop:enable Metrics/MethodLength
specify "Dependencies are auto-injected in a booted app" do
with_app do
require "hanami/boot"
op = TestApp::App["some_operation"]
expect(op.some_service).to be_a TestApp::SomeService
end
end
specify "Dependencies are lazily resolved and auto-injected in an unbooted app" do
with_app do
require "hanami/prepare"
op = TestApp::App["some_operation"]
expect(op.some_service).to be_a TestApp::SomeService
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/container/provider_lifecycle_spec.rb | spec/integration/container/provider_lifecycle_spec.rb | # frozen_string_literal: true
RSpec.describe "Container / Provider lifecycle", :app_integration do
let!(:slice) {
module TestApp
class App < Hanami::App
register_provider :connection do
prepare do
module ::TestApp
class Connection
def initialize
@connected = true
end
def disconnect
@connected = false
end
def connected?
@connected
end
end
end
end
start do
register("connection", TestApp::Connection.new)
end
stop do
container["connection"].disconnect
end
end
end
end
TestApp::App
}
before do
require "hanami/setup"
end
specify "individual providers can be prepared, started and stopped" do
expect { TestApp::Connection }.to raise_error NameError
slice.prepare :connection
expect(TestApp::Connection).to be
expect(slice.container.registered?("connection")).to be false
slice.start :connection
expect(slice.container.registered?("connection")).to be true
expect(slice["connection"]).to be_connected
slice.stop :connection
expect(slice["connection"]).not_to be_connected
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/container/prepare_container_spec.rb | spec/integration/container/prepare_container_spec.rb | # frozen_string_literal: true
RSpec.describe "Container / prepare_container", :app_integration do
# (Most of) the examples below make their expectations on a `container_to_prepare`,
# which is the container yielded to the `Slice.prepare_container` block _at the moment
# it is called_.
#
# This around hook ensures the examples are run at the right time and container is
# available to each.
around(in_prepare_container: true) do |example|
# Eagerly capture @loaded_features here (see spec/support/app_integration.rb) since
# around hooks are run before any before hooks (where we ordinarily capture
# @loaded_features), and by invoking `example_group_instance.subject` below, we're
# making requires that we want to ensure are properly cleaned between examples.
@loaded_features = $LOADED_FEATURES.dup
slice = example.example_group_instance.subject
slice.prepare_container do |container|
example.example.example_group.let(:container_to_prepare) { container }
example.run
end
# The prepare_container block is called when the slice is prepared
slice.prepare
autoloaders_teardown!
end
describe "in app", :in_prepare_container do
before :context do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/.keep", ""
end
end
subject {
with_directory(@dir) { require "hanami/setup" }
Hanami.app
}
it "receives the container for the app" do
expect(container_to_prepare).to be TestApp::Container
end
specify "the container has been already configured by the app" do
expect(container_to_prepare.config.component_dirs.dir("app")).to be
end
specify "the container is not yet marked as configured" do
expect(container_to_prepare).not_to be_configured
end
describe "after app is prepared", in_prepare_container: false do
before do
subject.prepare_container do |container|
container.config.name = :custom_name
end
end
it "preserves any container configuration changes made via the block" do
expect { subject.prepare }
.to change { subject.container.config.name }
.to :custom_name
expect(subject.container).to be_configured
end
end
end
describe "in slice", :in_prepare_container do
before :context do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/.keep", ""
end
end
subject {
with_directory(@dir) { require "hanami/setup" }
Hanami.app.register_slice(:main)
}
it "receives the container for the slice" do
expect(container_to_prepare).to be Main::Container
end
specify "the container has been already configured by the slice" do
expect(container_to_prepare.config.component_dirs.dir("")).to be
end
specify "the container is not yet marked as configured" do
expect(container_to_prepare).not_to be_configured
end
describe "after slice is prepared", in_prepare_container: false do
before do
subject.prepare_container do |container|
container.config.name = :custom_name
end
end
it "preserves any container configuration changes made via the block" do
expect { subject.prepare }
.to change { subject.container.config.name }
.to :custom_name
expect(subject.container).to be_configured
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/container/shutdown_spec.rb | spec/integration/container/shutdown_spec.rb | # frozen_string_literal: true
RSpec.describe "App shutdown", :app_integration do
specify "App shutdown stops providers in both the app and slices" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
# frozen_string_literal: true
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/providers/connection.rb", <<~RUBY
# frozen_string_literal: true
Hanami.app.register_provider :connection do
prepare do
module TestApp
class Connection
attr_reader :connected
def initialize
@connected = true
end
def disconnect
@connected = false
end
end
end
end
start do
register("connection", TestApp::Connection.new)
end
stop do
container["connection"].disconnect
end
end
RUBY
write "slices/main/config/providers/connection.rb", <<~RUBY
# frozen_string_literal: true
Main::Slice.register_provider :connection do
prepare do
module Main
class Connection
attr_reader :connected
def initialize
@connected = true
end
def disconnect
@connected = false
end
end
end
end
start do
register "connection", Main::Connection.new
end
stop do
container["connection"].disconnect
end
end
RUBY
require "hanami/boot"
app_connection = Hanami.app["connection"]
slice_connection = Main::Slice["connection"]
expect(app_connection.connected).to be true
expect(slice_connection.connected).to be true
Hanami.shutdown
expect(app_connection.connected).to be false
expect(slice_connection.connected).to be false
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/container/auto_registration_spec.rb | spec/integration/container/auto_registration_spec.rb | # frozen_string_literal: true
RSpec.describe "Container auto-registration", :app_integration do
specify "Auto-registering files in slice source directories" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.inflections do |inflections|
inflections.acronym "NBA"
end
end
end
RUBY
write "app/action.rb", <<~RUBY
# auto_register: false
require "hanami/action"
module TestApp
class Action < Hanami::Action
end
end
RUBY
write "app/actions/nba_rosters/index.rb", <<~RUBY
module TestApp
module Actions
module NBARosters
class Index < TestApp::Action
end
end
end
end
RUBY
write "slices/admin/lib/nba_jam/get_that_outta_here.rb", <<~RUBY
module Admin
module NBAJam
class GetThatOuttaHere
end
end
end
RUBY
require "hanami/setup"
Hanami.boot
expect(TestApp::App["actions.nba_rosters.index"]).to be_an TestApp::Actions::NBARosters::Index
expect(Admin::Slice["nba_jam.get_that_outta_here"]).to be_an Admin::NBAJam::GetThatOuttaHere
end
end
it "Unbooted app resolves components lazily from the lib/ directories" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.inflections do |inflections|
inflections.acronym "NBA"
end
end
end
RUBY
write "slices/admin/lib/nba_jam/get_that_outta_here.rb", <<~RUBY
module Admin
module NBAJam
class GetThatOuttaHere
end
end
end
RUBY
require "hanami/prepare"
expect(Admin::Slice.keys).not_to include("nba_jam.get_that_outta_here")
expect(Admin::Slice["nba_jam.get_that_outta_here"]).to be_an Admin::NBAJam::GetThatOuttaHere
expect(Admin::Slice.keys).to include("nba_jam.get_that_outta_here")
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/container/provider_environment_spec.rb | spec/integration/container/provider_environment_spec.rb | # frozen_string_literal: true
RSpec.describe "Container / Provider environment", :app_integration do
let!(:app) {
module TestApp
class App < Hanami::App
class << self
attr_accessor :test_provider_target
end
end
end
before_prepare if respond_to?(:before_prepare)
Hanami.app.prepare
Hanami.app
}
context "app provider" do
before do
Hanami.app.register_provider :test_provider, namespace: true do
start do
Hanami.app.test_provider_target = target
end
end
end
it "exposes the app as the provider target" do
Hanami.app.start :test_provider
expect(Hanami.app.test_provider_target).to be Hanami.app
end
end
context "slice provider" do
def before_prepare
Hanami.app.register_slice :main
end
before do
Main::Slice.register_provider :test_provider, namespace: true do
start do
Hanami.app.test_provider_target = target
end
end
end
it "exposes the slice as the provider target" do
Main::Slice.start :test_provider
expect(Hanami.app.test_provider_target).to be Main::Slice
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/container/standard_providers/rack_provider_spec.rb | spec/integration/container/standard_providers/rack_provider_spec.rb | RSpec.describe "Container / Standard providers / Rack", :app_integration do
specify "Rack provider is loaded when rack is bundled" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/.keep", ""
require "hanami/prepare"
expect(Hanami.app["rack.monitor"]).to be_a_kind_of(Dry::Monitor::Rack::Middleware)
expect(Main::Slice["rack.monitor"]).to be_a_kind_of(Dry::Monitor::Rack::Middleware)
end
end
specify "Rack provider is not loaded when rack is not bundled" do
allow(Hanami).to receive(:bundled?).and_call_original
allow(Hanami).to receive(:bundled?).with("rack").and_return false
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/.keep", ""
require "hanami/prepare"
expect(Hanami.app.key?("rack.monitor")).to be false
expect(Main::Slice.key?("rack.monitor")).to be false
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/slices_importing_from_parent.rb | spec/integration/db/slices_importing_from_parent.rb | # frozen_string_literal: true
RSpec.describe "DB / Slices / Importing from app", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
specify "app DB components do not import into slices by default" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "slices/admin/.keep", ""
require "hanami/prepare"
expect { Admin::Slice.start :db }.to raise_error Dry::System::ProviderNotFoundError
end
end
specify "importing app DB components into slices via config.db.import_from_parent = true" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.db.import_from_parent = true
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "slices/admin/.keep", ""
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
Hanami.app.prepare :db
# Manually run a migration and add a test record
gateway = Hanami.app["db.gateway"]
migration = gateway.migration do
change do
# drop_table? :posts
create_table :posts do
primary_key :id
column :title, :text, null: false
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
Admin::Slice.start :db
expect(Admin::Slice["db.rom"]).to be(Hanami.app["db.rom"])
expect(Admin::Slice["relations.posts"]).to be(Hanami.app["relations.posts"])
expect(Admin::Slice["relations.posts"].to_a).to eq [{id: 1, title: "Together breakfast"}]
end
end
specify "disabling import of the DB components within a specific slice" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.db.import_from_parent = true
end
end
RUBY
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
config.db.import_from_parent = false
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
require "hanami/prepare"
expect { Admin::Slice.start :db }.to raise_error Dry::System::ProviderNotFoundError
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/provider_spec.rb | spec/integration/db/provider_spec.rb | # frozen_string_literal: true
RSpec.describe "DB / Provider", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
it "is registered when only a config/db/ dir exists" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/db/.keep", ""
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
Hanami.app.prepare :db
expect(Hanami.app["db.gateway"]).to be
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/db_slices_spec.rb | spec/integration/db/db_slices_spec.rb | # frozen_string_literal: true
RSpec.describe "DB / Slices", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
specify "slices using the same database_url and extensions share a gateway/connection" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "slices/admin/relations/.keep", ""
write "slices/main/relations/.keep", ""
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
expect(Admin::Slice["db.rom"].gateways[:default]).to be Main::Slice["db.rom"].gateways[:default]
end
end
specify "slices using a parent gateway with connection options share a gateway/connection" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
config.gateway :default do |gw|
gw.connection_options timeout: 10_000
end
config.gateway :extra do |gw|
gw.connection_options timeout: 20_000
end
end
RUBY
write "slices/main/config/providers/db.rb", <<~RUBY
Main::Slice.configure_provider :db do
config.gateway :bonus do |gw|
gw.connection_options timeout: 5_000
end
end
RUBY
write "db/.keep", ""
write "slices/admin/relations/.keep", ""
write "slices/main/relations/.keep", ""
ENV["DATABASE_URL"] = "sqlite://" + Pathname(@dir).realpath.join("app.sqlite").to_s
ENV["DATABASE_URL__EXTRA"] = "sqlite://" + Pathname(@dir).realpath.join("extra.sqlite").to_s
ENV["DATABASE_URL__BONUS"] = "sqlite://" + Pathname(@dir).realpath.join("bonus.sqlite").to_s
# "extra" gateway in admin slice, same URL as app
ENV["ADMIN__DATABASE_URL__EXTRA"] = ENV["DATABASE_URL__EXTRA"]
# "extra" gatway in main slice, different URL
ENV["MAIN__DATABASE_URL__EXTRA"] = "sqlite://" + Pathname(@dir).realpath.join("extra-main.sqlite").to_s
# "bonus" gateway in admin slice, same URL as app
ENV["ADMIN__DATABASE_URL__BONUS"] = ENV["DATABASE_URL__BONUS"]
# "bonus" gateway in main slice, same URL as app; different connection options in provider
ENV["MAIN__DATABASE_URL__BONUS"] = ENV["DATABASE_URL__BONUS"]
require "hanami/prepare"
expect(Admin::Slice["db.gateway"]).to be Hanami.app["db.gateway"]
expect(Admin::Slice["db.gateways.extra"]).to be Hanami.app["db.gateways.extra"]
expect(Main::Slice["db.gateways.extra"]).not_to be Hanami.app["db.gateways.extra"]
expect(Admin::Slice["db.gateways.bonus"]).to be Hanami.app["db.gateways.bonus"]
expect(Main::Slice["db.gateways.bonus"]).not_to be Hanami.app["db.gateways.bonus"]
end
end
specify "slices using the same database_url but different extensions have distinct gateways/connections" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "slices/admin/config/providers/db.rb", <<~RUBY
Admin::Slice.configure_provider :db do
config.adapter :sql do |a|
a.extensions.clear
end
end
RUBY
write "slices/main/config/providers/db.rb", <<~RUBY
Main::Slice.configure_provider :db do
config.adapter :sql do |a|
a.extensions.clear
a.extension :error_sql
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
# Different gateways, due to the distinct extensions
expect(Admin::Slice["db.rom"].gateways[:default]).not_to be Main::Slice["db.rom"].gateways[:default]
# Even though their URIs are the same
expect(Admin::Slice["db.rom"].gateways[:default].connection.opts[:uri])
.to eq Main::Slice["db.rom"].gateways[:default].connection.opts[:uri]
end
end
specify "using separate relations per slice, while sharing config from the app" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
config.adapter :sql do |a|
a.extension :exclude_or_null
end
end
RUBY
write "slices/admin/relations/posts.rb", <<~RUBY
module Admin
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "slices/admin/relations/authors.rb", <<~RUBY
module Admin
module Relations
class Authors < Hanami::DB::Relation
schema :authors, infer: true
end
end
end
RUBY
write "slices/main/config/providers/db.rb", <<~RUBY
Main::Slice.configure_provider :db do
config.adapter :sql do |a|
a.skip_defaults :extensions
a.extensions.clear
end
end
RUBY
write "slices/main/relations/posts.rb", <<~RUBY
module Main
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite://" + Pathname(@dir).realpath.join("database.db").to_s
# Extra gateway for app only. Unlike other config, not copied to child slices.
ENV["DATABASE_URL__EXTRA"] = "sqlite://" + Pathname(@dir).realpath.join("extra.db").to_s
require "hanami/prepare"
Main::Slice.prepare :db
expect(Main::Slice["db.config"]).to be_an_instance_of ROM::Configuration
expect(Main::Slice["db.gateway"]).to be_an_instance_of ROM::SQL::Gateway
expect(Admin::Slice.registered?("db.config")).to be false
Admin::Slice.prepare :db
expect(Admin::Slice["db.config"]).to be_an_instance_of ROM::Configuration
expect(Admin::Slice["db.gateway"]).to be_an_instance_of ROM::SQL::Gateway
# Manually run a migration and add a test record
gateway = Admin::Slice["db.gateway"]
migration = gateway.migration do
change do
create_table :posts do
primary_key :id
column :title, :text, null: false
end
create_table :authors do
primary_key :id
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
# Gateways on app are not passed down to child slices
expect(Hanami.app["db.rom"].gateways.keys).to eq [:default, :extra]
expect(Main::Slice["db.rom"].gateways.keys).to eq [:default]
expect(Admin::Slice["db.rom"].gateways.keys).to eq [:default]
# Admin slice has appropriate relations registered, and can access data
expect(Admin::Slice["db.rom"].relations[:posts].to_a).to eq [{id: 1, title: "Together breakfast"}]
expect(Admin::Slice["relations.posts"]).to be Admin::Slice["db.rom"].relations[:posts]
expect(Admin::Slice["relations.authors"]).to be Admin::Slice["db.rom"].relations[:authors]
# Main slice can access data, and only has its own relations (no crossover from admin slice)
expect(Main::Slice["db.rom"].relations[:posts].to_a).to eq [{id: 1, title: "Together breakfast"}]
expect(Main::Slice["relations.posts"]).to be Main::Slice["db.rom"].relations[:posts]
expect(Main::Slice["db.rom"].relations.elements.keys).not_to include :authors
expect(Main::Slice["relations.posts"]).not_to be Admin::Slice["relations.posts"]
# Config in the app's db provider is copied to child slice providers
expect(Admin::Slice["db.gateway"].options[:extensions]).to eq [
:exclude_or_null,
:caller_logging,
:error_sql,
:sql_comments,
]
# Except when it has been explicitly configured in a child slice provider
expect(Main::Slice["db.gateway"].options[:extensions]).to eq []
# Plugins configured in the app's db provider are copied to child slice providers
expect(Admin::Slice["db.config"].setup.plugins.length).to eq 2
expect(Admin::Slice["db.config"].setup.plugins).to include an_object_satisfying { |plugin|
plugin.type == :relation && plugin.name == :auto_restrictions
}
expect(Admin::Slice["db.config"].setup.plugins).to include an_object_satisfying { |plugin|
plugin.type == :relation && plugin.name == :instrumentation
}
expect(Main::Slice["db.config"].setup.plugins).to eq Admin::Slice["db.config"].setup.plugins
end
end
specify "disabling sharing of config from the app" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
config.adapter :sql do |a|
a.extension :exclude_or_null
end
end
RUBY
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
config.db.configure_from_parent = false
end
end
RUBY
write "slices/admin/config/providers/db.rb", <<~RUBY
Admin::Slice.configure_provider :db do
end
RUBY
ENV["DATABASE_URL"] = "sqlite://" + Pathname(@dir).realpath.join("database.db").to_s
require "hanami/prepare"
expect(Admin::Slice["db.gateway"].options[:extensions]).not_to include :exclude_or_null
end
end
specify "slices using separate databases" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "slices/admin/relations/posts.rb", <<~RUBY
module Admin
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "slices/admin/slices/super/relations/posts.rb", <<~RUBY
module Admin
module Super
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
end
RUBY
write "slices/main/relations/posts.rb", <<~RUBY
module Main
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
ENV["ADMIN__DATABASE_URL"] = "sqlite://" + Pathname(@dir).realpath.join("admin.db").to_s
ENV["ADMIN__SUPER__DATABASE_URL"] = "sqlite://" + Pathname(@dir).realpath.join("admin_super.db").to_s
ENV["MAIN__DATABASE_URL"] = "sqlite://" + Pathname(@dir).realpath.join("main.db").to_s
require "hanami/prepare"
Admin::Slice.prepare :db
Admin::Super::Slice.prepare :db
Main::Slice.prepare :db
# Manually run a migration and add a test record in each slice's database
gateways = [
Admin::Slice["db.gateway"],
Admin::Super::Slice["db.gateway"],
Main::Slice["db.gateway"]
]
gateways.each do |gateway|
migration = gateway.migration do
change do
create_table :posts do
primary_key :id
column :title, :text, null: false
end
create_table :authors do
primary_key :id
end
end
end
migration.apply(gateway, :up)
end
gateways[0].connection.execute("INSERT INTO posts (title) VALUES ('Gem glow')")
gateways[1].connection.execute("INSERT INTO posts (title) VALUES ('Cheeseburger backpack')")
gateways[2].connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
expect(Admin::Slice["relations.posts"].to_a).to eq [{id: 1, title: "Gem glow"}]
expect(Admin::Super::Slice["relations.posts"].to_a).to eq [{id: 1, title: "Cheeseburger backpack"}]
expect(Main::Slice["relations.posts"].to_a).to eq [{id: 1, title: "Together breakfast"}]
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/provider_config_spec.rb | spec/integration/db/provider_config_spec.rb | # frozen_string_literal: true
RSpec.describe "DB / Provider / Config", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
describe "default config" do
it "provides default plugins and extensions" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/db/.keep", ""
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
Hanami.app.prepare :db
plugins = Hanami.app["db.config"].setup.plugins
expect(plugins).to match [
an_object_satisfying {
_1.name == :instrumentation && _1.type == :relation &&
_1.config.notifications == Hanami.app["notifications"]
},
an_object_satisfying { _1.name == :auto_restrictions && _1.type == :relation }
]
extensions = Hanami.app["db.gateway"].options[:extensions]
expect(extensions).to eq [:caller_logging, :error_sql, :sql_comments]
end
end
end
it "evaluates plugin config blocks in the context of the provider" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
config.adapter :sql do |a|
a.skip_defaults :plugins
a.plugin relations: :instrumentation do |plugin|
plugin.notifications = target["custom_notifications"]
end
end
end
RUBY
write "app/custom_notifications.rb", <<~RUBY
module TestApp
class CustomNotifications
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
Hanami.app.prepare :db
plugin = Hanami.app["db.config"].setup.plugins.find { _1.name == :instrumentation }
expect(plugin.config.notifications).to be_an_instance_of TestApp::CustomNotifications
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/repo_spec.rb | spec/integration/db/repo_spec.rb | # frozen_string_literal: true
RSpec.describe "DB / Repo", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
specify "repos have a root inferred from their name, or can set their own" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/repo.rb", <<~RUBY
module TestApp
class Repo < Hanami::DB::Repo
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "app/repos/post_repo.rb", <<~RUBY
module TestApp
module Repos
class PostRepo < Repo
def get(id)
posts.by_pk(id).one!
end
end
end
end
RUBY
write "app/repos/no_implicit_root_relation_repo.rb", <<~RUBY
module TestApp
module Repos
class NoImplicitRootRelationRepo < Repo
end
end
end
RUBY
write "app/repos/explicit_root_relation_repo.rb", <<~RUBY
module TestApp
module Repos
class ExplicitRootRelationRepo < Repo[:posts]
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
Hanami.app.prepare :db
# Manually run a migration and add a test record
gateway = Hanami.app["db.gateway"]
migration = gateway.migration do
change do
# drop_table? :posts
create_table :posts do
primary_key :id
column :title, :text, null: false
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
# Repos use a matching root relation automatically
repo = Hanami.app["repos.post_repo"]
expect(repo.get(1).title).to eq "Together breakfast"
expect(repo.root).to eql Hanami.app["relations.posts"]
# Non-matching repos still work, just with no root relation
repo = Hanami.app["repos.no_implicit_root_relation_repo"]
expect(repo.root).to be nil
# Repos can provide an explicit root relation
repo = Hanami.app["repos.explicit_root_relation_repo"]
expect(repo.root).to eql Hanami.app["relations.posts"]
end
end
specify "repos use relations and structs only from their own slice" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/repo.rb", <<~RUBY
module TestApp
class Repo < Hanami::DB::Repo
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
write "slices/admin/db/struct.rb", <<~RUBY
module Admin
module DB
class Struct < Hanami::DB::Struct
end
end
end
RUBY
write "slices/admin/relations/posts.rb", <<~RUBY
module Admin
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "slices/admin/repo.rb", <<~RUBY
module Admin
class Repo < TestApp::Repo
end
end
RUBY
write "slices/admin/repos/post_repo.rb", <<~RUBY
module Admin
module Repos
class PostRepo < Repo
end
end
end
RUBY
write "slices/admin/structs/post.rb", <<~RUBY
module Admin
module Structs
class Post < DB::Struct
end
end
end
RUBY
write "slices/main/relations/posts.rb", <<~RUBY
module Main
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "slices/main/repo.rb", <<~RUBY
module Main
class Repo < TestApp::Repo
end
end
RUBY
write "slices/main/repos/post_repo.rb", <<~RUBY
module Main
module Repos
class PostRepo < Repo
end
end
end
RUBY
write "slices/main/repositories/post_repository.rb", <<~RUBY
module Main
module Repositories
class PostRepository < Repo
end
end
end
RUBY
require "hanami/prepare"
Admin::Slice.prepare :db
# Manually run a migration
gateway = Admin::Slice["db.gateway"]
migration = gateway.migration do
change do
# drop_table? :posts
create_table :posts do
primary_key :id
column :title, :text, null: false
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
expect(Admin::Slice["repos.post_repo"].root).to eql Admin::Slice["relations.posts"]
expect(Admin::Slice["repos.post_repo"].posts).to eql Admin::Slice["relations.posts"]
expect(Admin::Slice["repos.post_repo"].posts.by_pk(1).one!.class).to be < Admin::Structs::Post
expect(Main::Slice["repos.post_repo"].posts).to eql Main::Slice["relations.posts"]
expect(Main::Slice["repositories.post_repository"].posts).to eql Main::Slice["relations.posts"]
# Slice struct namespace used even when no concrete struct classes are defined
expect(Main::Slice["repos.post_repo"].posts.by_pk(1).one!.class).to be < Main::Structs::Post
end
end
specify "repos resolve registered container dependencies with Deps[]" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
Hanami.app.register("dependency") { -> { "Hello dependency!" } }
end
end
RUBY
write "app/repo.rb", <<~RUBY
module TestApp
class Repo < Hanami::DB::Repo
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "app/repos/post_repo.rb", <<~RUBY
module TestApp
module Repos
class PostRepo < Repo
include Deps["dependency"]
def test
dependency.call
end
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
Hanami.app.prepare :db
# Manually run a migration and add a test record
gateway = Hanami.app["db.gateway"]
migration = gateway.migration do
change do
create_table :posts do
primary_key :id
column :title, :text, null: false
end
end
end
migration.apply(gateway, :up)
repo = Hanami.app["repos.post_repo"]
expect(repo.test).to eq "Hello dependency!"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/logging_spec.rb | spec/integration/db/logging_spec.rb | # frozen_string_literal: true
RSpec.describe "DB / Logging", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
it "logs SQL queries" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/setup"
logger_stream = StringIO.new
Hanami.app.config.logger.stream = logger_stream
require "hanami/prepare"
Hanami.app.prepare :db
# Manually run a migration and add a test record
gateway = Hanami.app["db.gateway"]
migration = gateway.migration do
change do
create_table :posts do
primary_key :id
column :title, :text, null: false
end
create_table :authors do
primary_key :id
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
relation = Hanami.app["relations.posts"]
expect(relation.select(:title).to_a).to eq [{:title=>"Together breakfast"}]
logger_stream.rewind
log_lines = logger_stream.read.split("\n")
expect(log_lines.length).to eq 1
expect(log_lines.first).to match /Loaded :sqlite in \d+ms SELECT `posts`.`title` FROM `posts` ORDER BY `posts`.`id`/
end
end
describe "slices sharing app db config" do
it "logs SQL queries" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
write "slices/admin/relations/posts.rb", <<~RUBY
module Admin
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "slices/main/relations/posts.rb", <<~RUBY
module Main
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
require "hanami/setup"
logger_stream = StringIO.new
Hanami.app.config.logger.stream = logger_stream
require "hanami/prepare"
Admin::Slice.prepare :db
# Manually run a migration
gateway = Admin::Slice["db.gateway"]
migration = gateway.migration do
change do
create_table :posts do
primary_key :id
column :title, :text, null: false
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
Hanami.app.boot
# Booting the app will have the ROM schemas infer themself via some `PRAGMA` queries to the
# database, which themselves will emit logs. Clear those logs, since we want to focus on
# individual query logging in this test.
logger_stream.truncate(0)
relation = Admin::Slice["relations.posts"]
relation.select(:title).to_a
log_lines = logger_stream.string.split("\n")
expect(log_lines.length).to eq 1
expect(log_lines.last).to match /Loaded :sqlite in \d+ms SELECT `posts`.`title` FROM `posts` ORDER BY `posts`.`id`/
relation = Main::Slice["relations.posts"]
relation.select(:id).to_a
log_lines = logger_stream.string.split("\n")
expect(log_lines.length).to eq 2
expect(log_lines.last).to match /Loaded :sqlite in \d+ms SELECT `posts`.`id` FROM `posts` ORDER BY `posts`.`id`/
end
end
end
describe "slices with independent db config" do
# This is the same test as above, except without the config/providers/db.rb file.
it "logs SQL queries" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
write "slices/admin/relations/posts.rb", <<~RUBY
module Admin
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "slices/main/relations/posts.rb", <<~RUBY
module Main
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
require "hanami/setup"
logger_stream = StringIO.new
Hanami.app.config.logger.stream = logger_stream
require "hanami/prepare"
Admin::Slice.prepare :db
# Manually run a migration
gateway = Admin::Slice["db.gateway"]
migration = gateway.migration do
change do
create_table :posts do
primary_key :id
column :title, :text, null: false
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
Hanami.app.boot
# Booting the app will have the ROM schemas infer themself via some `PRAGMA` queries to the
# database, which themselves will emit logs. Clear those logs, since we want to focus on
# individual query logging in this test.
logger_stream.truncate(0)
relation = Admin::Slice["relations.posts"]
relation.select(:title).to_a
log_lines = logger_stream.string.split("\n")
expect(log_lines.length).to eq 1
expect(log_lines.last).to match /Loaded :sqlite in \d+ms SELECT `posts`.`title` FROM `posts` ORDER BY `posts`.`id`/
relation = Main::Slice["relations.posts"]
relation.select(:id).to_a
log_lines = logger_stream.string.split("\n")
expect(log_lines.length).to eq 2
expect(log_lines.last).to match /Loaded :sqlite in \d+ms SELECT `posts`.`id` FROM `posts` ORDER BY `posts`.`id`/
end
end
end
describe "in production" do
it "logs SQL queries" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
ENV["HANAMI_ENV"] = "production"
require "hanami/setup"
logger_stream = StringIO.new
Hanami.app.config.logger.stream = logger_stream
require "hanami/prepare"
Hanami.app.prepare :db
# Manually run a migration and add a test record
gateway = Hanami.app["db.gateway"]
migration = gateway.migration do
change do
create_table :posts do
primary_key :id
column :title, :text, null: false
end
create_table :authors do
primary_key :id
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
relation = Hanami.app["relations.posts"]
expect(relation.select(:title).to_a).to eq [{:title=>"Together breakfast"}]
logger_stream.rewind
log_lines = logger_stream.read.split("\n")
expect(log_lines.length).to eq 1
expect(log_lines.first).to match /Loaded :sqlite in \d+ms SELECT `posts`.`title` FROM `posts` ORDER BY `posts`.`id`/
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/relations_spec.rb | spec/integration/db/relations_spec.rb | # frozen_string_literal: true
RSpec.describe "DB / Relations", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
it "registers nested relations" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "app/relations/nested/posts.rb", <<~RUBY
module TestApp
module Relations
module Nested
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
Hanami.app.prepare :db
# Manually run a migration and add a test record
gateway = TestApp::App["db.gateway"]
migration = gateway.migration do
change do
create_table :posts do
primary_key :id
column :title, :text
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Hi from nested relation')")
post = TestApp::App["relations.posts"].to_a[0]
expect(post[:title]).to eq "Hi from nested relation"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/gateways_spec.rb | spec/integration/db/gateways_spec.rb | # frozen_string_literal: true
RSpec.describe "DB / Gateways", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
it "configures gateways by detecting ENV vars" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "db/.keep", ""
write "app/relations/.keep", ""
write "slices/admin/relations/.keep", ""
ENV["DATABASE_URL"] = "sqlite://db/default.sqlite3"
ENV["DATABASE_URL__EXTRA"] = "sqlite://db/extra.sqlite3"
ENV["ADMIN__DATABASE_URL__DEFAULT"] = "sqlite://db/admin.sqlite3"
ENV["ADMIN__DATABASE_URL__SPECIAL"] = "sqlite://db/admin_special.sqlite3"
require "hanami/prepare"
expect(Hanami.app["db.rom"].gateways[:default]).to be
expect(Hanami.app["db.rom"].gateways[:extra]).to be
expect(Hanami.app["db.gateway"]).to be Hanami.app["db.rom"].gateways[:default]
expect(Hanami.app["db.gateways.default"]).to be Hanami.app["db.rom"].gateways[:default]
expect(Hanami.app["db.gateways.extra"]).to be Hanami.app["db.rom"].gateways[:extra]
expect(Admin::Slice["db.rom"].gateways[:default]).to be
expect(Admin::Slice["db.rom"].gateways[:special]).to be
expect(Admin::Slice["db.gateway"]).to be Admin::Slice["db.rom"].gateways[:default]
expect(Admin::Slice["db.gateways.default"]).to be Admin::Slice["db.rom"].gateways[:default]
expect(Admin::Slice["db.gateways.special"]).to be Admin::Slice["db.rom"].gateways[:special]
end
end
it "configures gateways from explicit config in the provider" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "db/.keep", ""
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
config.gateway :default do |gw|
gw.database_url = "sqlite://db/default.sqlite3"
end
config.gateway :extra do |gw|
gw.database_url = "sqlite://db/extra.sqlite3"
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app["db.rom"].gateways[:default]).to be
expect(Hanami.app["db.rom"].gateways[:extra]).to be
expect(Hanami.app["db.gateway"]).to be Hanami.app["db.rom"].gateways[:default]
expect(Hanami.app["db.gateways.default"]).to be Hanami.app["db.rom"].gateways[:default]
expect(Hanami.app["db.gateways.extra"]).to be Hanami.app["db.rom"].gateways[:extra]
end
end
it "configures connection options on their respective gateways" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "db/.keep", ""
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
config.gateway :default do |gw|
gw.connection_options timeout: 10_000
gw.adapter :sql do |a|
a.skip_defaults :extensions
a.extension :error_sql
end
end
config.gateway :extra do |gw|
gw.connection_options readonly: true
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
ENV["DATABASE_URL__EXTRA"] = "sqlite::memory"
require "hanami/prepare"
default = Hanami.app["db.gateways.default"]
extra = Hanami.app["db.gateways.extra"]
expect(default.options).to eq({timeout: 10_000, extensions: [:error_sql]})
expect(extra.options).to eq({readonly: true, extensions: %i[caller_logging error_sql sql_comments]})
end
end
it "exposes all database URLs as #database_urls on the provider source (for CLI commands)" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
config.gateway :special do |gw|
gw.database_url = "sqlite://db/special.sqlite3"
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite://db/default.sqlite3"
ENV["DATABASE_URL__EXTRA"] = "sqlite://db/extra.sqlite3"
require "hanami/prepare"
database_urls = Hanami.app.container.providers[:db].source.finalize_config.database_urls
expect(database_urls).to eq(
default: "sqlite://db/default.sqlite3",
extra: "sqlite://db/extra.sqlite3",
special: "sqlite://db/special.sqlite3"
)
end
end
it "applies extensions from the default adapter to explicitly configured gateway adapters" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
config.adapter :sql do |a|
a.extension :is_distinct_from
end
config.gateway :default do |gw|
gw.adapter :sql do |a|
a.extension :exclude_or_null
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
ENV["DATABASE_URL__SPECIAL"] = "sqlite::memory"
require "hanami/prepare"
expect(Hanami.app["db.gateways.default"].options[:extensions])
.to eq [:exclude_or_null, :is_distinct_from, :caller_logging, :error_sql, :sql_comments]
expect(Hanami.app["db.gateways.special"].options[:extensions])
.to eq [:is_distinct_from, :caller_logging, :error_sql, :sql_comments]
end
end
it "combines ROM plugins from both default adapter and gateway-configured adapters" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
config.adapter :sql do |a|
a.plugin command: :associates
end
config.gateway :default do |gw|
gw.database_url = "sqlite::memory"
gw.adapter :sql do |a|
a.plugin relation: :nullify
end
end
config.gateway :special do |gw|
gw.adapter :sql do |a|
a.plugin relation: :pagination
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
ENV["DATABASE_URL__SPECIAL"] = "sqlite::memory"
require "hanami/prepare"
expect(Hanami.app["db.config"].setup.plugins.length).to eq 5
expect(Hanami.app["db.config"].setup.plugins).to include(
satisfying { |plugin| plugin.type == :command && plugin.name == :associates },
satisfying { |plugin| plugin.type == :relation && plugin.name == :nullify },
satisfying { |plugin| plugin.type == :relation && plugin.name == :pagination },
satisfying { |plugin| plugin.type == :relation && plugin.name == :auto_restrictions },
satisfying { |plugin| plugin.type == :relation && plugin.name == :instrumentation }
)
end
end
it "configures gateway adapters for their specific database types" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
config.gateway :default do |gw|
gw.database_url = "sqlite::memory"
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
ENV["DATABASE_URL__SPECIAL"] = "postgres://localhost/database"
require "hanami/prepare"
# Get the provider source and finalize config, because the tests here aren't set up to handle
# connections to a running postgres database
allow(Hanami).to receive(:bundled?).and_call_original
allow(Hanami).to receive(:bundled?).with("pg").and_return true
provider_source = Hanami.app.container.providers[:db].source
provider_source.finalize_config
expect(provider_source.config.gateways[:default].config.adapter.extensions)
.to eq [:caller_logging, :error_sql, :sql_comments]
expect(provider_source.config.gateways[:special].config.adapter.extensions)
.to eq [
:caller_logging, :error_sql, :sql_comments,
:pg_array, :pg_enum, :pg_json, :pg_range
]
end
end
it "makes the gateways available to relations" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "app/relations/users.rb", <<~RUBY
module TestApp
module Relations
class Users < Hanami::DB::Relation
gateway :extra
schema :users, infer: true
end
end
end
RUBY
write "db/.keep", ""
ENV["DATABASE_URL"] = "sqlite://db/default.sqlite3"
ENV["DATABASE_URL__EXTRA"] = "sqlite://db/extra.sqlite3"
require "hanami/prepare"
Hanami.app.prepare :db
# Manually run a migration and add a test record
default_gateway = Hanami.app["db.gateways.default"]
migration = default_gateway.migration do
change do
create_table :posts do
primary_key :id
column :title, :text, null: false
end
end
end
migration.apply(default_gateway, :up)
default_gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
extra_gateway = Hanami.app["db.gateways.extra"]
migration = extra_gateway.migration do
change do
create_table :users do
primary_key :id
column :name, :text, null: false
end
end
end
migration.apply(extra_gateway, :up)
extra_gateway.connection.execute("INSERT INTO users (name) VALUES ('Jane Doe')")
Hanami.app.boot
expect(Hanami.app["relations.posts"].to_a).to eq [{id: 1, title: "Together breakfast"}]
expect(Hanami.app["relations.users"].to_a).to eq [{id: 1, name: "Jane Doe"}]
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/commands_spec.rb | spec/integration/db/commands_spec.rb | # frozen_string_literal: true
RSpec.describe "DB / Commands", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
it "registers custom commands" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "app/db/commands/nested/create_post_with_default_title.rb", <<~RUBY
module TestApp
module DB
module Commands
module Nested
class CreatePostWithDefaultTitle < ROM::SQL::Commands::Create
relation :posts
register_as :create_with_default_title
result :one
before :set_title
def set_title(tuple, *)
tuple[:title] ||= "Default title from command"
tuple
end
end
end
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
Hanami.app.prepare :db
# Manually run a migration and add a test record
gateway = TestApp::App["db.gateway"]
migration = gateway.migration do
change do
create_table :posts do
primary_key :id
column :title, :text, null: false
end
end
end
migration.apply(gateway, :up)
post = TestApp::App["relations.posts"].command(:create_with_default_title).call({})
expect(post[:title]).to eq "Default title from command"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/mappers_spec.rb | spec/integration/db/mappers_spec.rb | # frozen_string_literal: true
RSpec.describe "DB / Mappers", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
it "registers custom mappers" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "app/db/mappers/nested/default_title_mapper.rb", <<~RUBY
require "rom/transformer"
module TestApp
module DB
module Mappers
module Nested
class DefaultTitleMapper < ROM::Transformer
relation :posts
register_as :default_title_mapper
map do
set_default_title
end
def set_default_title(row)
row[:title] ||= "Default title from mapper"
row
end
end
end
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
Hanami.app.prepare :db
# Manually run a migration and add a test record
gateway = TestApp::App["db.gateway"]
migration = gateway.migration do
change do
create_table :posts do
primary_key :id
column :title, :text
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES (NULL)")
post = TestApp::App["relations.posts"].map_with(:default_title_mapper).to_a[0]
expect(post[:title]).to eq "Default title from mapper"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/auto_registration_spec.rb | spec/integration/db/auto_registration_spec.rb | # frozen_string_literal: true
RSpec.describe "DB / auto-registration", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
it "does not auto-register files in entities/, structs/, or db/" do
with_tmp_directory(@dir = Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/db/changesets/update_posts.rb", ""
write "app/entities/post.rb", ""
write "app/structs/post.rb", ""
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/boot"
expect(Hanami.app.keys).not_to include(*[
"db.changesets.update_posts",
"entities.post",
"structs.post"
])
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/db_inflector_spec.rb | spec/integration/db/db_inflector_spec.rb | # frozen_string_literal: true
require "dry/system"
RSpec.describe "ROM::Inflector", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
around :each do |example|
inflector = ROM::Inflector
ROM.instance_eval {
remove_const :Inflector
const_set :Inflector, Dry::Inflector.new
}
example.run
ensure
ROM.instance_eval {
remove_const :Inflector
const_set :Inflector, inflector
}
end
it "replaces ROM::Inflector with the Hanami inflector" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
expect { Hanami.app.prepare :db }.to change { ROM::Inflector == Hanami.app["inflector"] }.from(false).to(true)
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/db/db_spec.rb | spec/integration/db/db_spec.rb | # frozen_string_literal: true
RSpec.describe "DB", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after do
ENV.replace(@env)
end
it "sets up ROM and registers relations" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
Hanami.app.prepare :db
expect(Hanami.app["db.config"]).to be_an_instance_of ROM::Configuration
expect(Hanami.app["db.gateway"]).to be_an_instance_of ROM::SQL::Gateway
expect(Hanami.app["db.gateways.default"]).to be Hanami.app["db.gateway"]
# Manually run a migration and add a test record
gateway = Hanami.app["db.gateway"]
migration = gateway.migration do
change do
# drop_table? :posts
create_table :posts do
primary_key :id
column :title, :text, null: false
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
Hanami.app.boot
expect(Hanami.app["db.rom"].relations[:posts].to_a).to eq [{id: 1, title: "Together breakfast"}]
expect(Hanami.app["relations.posts"]).to be Hanami.app["db.rom"].relations[:posts]
end
end
it "provides access in a non-booted app" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
ENV["DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
Hanami.app.prepare :db
expect(Hanami.app["db.config"]).to be_an_instance_of ROM::Configuration
expect(Hanami.app["db.gateway"]).to be_an_instance_of ROM::SQL::Gateway
expect(Hanami.app["db.gateways.default"]).to be Hanami.app["db.gateway"]
# Manually run a migration and add a test record
gateway = Hanami.app["db.gateway"]
migration = gateway.migration do
change do
# drop_table? :posts
create_table :posts do
primary_key :id
column :title, :text, null: false
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
expect(Hanami.app["db.rom"].relations[:posts].to_a).to eq [{id: 1, title: "Together breakfast"}]
expect(Hanami.app["relations.posts"]).to be Hanami.app["db.rom"].relations[:posts]
end
end
it "raises an error when no database URL is provided" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/relations/.keep", ""
require "hanami/prepare"
expect { Hanami.app.prepare :db }.to raise_error(Hanami::ComponentLoadError, /database_url/)
end
end
it "raises an error when the database driver gem is missing" do
allow(Hanami).to receive(:bundled?).and_call_original
expect(Hanami).to receive(:bundled?).with("pg").and_return false
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/relations/.keep", ""
ENV["DATABASE_URL"] = "postgres://127.0.0.0"
require "hanami/prepare"
expect { Hanami.app.prepare :db }.to raise_error(Hanami::ComponentLoadError) { |error|
expect(error.message).to include %(The "pg" gem is required)
}
end
end
it "allows the user to configure the provider" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
write "config/providers/db.rb", <<~RUBY
Hanami.app.configure_provider :db do
# In this test, we're not setting an ENV["DATABASE_URL"], and instead configuring
# it via the provider source config, to prove that this works
config.gateway :default do |gw|
gw.database_url = "sqlite::memory"
end
end
RUBY
require "hanami/prepare"
Hanami.app.prepare :db
gateway = Hanami.app["db.gateway"]
migration = gateway.migration do
change do
# drop_table? :posts
create_table :posts do
primary_key :id
column :title, :text, null: false
end
end
end
migration.apply(gateway, :up)
gateway.connection.execute("INSERT INTO posts (title) VALUES ('Together breakfast')")
Hanami.app.boot
expect(Hanami.app["db.rom"].relations[:posts].to_a).to eq [{id: 1, title: "Together breakfast"}]
expect(Hanami.app["relations.posts"]).to be Hanami.app["db.rom"].relations[:posts]
end
end
it "transforms the database URL in test mode" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/relations/posts.rb", <<~RUBY
module TestApp
module Relations
class Posts < Hanami::DB::Relation
schema :posts, infer: true
end
end
end
RUBY
ENV["HANAMI_ENV"] = "test"
ENV["DATABASE_URL"] = "sqlite://./development.db"
require "hanami/prepare"
Hanami.app.prepare :db
expect(Hanami.app["db.gateway"].connection.url).to eq "sqlite://./test.db"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/action/format_config_spec.rb | spec/integration/action/format_config_spec.rb | # frozen_string_literal: true
require "json"
require "rack/test"
RSpec.describe "App action / Format config", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
around do |example|
with_tmp_directory(Dir.mktmpdir, &example)
end
it "adds a body parser middleware for the accepted formats from the action config" do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
config.actions.formats.accept :json
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
post "/users", to: "users.create"
end
end
RUBY
write "app/action.rb", <<~RUBY
# auto_register: false
module TestApp
class Action < Hanami::Action
end
end
RUBY
write "app/actions/users/create.rb", <<~RUBY
module TestApp
module Actions
module Users
class Create < TestApp::Action
def handle(req, res)
res.body = req.params[:users].join("-")
end
end
end
end
end
RUBY
require "hanami/boot"
post(
"/users",
JSON.generate("users" => %w[jane john jade joe]),
"CONTENT_TYPE" => "application/json"
)
expect(last_response).to be_successful
expect(last_response.body).to eql("jane-john-jade-joe")
end
it "does not add a body parser middleware if one is already added" do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
config.actions.formats.accept :json
config.middleware.use :body_parser, [json: "application/json+custom"]
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
post "/users", to: "users.create"
end
end
RUBY
write "app/action.rb", <<~RUBY
# auto_register: false
module TestApp
class Action < Hanami::Action
end
end
RUBY
write "app/actions/users/create.rb", <<~RUBY
module TestApp
module Actions
module Users
class Create < TestApp::Action
config.formats.clear
def handle(req, res)
res.body = req.params[:users].join("-")
end
end
end
end
end
RUBY
require "hanami/boot"
post(
"/users",
JSON.generate("users" => %w[jane john jade joe]),
"CONTENT_TYPE" => "application/json+custom"
)
expect(last_response).to be_successful
expect(last_response.body).to eql("jane-john-jade-joe")
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/action/slice_configuration_spec.rb | spec/integration/action/slice_configuration_spec.rb | # frozen_string_literal: true
RSpec.describe "App action / Slice configuration", :app_integration do
before do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/action.rb", <<~'RUBY'
require "hanami/action"
module TestApp
class Action < Hanami::Action
end
end
RUBY
require "hanami/setup"
end
end
def prepare_app
with_directory(@dir) { require "hanami/prepare" }
end
describe "inheriting from app-level base class" do
describe "app-level base class" do
it "applies default actions config from the app", :aggregate_failures do
prepare_app
expect(TestApp::Action.config.formats.accepted).to eq []
end
it "applies actions config from the app" do
Hanami.app.config.actions.formats.accepted = [:json]
prepare_app
expect(TestApp::Action.config.formats.accepted).to eq [:json]
end
it "does not override config in the base class" do
Hanami.app.config.actions.formats.accepted = [:csv]
prepare_app
TestApp::Action.config.formats.accepted = [:json]
expect(TestApp::Action.config.formats.accepted).to eq [:json]
end
end
describe "subclass in app" do
before do
with_directory(@dir) do
write "app/actions/articles/index.rb", <<~'RUBY'
module TestApp
module Actions
module Articles
class Index < TestApp::Action
end
end
end
end
RUBY
end
end
it "applies default actions config from the app", :aggregate_failures do
prepare_app
expect(TestApp::Actions::Articles::Index.config.formats.accepted).to eq []
end
it "applies actions config from the app" do
Hanami.app.config.actions.formats.accepted = [:json]
prepare_app
expect(TestApp::Actions::Articles::Index.config.formats.accepted).to eq [:json]
end
it "applies config from the base class" do
prepare_app
TestApp::Action.config.formats.accepted = [:json]
expect(TestApp::Actions::Articles::Index.config.formats.accepted).to eq [:json]
end
end
describe "subclass in slice" do
before do
with_directory(@dir) do
write "slices/admin/actions/articles/index.rb", <<~'RUBY'
module Admin
module Actions
module Articles
class Index < TestApp::Action
end
end
end
end
RUBY
end
end
it "applies default actions config from the app", :aggregate_failures do
prepare_app
expect(Admin::Actions::Articles::Index.config.formats.accepted).to eq []
end
it "applies actions config from the app" do
Hanami.app.config.actions.formats.accepted = [:json]
prepare_app
expect(Admin::Actions::Articles::Index.config.formats.accepted).to eq [:json]
end
it "applies config from the base class" do
prepare_app
TestApp::Action.config.formats.accepted = [:json]
expect(Admin::Actions::Articles::Index.config.formats.accepted).to eq [:json]
end
end
end
describe "inheriting from a slice-level base class, in turn inheriting from an app-level base class" do
before do
with_directory(@dir) do
write "slices/admin/action.rb", <<~'RUBY'
module Admin
class Action < TestApp::Action
end
end
RUBY
end
end
describe "slice-level base class" do
it "applies default actions config from the app", :aggregate_failures do
prepare_app
expect(Admin::Action.config.formats.accepted).to eq []
end
it "applies actions config from the app" do
Hanami.app.config.actions.formats.accepted = [:json]
prepare_app
expect(Admin::Action.config.formats.accepted).to eq [:json]
end
it "applies config from the app base class" do
prepare_app
TestApp::Action.config.formats.accepted = [:json]
expect(Admin::Action.config.formats.accepted).to eq [:json]
end
context "slice actions config present" do
before do
with_directory(@dir) do
write "config/slices/admin.rb", <<~'RUBY'
module Admin
class Slice < Hanami::Slice
config.actions.format :csv
end
end
RUBY
end
end
it "applies actions config from the slice" do
prepare_app
expect(Admin::Action.config.formats.accepted).to eq [:csv]
end
it "prefers actions config from the slice over config from the app-level base class" do
prepare_app
TestApp::Action.config.formats.accepted = [:json]
expect(Admin::Action.config.formats.accepted).to eq [:csv]
end
it "prefers config from the base class over actions config from the slice" do
prepare_app
TestApp::Action.config.formats.accepted = [:csv]
Admin::Action.config.formats.accepted = [:json]
expect(Admin::Action.config.formats.accepted).to eq [:json]
end
end
end
describe "subclass in slice" do
before do
with_directory(@dir) do
write "slices/admin/actions/articles/index.rb", <<~'RUBY'
module Admin
module Actions
module Articles
class Index < Admin::Action
end
end
end
end
RUBY
end
end
it "applies default actions config from the app", :aggregate_failures do
prepare_app
expect(Admin::Actions::Articles::Index.config.formats.accepted).to eq []
end
it "applies actions config from the app" do
Hanami.app.config.actions.formats.accepted = [:json]
prepare_app
expect(Admin::Actions::Articles::Index.config.formats.accepted).to eq [:json]
end
it "applies actions config from the slice" do
with_directory(@dir) do
write "config/slices/admin.rb", <<~'RUBY'
module Admin
class Slice < Hanami::Slice
config.actions.formats.accepted = [:json]
end
end
RUBY
end
prepare_app
expect(Admin::Actions::Articles::Index.config.formats.accepted).to eq [:json]
end
it "applies config from the slice base class" do
prepare_app
Admin::Action.config.formats.accepted = [:json]
expect(Admin::Actions::Articles::Index.config.formats.accepted).to eq [:json]
end
it "prefers config from the slice base class over actions config from the slice" do
with_directory(@dir) do
write "config/slices/admin.rb", <<~'RUBY'
module Admin
class Slice < Hanami::Slice
config.actions.format :csv
end
end
RUBY
end
prepare_app
Admin::Action.config.formats.accepted = [:json]
expect(Admin::Actions::Articles::Index.config.formats.accepted).to eq [:json]
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/action/cookies_spec.rb | spec/integration/action/cookies_spec.rb | # frozen_string_literal: true
RSpec.describe "App action / Cookies", :app_integration do
before do
module TestApp
class App < Hanami::App
end
end
Hanami.app.instance_eval(&app_hook) if respond_to?(:app_hook)
Hanami.app.prepare
module TestApp
class Action < Hanami::Action
end
end
end
subject(:action_class) { TestApp::Action }
context "default configuration" do
it "has cookie support enabled" do
expect(action_class.ancestors).to include Hanami::Action::Cookies
end
end
context "custom cookie options given in app-level config" do
subject(:app_hook) {
proc do
config.actions.cookies = {max_age: 300}
end
}
it "has cookie support enabled" do
expect(action_class.ancestors).to include Hanami::Action::Cookies
end
it "has the cookie options configured" do
expect(action_class.config.cookies).to eq(max_age: 300)
end
end
context "cookies disabled in app-level config" do
subject(:app_hook) {
proc do
config.actions.cookies = nil
end
}
it "does not have cookie support enabled" do
expect(action_class.ancestors.map(&:to_s)).not_to include "Hanami::Action::Cookies"
end
it "has no cookie options configured" do
expect(action_class.config.cookies).to eq({})
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/action/csrf_protection_spec.rb | spec/integration/action/csrf_protection_spec.rb | # frozen_string_literal: true
RSpec.describe "App action / CSRF protection", :app_integration do
before do
module TestApp
class App < Hanami::App
end
end
Hanami.app.instance_eval(&app_hook) if respond_to?(:app_hook)
Hanami.app.register_slice :main
Hanami.app.prepare
module TestApp
class Action < Hanami::Action
end
end
end
subject(:action_class) { TestApp::Action }
context "app sessions enabled" do
context "CSRF protection not explicitly configured" do
let(:app_hook) {
proc do
config.actions.sessions = :cookie, {secret: "abc123"}
end
}
it "has CSRF protection enabled" do
expect(action_class.ancestors).to include Hanami::Action::CSRFProtection
end
end
context "CSRF protection explicitly disabled" do
let(:app_hook) {
proc do
config.actions.sessions = :cookie, {secret: "abc123"}
config.actions.csrf_protection = false
end
}
it "does not have CSRF protection enabled" do
expect(action_class.ancestors.map(&:to_s)).not_to include "Hanami::Action::CSRFProtection"
end
end
end
context "app sessions not enabled" do
it "does not have CSRF protection enabled" do
expect(action_class.ancestors.map(&:to_s)).not_to include "Hanami::Action::CSRFProtection"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/action/routes_spec.rb | spec/integration/action/routes_spec.rb | # frozen_string_literal: true
RSpec.describe "App action / Routes", :app_integration do
specify "Access app routes from an action" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App; end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
root to: "home.index"
slice :admin, at: "/admin" do
root to: "dashboard.index"
end
end
end
RUBY
write "app/action.rb", <<~RUBY
# auto_register: false
module TestApp
class Action < Hanami::Action; end
end
RUBY
write "app/actions/home/index.rb", <<~RUBY
module TestApp
module Actions
module Home
class Index < TestApp::Action
def handle(req, res)
res.body = routes.path(:root)
end
end
end
end
end
RUBY
write "slices/admin/actions/dashboard/index.rb", <<~RUBY
module Admin
module Actions
module Dashboard
class Index < TestApp::Action
def handle(req, res)
res.body = routes.path(:admin_root)
end
end
end
end
end
RUBY
require "hanami/prepare"
response = TestApp::App["actions.home.index"].call({})
expect(response.body).to eq ["/"]
response = Admin::Slice["actions.dashboard.index"].call({})
expect(response.body).to eq ["/admin"]
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/action/sessions_spec.rb | spec/integration/action/sessions_spec.rb | # frozen_string_literal: true
RSpec.describe "App action / Sessions", :app_integration do
before do
module TestApp
class App < Hanami::App
end
end
Hanami.app.instance_eval(&app_hook) if respond_to?(:app_hook)
Hanami.app.prepare
module TestApp
class Action < Hanami::Action
end
end
end
subject(:action_class) { TestApp::Action }
context "HTTP sessions enabled" do
let(:app_hook) {
proc do
config.actions.sessions = :cookie, {secret: "abc123"}
end
}
it "has HTTP sessions enabled" do
expect(action_class.ancestors).to include(Hanami::Action::Session)
end
end
context "HTTP sessions explicitly disabled" do
let(:app_hook) {
proc do
config.actions.sessions = nil
end
}
it "does not have HTTP sessions enabled" do
expect(action_class.ancestors.map(&:to_s)).not_to include("Hanami::Action::Session")
end
end
context "HTTP sessions not enabled" do
it "does not have HTTP session enabled" do
expect(action_class.ancestors.map(&:to_s)).not_to include("Hanami::Action::Session")
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/action/view_rendering_spec.rb | spec/integration/action/view_rendering_spec.rb | # frozen_string_literal: true
RSpec.describe "App action / View rendering", :app_integration do
specify "Views render with a request-specific context object" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/action.rb", <<~RUBY
# auto_register: false
module TestApp
class Action < Hanami::Action
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
end
end
RUBY
write "app/actions/users/show.rb", <<~RUBY
module TestApp
module Actions
module Users
class Show < TestApp::Action
include Deps[view: "views.users.show"]
def handle(req, res)
res[:job] = "Singer"
res[:age] = 0
res.render view, name: req.params[:name], age: 51
end
end
end
end
end
RUBY
write "app/views/users/show.rb", <<~RUBY
module TestApp
module Views
module Users
class Show < TestApp::View
expose :name, :job, :age
end
end
end
end
RUBY
write "app/templates/layouts/app.html.slim", <<~SLIM
html
body
== yield
SLIM
write "app/templates/users/show.html.slim", <<~'SLIM'
h1 Hello, #{name}
- request.params.to_h.values.sort.each do |value|
p = value
p = job
p = age
SLIM
require "hanami/prepare"
action = TestApp::App["actions.users.show"]
response = action.(name: "Jennifer", last_name: "Lopez")
rendered = response.body[0]
expect(rendered).to eq "<html><body><h1>Hello, Jennifer</h1><p>Jennifer</p><p>Lopez</p><p>Singer</p><p>51</p></body></html>"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/action/view_rendering/view_context_spec.rb | spec/integration/action/view_rendering/view_context_spec.rb | # frozen_string_literal: true
RSpec.describe "App action / View rendering / View context", :app_integration do
subject(:context) {
# We capture the context during rendering via our view spies; see the view classes below
action.call("REQUEST_METHOD" => "GET", "QUERY_STRING" => "/mock_request")
action.view.called_with[:context]
}
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/action.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class Action < Hanami::Action
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "app action" do
let(:action) { TestApp::App["actions.posts.show"] }
def before_prepare
write "app/actions/posts/show.rb", <<~RUBY
module TestApp
module Actions
module Posts
class Show < TestApp::Action
end
end
end
end
RUBY
# Custom view class as a spy for `#call` args
write "app/views/posts/show.rb", <<~RUBY
module TestApp
module Views
module Posts
class Show
attr_reader :called_with
def call(**args)
@called_with = args
""
end
end
end
end
end
RUBY
end
context "no context class defined" do
it "defines and uses a context class" do
expect(context).to be_an_instance_of TestApp::Views::Context
expect(context.class).to be < Hanami::View::Context
end
it "includes the request" do
expect(context.request).to be_an_instance_of Hanami::Action::Request
expect(context.request.env["QUERY_STRING"]).to eq "/mock_request"
end
end
context "context class defined" do
def before_prepare
super()
write "app/views/context.rb", <<~RUBY
# auto_register: false
module TestApp
module Views
class Context < Hanami::View::Context
def concrete_app_context?
true
end
end
end
end
RUBY
end
it "uses the defined context class" do
expect(context).to be_an_instance_of TestApp::Views::Context
expect(context).to be_a_concrete_app_context
end
end
context "hanami-view not bundled" do
before do
allow(Hanami).to receive(:bundled?).and_call_original
expect(Hanami).to receive(:bundled?).with("hanami-view").and_return false
end
it "does not provide a context" do
expect(context).to be nil
end
context "context class defined" do
def before_prepare
super()
write "app/views/context.rb", <<~RUBY
module TestApp
module Views
class Context
def initialize(**)
end
def with(**)
self
end
def concrete_app_context?
true
end
end
end
end
RUBY
end
it "uses the defined context class" do
expect(context).to be_an_instance_of TestApp::Views::Context
expect(context).to be_a_concrete_app_context
end
end
end
end
describe "slice action" do
let(:action) { Main::Slice["actions.posts.show"] }
def before_prepare
write "slices/main/action.rb", <<~RUBY
module Main
class Action < TestApp::Action
end
end
RUBY
write "slices/main/actions/posts/show.rb", <<~RUBY
module Main
module Actions
module Posts
class Show < Main::Action
end
end
end
end
RUBY
# Custom view class as a spy for `#call` args
write "slices/main/views/posts/show.rb", <<~RUBY
module Main
module Views
module Posts
class Show
attr_reader :called_with
def call(**args)
@called_with = args
""
end
end
end
end
end
RUBY
end
context "no context class defined" do
it "defines and uses a context class" do
expect(context).to be_an_instance_of Main::Views::Context
expect(context.class).to be < Hanami::View::Context
end
end
context "context class defined" do
def before_prepare
super()
write "slices/main/views/context.rb", <<~RUBY
# auto_register: false
module Main
module Views
class Context < Hanami::View::Context
def concrete_slice_context?
true
end
end
end
end
RUBY
end
it "uses the defined context class" do
expect(context).to be_an_instance_of Main::Views::Context
expect(context).to be_a_concrete_slice_context
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/action/view_rendering/paired_view_inference_spec.rb | spec/integration/action/view_rendering/paired_view_inference_spec.rb | # frozen_string_literal: true
require "hanami"
RSpec.describe "App action / View rendering / Paired view inference", :app_integration do
before do
module TestApp
class App < Hanami::App
end
end
Hanami.app.prepare
module TestApp
class Action < Hanami::Action
end
end
end
let(:action) { action_class.new }
describe "Ordinary action" do
before do
module TestApp
module Actions
module Articles
class Index < TestApp::Action
end
end
end
end
end
let(:action_class) { TestApp::Actions::Articles::Index }
context "Paired view exists" do
before do
TestApp::App.register "views.articles.index", view
end
let(:view) { double(:view) }
it "auto-injects a paired view from a matching container identifier" do
expect(action.view).to be view
end
context "Another view explicitly auto-injected" do
before do
module TestApp
module Actions
module Articles
class Index < TestApp::Action
include Deps[view: "views.articles.custom"]
end
end
end
end
TestApp::App.register "views.articles.custom", explicit_view
end
let(:action_class) { TestApp::Actions::Articles::Index }
let(:explicit_view) { double(:explicit_view) }
it "respects the explicitly auto-injected view" do
expect(action.view).to be explicit_view
end
end
end
context "No paired view exists" do
it "does not auto-inject any view" do
expect(action.view).to be_nil
end
end
end
describe "RESTful action" do
before do
module TestApp
module Actions
module Articles
class Create < TestApp::Action
end
end
end
end
end
let(:action_class) { TestApp::Actions::Articles::Create }
let(:direct_paired_view) { double(:direct_paired_view) }
let(:alternative_paired_view) { double(:alternative_paired_view) }
context "Direct paired view exists" do
before do
TestApp::App.register "views.articles.create", direct_paired_view
TestApp::App.register "views.articles.new", alternative_paired_view
end
it "auto-injects the directly paired view" do
expect(action.view).to be direct_paired_view
end
end
context "Alternative paired view exists" do
before do
TestApp::App.register "views.articles.new", alternative_paired_view
end
it "auto-injects the alternative paired view" do
expect(action.view).to be alternative_paired_view
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/action/view_rendering/automatic_rendering_spec.rb | spec/integration/action/view_rendering/automatic_rendering_spec.rb | # frozen_string_literal: true
RSpec.describe "App action / View rendering / Automatic rendering", :app_integration do
it "Renders a view automatically, passing all params and exposures" do
within_app do
write "app/actions/profile/show.rb", <<~RUBY
module TestApp
module Actions
module Profile
class Show < TestApp::Action
def handle(req, res)
res[:favorite_number] = 123
end
end
end
end
end
RUBY
write "app/views/profile/show.rb", <<~RUBY
module TestApp
module Views
module Profile
class Show < TestApp::View
expose :name, :favorite_number
end
end
end
end
RUBY
write "app/templates/profile/show.html.slim", <<~'SLIM'
h1 Hello, #{name}. Your favorite number is #{favorite_number}, right?
SLIM
require "hanami/prepare"
action = TestApp::App["actions.profile.show"]
response = action.(name: "Jennifer")
rendered = response.body[0]
expect(rendered).to eq "<html><body><h1>Hello, Jennifer. Your favorite number is 123, right?</h1></body></html>"
expect(response.status).to eq 200
end
end
it "Does not render a view automatically when #render? returns false " do
within_app do
write "app/actions/profile/show.rb", <<~RUBY
module TestApp
module Actions
module Profile
class Show < TestApp::Action
def handle(req, res)
res[:favorite_number] = 123
end
def auto_render?(_res)
false
end
end
end
end
end
RUBY
write "app/views/profile/show.rb", <<~RUBY
module TestApp
module Views
module Profile
class Show < TestApp::View
expose :name, :favorite_number
end
end
end
end
RUBY
write "app/templates/profile/show.html.slim", <<~'SLIM'
h1 Hello, #{name}. Your favorite number is #{favorite_number}, right?
SLIM
require "hanami/prepare"
action = TestApp::App["actions.profile.show"]
response = action.(name: "Jennifer")
expect(response.body).to eq []
expect(response.status).to eq 200
end
end
it "Doesn't render view automatically when body is already assigned" do
within_app do
write "app/actions/profile/show.rb", <<~RUBY
module TestApp
module Actions
module Profile
class Show < TestApp::Action
def handle(req, res)
res.body = "200: Okay okay okay"
end
end
end
end
end
RUBY
write "app/views/profile/show.rb", <<~RUBY
module TestApp
module Views
module Profile
class Show < TestApp::View
expose :name, :favorite_number
end
end
end
end
RUBY
write "app/templates/profile/show.html.slim", <<~'SLIM'
h1 Hello, #{name}. Your favorite number is #{favorite_number}, right?
SLIM
require "hanami/prepare"
action = TestApp::App["actions.profile.show"]
response = action.(name: "Jennifer")
rendered = response.body[0]
expect(rendered).to eq "200: Okay okay okay"
expect(response.status).to eq 200
end
end
it "Doesn't render view automatically when halt is called" do
within_app do
write "app/actions/profile/show.rb", <<~RUBY
module TestApp
module Actions
module Profile
class Show < TestApp::Action
def handle(req, res)
halt 404
end
end
end
end
end
RUBY
write "app/views/profile/show.rb", <<~RUBY
module TestApp
module Views
module Profile
class Show < TestApp::View
expose :name
end
end
end
end
RUBY
# This template will crash if not rendered with a valid `name` string. The absence
# of a crash here tells us that the view was never rendered.
write "app/templates/profile/show.html.slim", <<~'SLIM'
h1 Hello, #{name.to_str}!
SLIM
require "hanami/prepare"
# Call the action without a `name` param, thereby ensuring the view will raise an
# error if rendered
action = TestApp::App["actions.profile.show"]
response = action.({})
rendered = response.body[0]
aggregate_failures do
expect(rendered).to eq "Not Found"
expect(response.status).to eq 404
end
end
end
it "Does not render if no view is available" do
within_app do
write "app/actions/profile/show.rb", <<~RUBY
module TestApp
module Actions
module Profile
class Show < TestApp::Action
end
end
end
end
RUBY
require "hanami/prepare"
action = TestApp::App["actions.profile.show"]
response = action.({})
expect(response.body).to eq []
expect(response.status).to eq 200
end
end
def within_app
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/action.rb", <<~RUBY
# auto_register: false
module TestApp
class Action < Hanami::Action
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
end
end
RUBY
write "app/templates/layouts/app.html.slim", <<~SLIM
html
body
== yield
SLIM
yield
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/slices/slice_loading_spec.rb | spec/integration/slices/slice_loading_spec.rb | # frozen_string_literal: true
require "rack/test"
RSpec.describe "Slices / Slice loading", :app_integration, :aggregate_failures do
let(:app_modules) { %i[TestApp Admin Main] }
describe "loading specific slices with config.slices" do
describe "setup app" do
it "ignores any explicitly registered slices not included in load_slices" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
config.slices = %w[admin]
end
end
RUBY
require "hanami/setup"
expect { Hanami.app.register_slice :main }.not_to(change { Hanami.app.slices.keys })
expect { Main }.to raise_error(NameError)
expect { Hanami.app.register_slice :admin }.to change { Hanami.app.slices.keys }.to [:admin]
expect(Admin::Slice).to be
end
end
describe "nested slices" do
it "ignores any explicitly registered slices not included in load_slices" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
config.slices = %w[admin.shop]
end
end
RUBY
require "hanami/setup"
expect { Hanami.app.register_slice :admin }.to change { Hanami.app.slices.keys }.to [:admin]
expect { Admin::Slice.register_slice :editorial }.not_to(change { Admin::Slice.slices.keys })
expect { Admin::Slice.register_slice :shop }.to change { Admin::Slice.slices.keys }.to [:shop]
expect(Admin::Shop::Slice).to be
end
end
end
end
describe "prepared app" do
it "loads only the slices included in load_slices" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
config.slices = %w[admin]
end
end
RUBY
write "slices/admin/.keep"
write "slices/main/.keep"
require "hanami/prepare"
expect(Hanami.app.slices.keys).to eq [:admin]
expect(Admin::Slice).to be
expect { Main }.to raise_error(NameError)
end
end
it "ignores unknown slices in load_slices" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
config.slices = %w[admin meep morp]
end
end
RUBY
write "slices/admin/.keep"
write "slices/main/.keep"
require "hanami/prepare"
expect(Hanami.app.slices.keys).to eq [:admin]
end
end
describe "nested slices" do
it "loads only the dot-delimited nested slices (and their parents) included in load_slices" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
config.slices = %w[admin.shop]
end
end
RUBY
write "slices/admin/.keep"
write "slices/admin/slices/shop/.keep"
write "slices/admin/slices/editorial/.keep"
write "slices/main/.keep"
require "hanami/prepare"
expect(Hanami.app.slices.keys).to eq [:admin]
expect(Admin::Slice.slices.keys).to eq [:shop]
expect(Admin::Slice).to be
expect(Admin::Shop::Slice).to be
expect { Admin::Editorial }.to raise_error(NameError)
expect { Main }.to raise_error(NameError)
end
end
end
end
end
describe "using ENV vars" do
before do
@orig_env = ENV.to_h
end
after do
ENV.replace(@orig_env)
end
it "uses HANAMI_SLICES" do
ENV["HANAMI_SLICES"] = "admin"
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/admin/.keep"
write "slices/main/.keep"
require "hanami/setup"
expect(Hanami.app.config.slices).to eq %w[admin]
require "hanami/prepare"
expect(Hanami.app.slices.keys).to eq [:admin]
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/slices/slice_configuration_spec.rb | spec/integration/slices/slice_configuration_spec.rb | # frozen_string_literal: true
require "stringio"
RSpec.describe "Slices / Slice configuration", :app_integration do
specify "Slices receive a copy of the app configuration, and can make distinct modifications" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
config.no_auto_register_paths = ["structs"]
end
end
RUBY
write "config/slices/main.rb", <<~'RUBY'
module Main
class Slice < Hanami::Slice
config.no_auto_register_paths << "schemas"
end
end
RUBY
write "config/slices/search.rb", <<~'RUBY'
module Search
class Slice < Hanami::Slice
end
end
RUBY
require "hanami/prepare"
expect(TestApp::App.config.no_auto_register_paths).to eq %w[structs]
expect(Main::Slice.config.no_auto_register_paths).to eq %w[structs schemas]
expect(Search::Slice.config.no_auto_register_paths).to eq %w[structs]
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/slices/external_slice_spec.rb | spec/integration/slices/external_slice_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Slices / External slices", :app_integration do
include Rack::Test::Methods
let(:app) { TestApp::App.app }
specify "External slices can be registered and used" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
require "external/slice"
register_slice(:external, External::Slice)
end
end
RUBY
write "config/routes.rb", <<~'RUBY'
require "hanami/routes"
module TestApp
class Routes < Hanami::Routes
slice :external, at: "/" do
root to: "test_action"
end
end
end
RUBY
# Put a slice and its components in `lib/external/`, as if it were an external gem
write "lib/external/slice.rb", <<~'RUBY'
# auto_register: false
require "hanami/slice"
module External
class Slice < Hanami::Slice
config.root = __dir__
end
end
RUBY
# FIXME: Remove redundant `lib/` dir once hanami/hanami#1174 is merged
write "lib/external/lib/test_repo.rb", <<~'RUBY'
require "hanami/slice"
module External
class TestRepo
def things
%w[foo bar baz]
end
end
end
RUBY
write "lib/external/actions/test_action.rb", <<~'RUBY'
require "hanami/action"
module External
module Actions
class TestAction < Hanami::Action
include Deps["test_repo"]
def handle(req, res)
res.body = test_repo.things.join(", ")
end
end
end
end
RUBY
require "hanami/prepare"
expect(Hanami.app.slices[:external]).to be External::Slice
get "/"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "foo, bar, baz"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/slices/slice_registrations_spec.rb | spec/integration/slices/slice_registrations_spec.rb | # frozen_string_literal: true
RSpec.describe "Slice Registrations", :app_integration do
matcher :have_key do |name, value|
match do |slice|
slice.resolve(name) == value
end
end
specify "Registrations are loaded" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/registrations/foo.rb", <<~RUBY
TestApp::App.register("foo") { "bar" }
RUBY
require "hanami/prepare"
expect(Hanami.app).to have_key(:foo, "bar")
end
end
specify "Slices load their own registrations" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/slices/main.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
end
end
RUBY
write "config/slices/admin.rb", <<~RUBY
module Main
class Slice < Hanami::Slice
end
end
RUBY
write "config/registrations/foo.rb", <<~RUBY
TestApp::App.register("foo") { "bar" }
RUBY
write "slices/admin/config/registrations/bar.rb", <<~RUBY
Admin::Slice.register("bar") { "baz" }
RUBY
write "slices/main/config/registrations/baz.rb", <<~RUBY
Main::Slice.register("baz") { "quux" }
RUBY
require "hanami/prepare"
admin_slice = Hanami.app.slices[:admin]
main_slice = Hanami.app.slices[:main]
aggregate_failures do
expect(Hanami.app).to have_key(:foo, "bar")
expect(admin_slice).to have_key(:bar, "baz")
expect(main_slice).to have_key(:baz, "quux")
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/slices/slice_routing_spec.rb | spec/integration/slices/slice_routing_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Slices / Slice routing", :app_integration do
include Rack::Test::Methods
let(:app) { Main::Slice.rack_app }
specify "Slices have a nil router when no routes are defined" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/.keep", ""
require "hanami/prepare"
expect(Main::Slice.routes).to be nil
expect(Main::Slice.router).to be nil
end
end
specify "Slices have the app 'routes' component registered when app routes are defined but not their own" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~'RUBY'
require "hanami/routes"
module TestApp
class Routes < Hanami::Routes
get "home", to: "home.show", as: :home
end
end
RUBY
write "slices/main/.keep", ""
require "hanami/prepare"
expect(Main::Slice["routes"].path(:home)).to eq "/home"
expect(Main::Slice.router).to be nil
expect(TestApp::App.router).not_to be nil
end
end
specify "Slices use their own router and registered 'routes' component when their own routes are defined" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "slices/main/config/routes.rb", <<~'RUBY'
require "hanami/routes"
module Main
class Routes < Hanami::Routes
get "home", to: "home.show", as: :home
end
end
RUBY
write "slices/main/actions/home/show.rb", <<~'RUBY'
require "hanami/action"
module Main
module Actions
module Home
class Show < Hanami::Action
def handle(*, res)
res.body = "Hello world"
end
end
end
end
end
RUBY
require "hanami/prepare"
Main::Slice.boot
expect(Main::Slice["routes"].path(:home)).to eq "/home"
get "/home"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Hello world"
end
end
describe "Mounting slice routes" do
before :context do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~'RUBY'
module TestApp
class Routes < Hanami::Routes
root to: "home.show"
slice :main, at: "/main"
end
end
RUBY
write "app/actions/home/show.rb", <<~'RUBY'
require "hanami/action"
module TestApp
module Actions
module Home
class Show < Hanami::Action
def handle(*, res)
res.body = "Hello from app"
end
end
end
end
end
RUBY
write "slices/main/config/routes.rb", <<~'RUBY'
module Main
class Routes < Hanami::Routes
root to: "home.show"
end
end
RUBY
write "slices/main/actions/home/show.rb", <<~'RUBY'
require "hanami/action"
module Main
module Actions
module Home
class Show < Hanami::Action
def handle(*, res)
res.body = "Hello from slice"
end
end
end
end
end
RUBY
end
end
let(:app) { TestApp::App.app }
describe "A slice with its own router can be mounted in its parent's routes" do
context "prepared" do
before do
with_directory(@dir) { require "hanami/prepare" }
end
specify do
get "/"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Hello from app"
get "/main"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Hello from slice"
end
end
context "booted" do
before do
with_directory(@dir) { require "hanami/boot" }
end
specify do
get "/"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Hello from app"
get "/main"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Hello from slice"
end
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/operations/extension_spec.rb | spec/integration/operations/extension_spec.rb | # frozen_string_literal: true
require "dry/operation"
RSpec.describe "Operation / Extensions", :app_integration do
before do
@env = ENV.to_h
allow(Hanami::Env).to receive(:loaded?).and_return(false)
end
after { ENV.replace(@env) }
specify "Transaction interface is made available automatically" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/operation.rb", <<~RUBY
module TestApp
class Operation < Dry::Operation
end
end
RUBY
write "slices/main/operation.rb", <<~RUBY
module Main
class Operation < Dry::Operation
end
end
RUBY
write "db/.keep", ""
write "app/relations/.keep", ""
write "slices/main/db/.keep", ""
write "slices/main/relations/.keep", ""
ENV["DATABASE_URL"] = "sqlite::memory"
ENV["MAIN__DATABASE_URL"] = "sqlite::memory"
require "hanami/prepare"
app = TestApp::Operation.new
main = Main::Operation.new
expect(app).to respond_to(:transaction)
expect(app.rom).to be TestApp::App["db.rom"]
expect(app.rom).not_to be Main::Slice["db.rom"]
expect(main.rom).to be Main::Slice["db.rom"]
end
end
context "hanami-db bundled, but no db configured" do
it "does not extend the operation class" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/operation.rb", <<~RUBY
module TestApp
class Operation < Dry::Operation
end
end
RUBY
require "hanami/prepare"
operation = TestApp::Operation.new
expect(operation.rom).to be nil
expect { operation.transaction }.to raise_error Hanami::ComponentLoadError, "A configured db for TestApp::App is required to run transactions."
end
end
end
context "hanami-db not bundled" do
before do
allow(Hanami).to receive(:bundled?).and_call_original
allow(Hanami).to receive(:bundled?).with("hanami-db").and_return false
end
it "does not extend the operation class" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/operation.rb", <<~RUBY
module TestApp
class Operation < Dry::Operation
end
end
RUBY
require "hanami/prepare"
operation = TestApp::Operation.new
expect { operation.rom }.to raise_error NoMethodError
expect { operation.transaction }.to raise_error NoMethodError
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/assets/assets_spec.rb | spec/integration/assets/assets_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Assets", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
let(:root) { make_tmp_directory }
before do
with_directory(root) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/assets.js", <<~JS
import * as assets from "hanami-assets";
await assets.run();
JS
write "package.json", <<~JSON
{
"type": "module"
}
JSON
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
config.layout = nil
end
end
RUBY
write "app/views/posts/show.rb", <<~RUBY
module TestApp
module Views
module Posts
class Show < TestApp::View
end
end
end
end
RUBY
write "app/templates/posts/show.html.erb", <<~ERB
<%= stylesheet_tag("app") %>
<%= javascript_tag("app") %>
ERB
write "app/assets/js/app.ts", <<~TS
import "../css/app.css";
console.log("Hello from index.ts");
TS
write "app/assets/css/app.css", <<~CSS
.btn {
background: #f00;
}
CSS
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
specify "assets are available in helpers and in `assets` component" do
compile_assets!
output = Hanami.app["views.posts.show"].call.to_s
expect(output).to match(%r{<link href="/assets/app-[A-Z0-9]{8}.css" type="text/css" rel="stylesheet">})
expect(output).to match(%r{<script src="/assets/app-[A-Z0-9]{8}.js" type="text/javascript"></script>})
assets = Hanami.app["assets"]
expect(assets["app.css"].to_s).to match(%r{/assets/app-[A-Z0-9]{8}.css})
expect(assets["app.js"].to_s).to match(%r{/assets/app-[A-Z0-9]{8}.js})
end
describe "slice with assets" do
def before_prepare
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < TestApp::View
end
end
RUBY
write "slices/main/views/posts/show.rb", <<~RUBY
module Main
module Views
module Posts
class Show < Main::View
end
end
end
end
RUBY
write "slices/main/templates/posts/show.html.erb", <<~ERB
<%= stylesheet_tag("app") %>
<%= javascript_tag("app") %>
ERB
write "slices/main/assets/js/app.ts", <<~TS
import "../css/app.css";
console.log("Hello from main slice index.ts");
TS
write "slices/main/assets/css/app.css", <<~CSS
.btn {
background: #f00;
}
CSS
end
specify "the slice's assets are available in its own and distinct `assets` component" do
compile_assets!
output = Main::Slice["views.posts.show"].call.to_s
expect(output).to match(%r{<link href="/assets/_main/app-[A-Z0-9]{8}.css" type="text/css" rel="stylesheet">})
expect(output).to match(%r{<script src="/assets/_main/app-[A-Z0-9]{8}.js" type="text/javascript"></script>})
assets = Main::Slice["assets"]
expect(assets["app.css"].to_s).to match(%r{/assets/_main/app-[A-Z0-9]{8}.css})
expect(assets["app.js"].to_s).to match(%r{/assets/_main/app-[A-Z0-9]{8}.js})
end
end
describe "slice without assets" do
def before_prepare
write "slices/main/.keep", ""
end
it "does not have an assets component" do
expect(Main::Slice.key?("assets")).to be false
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/assets/cross_slice_assets_helpers_spec.rb | spec/integration/assets/cross_slice_assets_helpers_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Cross-slice assets via helpers", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
let(:root) { make_tmp_directory }
before do
with_directory(root) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
# TODO: we should update `import` to make importing from the app nicer
# TODO: this test failed when I tried doing `as: "app"` (string instead of symbol); fix this in dry-system
import keys: ["assets"], from: Hanami.app.container, as: :app
end
end
RUBY
write "config/assets.js", <<~JS
import * as assets from "hanami-assets";
await assets.run();
JS
write "package.json", <<~JSON
{
"type": "module"
}
JSON
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
config.layout = nil
end
end
RUBY
write "app/assets/js/app.ts", <<~TS
import "../css/app.css";
console.log("Hello from index.ts");
TS
write "app/assets/css/app.css", <<~CSS
.btn {
background: #f00;
}
CSS
write "slices/admin/assets/js/app.ts", <<~TS
import "../css/app.css";
console.log("Hello from admin's index.ts");
TS
write "slices/admin/assets/css/app.css", <<~CSS
.btn {
background: #f00;
}
CSS
write "slices/admin/view.rb", <<~RUBY
# auto_register: false
module Admin
class View < TestApp::View
end
end
RUBY
write "slices/admin/views/posts/show.rb", <<~RUBY
module Admin
module Views
module Posts
class Show < Admin::View
end
end
end
end
RUBY
write "slices/admin/views/context.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module Admin
module Views
class Context < Hanami::View::Context
include Deps[app_assets: "app.assets"]
end
end
end
RUBY
write "slices/admin/templates/posts/show.html.erb", <<~ERB
<%= stylesheet_tag(app_assets["app.css"]) %>
<%= javascript_tag(app_assets["app.js"]) %>
ERB
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
specify "assets are available in helpers and in `assets` component" do
compile_assets!
output = Admin::Slice["views.posts.show"].call.to_s
expect(output).to match(%r{<link href="/assets/app-[A-Z0-9]{8}.css" type="text/css" rel="stylesheet">})
expect(output).to match(%r{<script src="/assets/app-[A-Z0-9]{8}.js" type="text/javascript"></script>})
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/assets/serve_static_assets_spec.rb | spec/integration/assets/serve_static_assets_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Serve Static Assets", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
let(:root) { make_tmp_directory }
let!(:env) { ENV.to_h }
before do
with_directory(root) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
root to: ->(env) { [200, {}, ["Hello from root"]] }
end
end
RUBY
write "public/assets/app.js", <<~JS
console.log("Hello from app.js");
JS
end
end
after do
ENV.replace(env)
end
context "with default configuration" do
before do
with_directory(root) do
require "hanami/prepare"
end
end
it "serves static assets" do
get "/assets/app.js"
expect(last_response.status).to eq(200)
expect(last_response.body).to match(/Hello/)
end
it "returns 404 for missing asset" do
get "/assets/missing.js"
expect(last_response.status).to eq(404)
expect(last_response.body).to match(/Not Found/i)
end
it "doesn't escape from root directory" do
get "/assets/../../config/app.rb"
expect(last_response.status).to eq(404)
expect(last_response.body).to match("Hanami::Router::NotFoundError")
end
end
context "when configuration is set to false" do
before do
with_directory(root) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
config.assets.serve = false
end
end
RUBY
require "hanami/boot"
end
end
it "doesn't serve static assets" do
get "/assets/app.js"
expect(last_response.status).to eq(404)
end
end
context "when env var is set to true" do
before do
with_directory(root) do
ENV["HANAMI_SERVE_ASSETS"] = "true"
require "hanami/boot"
end
end
it "serves static assets" do
get "/assets/app.js"
expect(last_response.status).to eq(200)
end
end
context "when env var is set to false" do
before do
with_directory(root) do
ENV["HANAMI_SERVE_ASSETS"] = "false"
require "hanami/boot"
end
end
it "doesn't serve static assets" do
get "/assets/app.js"
expect(last_response.status).to eq(404)
end
end
context "when Hanami.env is not :development or :test" do
before do
with_directory(root) do
ENV["HANAMI_ENV"] = "production"
require "hanami/boot"
end
end
it "doesn't serve static assets" do
get "/assets/app.js"
expect(last_response.status).to eq(404)
end
end
context "when Hanami.env is not :development or :test, but env var is set to true" do
before do
with_directory(root) do
ENV["HANAMI_ENV"] = "production"
ENV["HANAMI_SERVE_ASSETS"] = "true"
require "hanami/boot"
end
end
it "serves static assets" do
get "/assets/app.js"
expect(last_response.status).to eq(200)
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/rack_app/non_booted_rack_app_spec.rb | spec/integration/rack_app/non_booted_rack_app_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Running a Rack app for a non-booted app", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
it "lazy loads only the components required for any accessed routes" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~RUBY
require "hanami/routes"
module TestApp
class Routes < Hanami::Routes
slice :main, at: "/" do
root to: "home.show"
get "/articles", to: "articles.index"
end
end
end
RUBY
write "slices/main/lib/action.rb", <<~RUBY
# auto_register: false
require "hanami/action"
module Main
class Action < Hanami::Action
end
end
RUBY
write "slices/main/lib/article_repo.rb", <<~RUBY
module Main
class ArticleRepo < Hanami::Action
end
end
RUBY
write "slices/main/lib/greeter.rb", <<~RUBY
module Main
class Greeter
def greeting
"Hello world"
end
end
end
RUBY
write "slices/main/actions/home/show.rb", <<~RUBY
module Main
module Actions
module Home
class Show < Main::Action
include Deps["greeter"]
def handle(req, res)
res.body = greeter.greeting
end
end
end
end
end
RUBY
write "slices/main/actions/articles/index.rb", <<~RUBY
module Main
module Actions
module Articles
class Index < Main::Action
include Deps["article_repo"]
end
end
end
end
RUBY
require "hanami/prepare"
get "/"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Hello world"
expect(Hanami.app).not_to be_booted
expect(Main::Slice.keys).to include(*%w[actions.home.show greeter])
expect(Main::Slice.keys).not_to include(*%w[actions.articles.index article_repo])
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/rack_app/middleware_spec.rb | spec/integration/rack_app/middleware_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Hanami web app", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
around do |example|
with_tmp_directory(Dir.mktmpdir, &example)
end
before do
module TestApp
module Middlewares
class Core
def initialize(app)
@app = app
end
end
class Prepare < Core
def call(env)
env["tested"] = []
@app.call(env)
end
end
class AppendOne < Core
def call(env)
env["tested"] << "one"
@app.call(env)
end
end
class AppendTwo < Core
def call(env)
env["tested"] << "two"
@app.call(env)
end
end
end
end
end
specify "Setting middlewares in the config" do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
config.middleware.use Middlewares::AppendOne
config.middleware.use Middlewares::Prepare, before: Middlewares::AppendOne
config.middleware.use Middlewares::AppendTwo, after: Middlewares::AppendOne
end
end
RUBY
write "config/routes.rb", <<~RUBY
require "hanami/router"
module TestApp
class Routes < Hanami::Routes
slice :main, at: "/" do
root to: "home.index"
end
end
end
RUBY
write "slices/main/actions/home/index.rb", <<~RUBY
require "hanami/action"
module Main
module Actions
module Home
class Index < Hanami::Action
def handle(req, res)
res.body = req.env["tested"].join(".")
end
end
end
end
end
RUBY
require "hanami/boot"
get "/"
expect(last_response).to be_successful
expect(last_response.body).to eql("one.two")
end
specify "Setting middlewares in the router" do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~RUBY
require "hanami/router"
module TestApp
class Routes < Hanami::Routes
slice :main, at: "/" do
use TestApp::Middlewares::AppendOne
use TestApp::Middlewares::Prepare, before: TestApp::Middlewares::AppendOne
use TestApp::Middlewares::AppendTwo, after: TestApp::Middlewares::AppendOne
root to: "home.index"
end
end
end
RUBY
write "slices/main/actions/home/index.rb", <<~RUBY
require "hanami/action"
module Main
module Actions
module Home
class Index < Hanami::Action
def handle(req, res)
res.body = req.env["tested"].join(".")
end
end
end
end
end
RUBY
require "hanami/boot"
get "/"
expect(last_response).to be_successful
expect(last_response.body).to eql("one.two")
end
specify "Setting a middleware that requires keyword arguments" do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class TestMiddleware
def initialize(app, key:, value:)
@app = app
@key = key
@value = value
end
def call(env)
env[@key] = @value
@app.call(env)
end
end
class App < Hanami::App
config.logger.stream = StringIO.new
# Test middleware with keywords inside config
config.middleware.use(TestApp::TestMiddleware, key: "from_config", value: "config")
end
end
RUBY
write "config/routes.rb", <<~RUBY
require "hanami/router"
module TestApp
class Routes < Hanami::Routes
slice :main, at: "/" do
# Also test middleware with keywords inside routes
use TestApp::TestMiddleware, key: "from_routes", value: "routes"
root to: "home.index"
end
end
end
RUBY
write "slices/main/actions/home/index.rb", <<~RUBY
require "hanami/action"
module Main
module Actions
module Home
class Index < Hanami::Action
def handle(request, response)
response.body = [request.env["from_config"], request.env["from_routes"]].join(", ")
end
end
end
end
end
RUBY
require "hanami/boot"
get "/"
expect(last_response).to be_successful
expect(last_response.body).to eq "config, routes"
end
specify "Setting a middleware that requires a block" do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class TestMiddleware
def initialize(app, &block)
@app = app
@block = block
end
def call(env)
@block.call(env)
@app.call(env)
end
end
class App < Hanami::App
config.logger.stream = StringIO.new
config.middleware.use(TestApp::TestMiddleware) { |env| env["tested"] = "yes" }
end
end
RUBY
write "config/routes.rb", <<~RUBY
require "hanami/router"
module TestApp
class Routes < Hanami::Routes
slice :main, at: "/" do
root to: "home.index"
end
end
end
RUBY
write "slices/main/actions/home/index.rb", <<~RUBY
require "hanami/action"
module Main
module Actions
module Home
class Index < Hanami::Action
def handle(req, res)
res.body = req.env["tested"]
end
end
end
end
end
RUBY
require "hanami/boot"
get "/"
expect(last_response).to be_successful
expect(last_response.body).to eql("yes")
end
context "Using module as a middleware" do
it "sets the module as the middleware" do
mod = Module.new
app = Class.new(Hanami::App) { config.middleware.use(mod) }
expect(app.config.middleware.stack["/"][0]).to include(mod)
end
end
context "Setting an unsupported middleware" do
it "raises meaningful error when an unsupported middleware spec was passed" do
expect {
Class.new(Hanami::App) do
config.middleware.use("oops")
end
}.to raise_error(Hanami::UnsupportedMiddlewareSpecError)
end
it "raises meaningful error when corresponding file failed to load" do
expect {
Class.new(Hanami::App) do
config.middleware.namespaces.delete(Hanami::Middleware)
config.middleware.use(:body_parser)
end
}.to raise_error(Hanami::UnsupportedMiddlewareSpecError)
end
end
context "with simple app" do
before do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File.new("/dev/null", "w")
config.render_errors = true
end
end
RUBY
write "lib/test_app/middleware/authentication.rb", <<~RUBY
module TestApp
module Middleware
class Authentication
def self.inspect
"<Middleware::Auth>"
end
def initialize(app)
@app = app
end
def call(env)
env["AUTH_USER_ID"] = user_id = "23"
status, headers, body = @app.call(env)
headers["X-Auth-User-ID"] = user_id
[status, headers, body]
end
end
end
end
RUBY
write "config/routes.rb", <<~RUBY
require "test_app/middleware/authentication"
module TestApp
class Routes < Hanami::Routes
root to: ->(*) { [200, {"Content-Length" => "4"}, ["Home"]] }
slice :admin, at: "/admin" do
use TestApp::Middleware::Authentication
root to: "home.show"
end
end
end
RUBY
write "slices/admin/actions/home/show.rb", <<~RUBY
module Admin
module Actions
module Home
class Show < Hanami::Action
def handle(req, res)
res.body = "Hello from admin (User ID " + req.env['AUTH_USER_ID'] + ")"
end
end
end
end
end
RUBY
require "hanami/boot"
end
it "excludes root scope" do
get "/"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Home"
expect(last_response.headers).to_not have_key("X-Auth-User-ID")
end
it "excludes not found routes in root scope" do
get "/foo"
expect(last_response.status).to eq 404
expect(last_response.headers).to_not have_key("X-Auth-User-ID")
end
context "within slice" do
it "uses Rack middleware" do
get "/admin"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Hello from admin (User ID 23)"
expect(last_response.headers).to have_key("X-Auth-User-ID")
end
it "does not uses the Rack middleware for not found paths" do
get "/admin/users"
expect(last_response.status).to eq 404
expect(last_response.headers).not_to have_key("X-Auth-User-ID")
end
end
end
context "with complex app" do
let(:app_modules) { %i[TestApp Admin APIV1] }
before do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File.new("/dev/null", "w")
config.render_errors = true
end
end
RUBY
write "lib/test_app/middleware/elapsed.rb", <<~RUBY
module TestApp
module Middleware
class Elapsed
def self.inspect
"<Middleware::Elapsed>"
end
def initialize(app)
@app = app
end
def call(env)
with_time_instrumentation do
@app.call(env)
end
end
private
def with_time_instrumentation
starting = now
status, headers, body = yield
ending = now
headers["X-Elapsed"] = (ending - starting).round(5).to_s
[status, headers, body]
end
def now
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
end
end
end
RUBY
write "lib/test_app/middleware/authentication.rb", <<~RUBY
module TestApp
module Middleware
class Authentication
def self.inspect
"<Middleware::Auth>"
end
def initialize(app)
@app = app
end
def call(env)
env["AUTH_USER_ID"] = user_id = "23"
status, headers, body = @app.call(env)
headers["X-Auth-User-ID"] = user_id
[status, headers, body]
end
end
end
end
RUBY
write "lib/test_app/middleware/rate_limiter.rb", <<~RUBY
module TestApp
module Middleware
class RateLimiter
def self.inspect
"<Middleware::API::Limiter>"
end
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
headers["X-API-Rate-Limit-Quota"] = "4000"
[status, headers, body]
end
end
end
end
RUBY
write "lib/test_app/middleware/api_version.rb", <<~RUBY
module TestApp
module Middleware
class APIVersion
def self.inspect
"<Middleware::API::Version>"
end
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
headers["X-API-Version"] = "1"
[status, headers, body]
end
end
end
end
RUBY
write "lib/test_app/middleware/api_deprecation.rb", <<~RUBY
module TestApp
module Middleware
class APIDeprecation
def self.inspect
"<Middleware::API::Deprecation>"
end
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
headers["X-API-Deprecated"] = "API v1 is deprecated"
[status, headers, body]
end
end
end
end
RUBY
write "lib/test_app/middleware/scope_identifier.rb", <<~RUBY
module TestApp
module Middleware
class ScopeIdentifier
def self.inspect
"<Middleware::API::ScopeIdentifier>"
end
def initialize(app, scope)
@app = app
@scope = scope
end
def call(env)
status, header, body = @app.call(env)
header["X-Identifier-" + @scope] = "true"
[status, header, body]
end
def inspect
"Scope identifier: " + @scope.inspect
end
end
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
use TestApp::Middleware::Elapsed
use TestApp::Middleware::ScopeIdentifier, "Root"
root to: ->(*) { [200, {"Content-Length" => "4"}, ["Home (complex app)"]] }
mount ->(*) { [200, {"Content-Length" => "7"}, ["Mounted"]] }, at: "/mounted"
slice :admin, at: "/admin" do
use TestApp::Middleware::Authentication
use TestApp::Middleware::ScopeIdentifier, "Admin"
root to: "home.show"
end
# Without leading slash
# See: https://github.com/hanami/api/issues/8
scope "api" do
use TestApp::Middleware::RateLimiter
use TestApp::Middleware::ScopeIdentifier, "API"
root to: ->(*) { [200, {"Content-Length" => "3"}, ["API"]] }
slice :api_v1, at: "/v1" do
use TestApp::Middleware::APIVersion
use TestApp::Middleware::APIDeprecation
use TestApp::Middleware::ScopeIdentifier, "API-V1"
root to: "home.show"
end
end
end
end
RUBY
write "slices/admin/actions/home/show.rb", <<~RUBY
module Admin
module Actions
module Home
class Show < Hanami::Action
def handle(req, res)
res.body = "Hello from admin (User ID " + req.env['AUTH_USER_ID'] + ")"
end
end
end
end
end
RUBY
write "slices/api_v1/actions/home/show.rb", <<~RUBY
module APIV1
module Actions
module Home
class Show < Hanami::Action
def handle(req, res)
res.body = "API v1"
end
end
end
end
end
RUBY
require "hanami/boot"
end
it "uses Rack middleware" do
get "/"
expect(last_response.status).to be(200)
expect(last_response.body).to eq("Home (complex app)")
expect(last_response.headers["X-Identifier-Root"]).to eq("true")
expect(last_response.headers).to have_key("X-Elapsed")
expect(last_response.headers).to_not have_key("X-Auth-User-ID")
expect(last_response.headers).to_not have_key("X-API-Rate-Limit-Quota")
expect(last_response.headers).to_not have_key("X-API-Version")
end
it "does not use Rack middleware for other paths" do
get "/__not_found__"
expect(last_response.status).to eq 404
expect(last_response.headers).not_to have_key("X-Identifier-Root")
expect(last_response.headers).not_to have_key("X-Elapsed")
expect(last_response.headers).not_to have_key("X-Auth-User-ID")
expect(last_response.headers).not_to have_key("X-API-Rate-Limit-Quota")
expect(last_response.headers).not_to have_key("X-API-Version")
end
context "scoped" do
it "uses Rack middleware" do
get "/admin"
expect(last_response.status).to be(200)
expect(last_response.headers["X-Identifier-Admin"]).to eq("true")
expect(last_response.headers).to have_key("X-Elapsed")
expect(last_response.headers).to have_key("X-Auth-User-ID")
expect(last_response.headers).to_not have_key("X-API-Rate-Limit-Quota")
expect(last_response.headers).to_not have_key("X-API-Version")
end
it "uses Rack middleware for other paths" do
get "/admin/__not_found__"
expect(last_response.status).to eq 404
expect(last_response.headers).not_to have_key("X-Identifier-Admin")
expect(last_response.headers).not_to have_key("X-Elapsed")
expect(last_response.headers).not_to have_key("X-Elapsed")
expect(last_response.headers).not_to have_key("X-Auth-User-ID")
expect(last_response.headers).not_to have_key("X-API-Rate-Limit-Quota")
expect(last_response.headers).not_to have_key("X-API-Version")
end
# See: https://github.com/hanami/api/issues/8
it "uses Rack middleware for scope w/o leading slash" do
get "/api"
expect(last_response.status).to be(200)
expect(last_response.headers["X-Identifier-Api"]).to eq("true")
expect(last_response.headers).to have_key("X-Elapsed")
expect(last_response.headers).to_not have_key("X-Auth-User-ID")
expect(last_response.headers).to have_key("X-API-Rate-Limit-Quota")
expect(last_response.headers).to_not have_key("X-API-Version")
end
# See: https://github.com/hanami/api/issues/8
it "uses Rack middleware for nested scope w/o leading slash" do
get "/api/v1"
expect(last_response.status).to be(200)
expect(last_response.headers["X-Identifier-API-V1"]).to eq("true")
expect(last_response.headers).to have_key("X-Elapsed")
expect(last_response.headers).to_not have_key("X-Auth-User-ID")
expect(last_response.headers).to have_key("X-API-Rate-Limit-Quota")
expect(last_response.headers).to have_key("X-API-Deprecated")
expect(last_response.headers["X-API-Version"]).to eq("1")
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/rack_app/body_parser_spec.rb | spec/integration/rack_app/body_parser_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Hanami web app", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
around do |example|
with_tmp_directory(Dir.mktmpdir, &example)
end
specify "Default body parser" do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.actions.format :json
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
post "/users", to: "users.create"
end
end
RUBY
write "app/actions/users/create.rb", <<~RUBY
module TestApp
module Actions
module Users
class Create < Hanami::Action
def handle(req, res)
res.body = req.params[:users].join("-")
end
end
end
end
end
RUBY
require "hanami/boot"
post(
"/users",
JSON.dump("users" => %w[jane john jade joe]),
"CONTENT_TYPE" => "application/json"
)
expect(last_response).to be_successful
expect(last_response.body).to eql("jane-john-jade-joe")
end
specify "Configuring custom mime-types and body parser" do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.actions.formats.register :json, "application/json+scim"
config.actions.formats.accept :json
config.middleware.use :body_parser, [json: "application/json+scim"]
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
post "/users", to: "users.create"
end
end
RUBY
write "app/actions/users/create.rb", <<~RUBY
module TestApp
module Actions
module Users
class Create < Hanami::Action
def handle(req, res)
res.body = req.params[:users].join("-")
end
end
end
end
end
RUBY
require "hanami/boot"
post(
"/users",
JSON.dump("users" => %w[jane john jade joe]),
"CONTENT_TYPE" => "application/json+scim"
)
expect(last_response).to be_successful
expect(last_response.body).to eql("jane-john-jade-joe")
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/rack_app/rack_app_spec.rb | spec/integration/rack_app/rack_app_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Hanami web app", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
specify "Hanami.app returns a rack builder" do
with_tmp_directory do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
root to: ->(env) { [200, {}, ["OK"]] }
end
end
RUBY
require "hanami/boot"
expect(app).to be(TestApp::App)
end
end
specify "Routing to actions based on their container identifiers" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
get "/health", to: "health.show"
get "/inline" do
"Inline"
end
slice :main, at: "/" do
root to: "home.index"
end
slice :admin, at: "/admin" do
get "/dashboard", to: "dashboard.show"
end
end
end
RUBY
write "app/actions/health/show.rb", <<~RUBY
require "hanami/action"
module TestApp
module Actions
module Health
class Show < Hanami::Action
def handle(*, res)
res.body = "Health, OK"
end
end
end
end
end
RUBY
write "slices/main/actions/home/index.rb", <<~RUBY
require "hanami/action"
module Main
module Actions
module Home
class Index < Hanami::Action
def handle(*, res)
res.body = "Hello world"
end
end
end
end
end
RUBY
write "slices/admin/actions/dashboard/show.rb", <<~RUBY
require "hanami/action"
module Admin
module Actions
module Dashboard
class Show < Hanami::Action
def handle(*, res)
res.body = "Admin dashboard here"
end
end
end
end
end
RUBY
require "hanami/boot"
get "/"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Hello world"
get "/inline"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Inline"
get "/health"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Health, OK"
get "/admin/dashboard"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Admin dashboard here"
end
end
# TODO: is this test even needed, given this is standard hanami-router behavior?
specify "It gives priority to the last declared route" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
root to: "home.index"
slice :main, at: "/" do
root to: "home.index"
end
end
end
RUBY
write "app/actions/home/index.rb", <<~RUBY
require "hanami/action"
module TestApp
module Actions
module Home
class Index < Hanami::Action
def handle(*, res)
res.body = "Hello from App"
end
end
end
end
end
RUBY
write "slices/main/actions/home/index.rb", <<~RUBY
require "hanami/action"
module Main
module Actions
module Home
class Index < Hanami::Action
def handle(*, res)
res.body = "Hello from Slice"
end
end
end
end
end
RUBY
require "hanami/boot"
get "/"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "Hello from Slice"
end
end
specify "It does not choose actions from slice to route in app" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
get "/feedbacks", to: "feedbacks.index"
slice :api, at: "/api" do
get "/people", to: "people.index"
end
end
end
RUBY
write "app/action.rb", <<~RUBY
# auto_register: false
require "hanami/action"
module TestApp
class Action < Hanami::Action
end
end
RUBY
write "app/actions/feedbacks/index.rb", <<~RUBY
module TestApp
module Actions
module Feedbacks
class Index < TestApp::Action
def handle(*, res)
res.body = "Feedbacks"
end
end
end
end
end
RUBY
write "slices/api/action.rb", <<~RUBY
module API
class Action < TestApp::Action
end
end
RUBY
write "slices/api/actions/people/index.rb", <<~RUBY
module API
module Actions
module People
class Index < API::Action
def handle(*, res)
res.body = "People"
end
end
end
end
end
RUBY
require "hanami/boot"
get "/api/people"
expect(last_response.status).to eq 200
expect(last_response.body).to eq "People"
end
end
specify "For a booted app, rack_app raises an exception if a referenced action isn't registered in the app" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
get "/missing", to: "missing.action"
end
end
RUBY
require "hanami/boot"
expect { Hanami.app.rack_app }.to raise_error do |exception|
expect(exception).to be_kind_of(Hanami::Routes::MissingActionError)
expect(exception.message).to include("Could not find action with key \"actions.missing.action\" in TestApp::App")
expect(exception.message).to include("define the action class TestApp::Actions::Missing::Action in app/actions/missing/action.rb")
end
end
end
specify "For a booted app, rack_app raises an error if a referenced action isn't registered in a slice" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
register_slice :admin
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
slice :admin, at: "/admin" do
get "/missing", to: "missing.action"
end
end
end
RUBY
require "hanami/boot"
expect { Hanami.app.rack_app }.to raise_error do |exception|
expect(exception).to be_kind_of(Hanami::Routes::MissingActionError)
expect(exception.message).to include("Could not find action with key \"actions.missing.action\" in Admin::Slice")
expect(exception.message).to include("define the action class Admin::Actions::Missing::Action in slices/admin/actions/missing/action.rb")
end
end
end
specify "For a non-booted app, rack_app does not raise an error if a referenced action isn't registered in the app" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.render_detailed_errors = false
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
get "/missing", to: "missing.action"
end
end
RUBY
require "hanami/prepare"
expect { Hanami.app.rack_app }.not_to raise_error
expect { get "/missing" }.to raise_error do |exception|
expect(exception).to be_kind_of(Hanami::Routes::MissingActionError)
expect(exception.message).to include("Could not find action with key \"actions.missing.action\" in TestApp::App")
expect(exception.message).to match(%r{define the action class TestApp::Actions::Missing::Action.+actions/missing/action.rb})
end
end
end
specify "For a non-booted app, rack_app does not raise an error if a referenced action isn't registered in a slice" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.render_detailed_errors = false
register_slice :admin
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
slice :admin, at: "/admin" do
get "/missing", to: "missing.action"
end
end
end
RUBY
require "hanami/prepare"
expect { Hanami.app.rack_app }.not_to raise_error
expect { get "/admin/missing" }.to raise_error do |exception|
expect(exception).to be_kind_of(Hanami::Routes::MissingActionError)
expect(exception.message).to include("Could not find action with key \"actions.missing.action\" in Admin::Slice")
expect(exception.message).to match(%r{define the action class Admin::Actions::Missing::Action.+slices/admin/actions/missing/action.rb})
end
end
end
specify "rack_app raises an error if a referenced slice is not registered" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
slice :foo, at: "/foo" do
get "/bar", to: "bar.index"
end
end
end
RUBY
require "hanami/prepare"
expect { Hanami.app.rack_app }.to raise_error do |exception|
expect(exception).to be_kind_of(Hanami::SliceLoadError)
expect(exception.message).to include("Slice 'foo' not found")
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/rack_app/method_override_spec.rb | spec/integration/rack_app/method_override_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Hanami web app: Method Override", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
around do |example|
with_tmp_directory(Dir.mktmpdir, &example)
end
context "enabled by default" do
before do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
generate_app_code
end
it "overrides the original HTTP method" do
post(
"/users/:id",
{"_method" => "PUT"},
"CONTENT_TYPE" => "multipart/form-data"
)
expect(last_response).to be_successful
expect(last_response.body).to eq("PUT")
end
end
context "when disabled" do
before do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
config.actions.method_override = false
end
end
RUBY
generate_app_code
end
it "overrides the original HTTP method" do
post(
"/users/:id",
{"_method" => "PUT"},
"CONTENT_TYPE" => "multipart/form-data"
)
expect(last_response).to_not be_successful
expect(last_response.status).to be(404)
end
end
private
def generate_app_code
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
put "/users/:id", to: "users.update"
end
end
RUBY
write "app/actions/users/update.rb", <<~RUBY
module TestApp
module Actions
module Users
class Update < Hanami::Action
def handle(req, res)
res.body = req.env.fetch("REQUEST_METHOD")
end
end
end
end
end
RUBY
require "hanami/boot"
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/slice_configuration_spec.rb | spec/integration/view/slice_configuration_spec.rb | # frozen_string_literal: true
RSpec.describe "App view / Slice configuration", :app_integration do
before do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
require "hanami/view"
module TestApp
class View < Hanami::View
end
end
RUBY
require "hanami/setup"
end
end
def prepare_app
with_directory(@dir) { require "hanami/prepare" }
end
describe "inheriting from app-level base class" do
describe "app-level base class" do
it "applies default views config from the app", :aggregate_failures do
prepare_app
expect(TestApp::View.config.layouts_dir).to eq "layouts"
expect(TestApp::View.config.layout).to eq "app"
end
it "applies views config from the app" do
Hanami.app.config.views.layout = "app_layout"
prepare_app
expect(TestApp::View.config.layout).to eq "app_layout"
end
it "does not override config in the base class" do
Hanami.app.config.views.layout = "app_layout"
prepare_app
TestApp::View.config.layout = "custom_layout"
expect(TestApp::View.config.layout).to eq "custom_layout"
end
end
describe "subclass in app" do
before do
with_directory(@dir) do
write "app/views/articles/index.rb", <<~RUBY
module TestApp
module Views
module Articles
class Index < TestApp::View
end
end
end
end
RUBY
end
end
it "applies default views config from the app", :aggregate_failures do
prepare_app
expect(TestApp::Views::Articles::Index.config.layouts_dir).to eq "layouts"
expect(TestApp::Views::Articles::Index.config.layout).to eq "app"
end
it "applies views config from the app" do
Hanami.app.config.views.layout = "app_layout"
prepare_app
expect(TestApp::Views::Articles::Index.config.layout).to eq "app_layout"
end
it "applies config from the base class" do
prepare_app
TestApp::View.config.layout = "base_class_layout"
expect(TestApp::Views::Articles::Index.config.layout).to eq "base_class_layout"
end
end
describe "subclass in slice" do
before do
with_directory(@dir) do
write "slices/admin/views/articles/index.rb", <<~RUBY
module Admin
module Views
module Articles
class Index < TestApp::View
end
end
end
end
RUBY
end
end
it "applies default views config from the app", :aggregate_failures do
prepare_app
expect(Admin::Views::Articles::Index.config.layouts_dir).to eq "layouts"
expect(Admin::Views::Articles::Index.config.layout).to eq "app"
end
it "applies views config from the app" do
Hanami.app.config.views.layout = "app_layout"
prepare_app
expect(Admin::Views::Articles::Index.config.layout).to eq "app_layout"
end
it "applies config from the base class" do
prepare_app
TestApp::View.config.layout = "base_class_layout"
expect(Admin::Views::Articles::Index.config.layout).to eq "base_class_layout"
end
end
end
describe "inheriting from a slice-level base class, in turn inheriting from an app-level base class" do
before do
with_directory(@dir) do
write "slices/admin/view.rb", <<~RUBY
module Admin
class View < TestApp::View
end
end
RUBY
end
end
describe "slice-level base class" do
it "applies default views config from the app", :aggregate_failures do
prepare_app
expect(Admin::View.config.layouts_dir).to eq "layouts"
expect(Admin::View.config.layout).to eq "app"
end
it "applies views config from the app" do
Hanami.app.config.views.layout = "app_layout"
prepare_app
expect(Admin::View.config.layout).to eq "app_layout"
end
it "applies config from the app base class" do
prepare_app
TestApp::View.config.layout = "app_base_class_layout"
expect(Admin::View.config.layout).to eq "app_base_class_layout"
end
context "slice views config present" do
before do
with_directory(@dir) do
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
config.views.layout = "slice_layout"
end
end
RUBY
end
end
it "applies views config from the slice" do
prepare_app
expect(Admin::View.config.layout).to eq "slice_layout"
end
it "prefers views config from the slice over config from the app-level base class" do
prepare_app
TestApp::View.config.layout = "app_base_class_layout"
expect(Admin::View.config.layout).to eq "slice_layout"
end
it "prefers config from the base class over views config from the slice" do
prepare_app
TestApp::View.config.layout = "app_base_class_layout"
Admin::View.config.layout = "slice_base_class_layout"
expect(Admin::View.config.layout).to eq "slice_base_class_layout"
end
end
end
describe "subclass in slice" do
before do
with_directory(@dir) do
write "slices/admin/views/articles/index.rb", <<~RUBY
module Admin
module Views
module Articles
class Index < Admin::View
end
end
end
end
RUBY
end
end
it "applies default views config from the app", :aggregate_failures do
prepare_app
expect(Admin::Views::Articles::Index.config.layouts_dir).to eq "layouts"
expect(Admin::Views::Articles::Index.config.layout).to eq "app"
end
it "applies views config from the app" do
Hanami.app.config.views.layout = "app_layout"
prepare_app
expect(Admin::Views::Articles::Index.config.layout).to eq "app_layout"
end
it "applies views config from the slice" do
with_directory(@dir) do
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
config.views.layout = "slice_layout"
end
end
RUBY
end
prepare_app
expect(Admin::Views::Articles::Index.config.layout).to eq "slice_layout"
end
it "applies config from the slice base class" do
prepare_app
Admin::View.config.layout = "slice_base_class_layout"
expect(Admin::Views::Articles::Index.config.layout).to eq "slice_base_class_layout"
end
it "prefers config from the slice base class over views config from the slice" do
with_directory(@dir) do
write "config/slices/admin.rb", <<~RUBY
module Admin
class Slice < Hanami::Slice
config.views.layout = "slice_layout"
end
end
RUBY
end
prepare_app
Admin::View.config.layout = "slice_base_class_layout"
expect(Admin::Views::Articles::Index.config.layout).to eq "slice_base_class_layout"
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/views_spec.rb | spec/integration/view/views_spec.rb | # frozen_string_literal: true
RSpec.describe "Hanami view integration", :app_integration do
specify "Views take their configuration from their slice in which they are defined" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
end
end
RUBY
write "app/views/users/show.rb", <<~RUBY
module TestApp
module Views
module Users
class Show < TestApp::View
expose :name
end
end
end
end
RUBY
write "app/templates/layouts/app.html.slim", <<~SLIM
html
body
== yield
SLIM
write "app/templates/users/show.html.slim", <<~'SLIM'
h1 Hello, #{name}
SLIM
require "hanami/prepare"
rendered = TestApp::App["views.users.show"].(name: "Jennifer")
expect(rendered.to_s).to eq "<html><body><h1>Hello, Jennifer</h1></body></html>"
end
end
specify "Views can also take configuration from the app when defined in the top-level app module" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
end
end
RUBY
write "app/views/users/show.rb", <<~RUBY
module TestApp
module Views
module Users
class Show < TestApp::View
expose :name
end
end
end
end
RUBY
write "app/templates/layouts/app.html.slim", <<~SLIM
html
body
== yield
SLIM
write "app/templates/users/show.html.slim", <<~'SLIM'
h1 Hello, #{name}
SLIM
require "hanami/prepare"
rendered = TestApp::App["views.users.show"].(name: "Jennifer")
expect(rendered.to_s).to eq "<html><body><h1>Hello, Jennifer</h1></body></html>"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/parts/default_rendering_spec.rb | spec/integration/view/parts/default_rendering_spec.rb | # frozen_string_literal: true
RSpec.describe "App view / Parts / Default rendering", :app_integration do
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
config.layout = nil
end
end
RUBY
write "app/views/part.rb", <<~RUBY
# auto_register: false
module TestApp
module Views
class Part < Hanami::View::Part
end
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "app part" do
def before_prepare
write "app/views/helpers.rb", <<~RUBY
# auto_register: false
module TestApp
module Views
module Helpers
def app_screaming_snake_case(str)
_context.inflector
.underscore(str)
.gsub(/\s+/, "_")
.upcase + "!"
end
end
end
end
RUBY
write "app/views/parts/post.rb", <<~RUBY
# auto_register: false
module TestApp
module Views
module Parts
class Post < TestApp::Views::Part
def title_tag
helpers.tag.h1(helpers.app_screaming_snake_case(value.title))
end
end
end
end
end
RUBY
end
it "provides a default rendering from the app" do
post = Struct.new(:title).new("Hello world")
part = TestApp::Views::Parts::Post.new(value: post)
expect(part.title_tag).to eq "<h1>HELLO_WORLD!</h1>"
end
end
describe "slice part" do
def before_prepare
write "slices/main/views/helpers.rb", <<~RUBY
# auto_register: false
module Main
module Views
module Helpers
def slice_screaming_snake_case(str)
_context.inflector
.underscore(str)
.gsub(/\s+/, "_")
.upcase + "!"
end
end
end
end
RUBY
write "slices/main/views/part.rb", <<~RUBY
# auto_register: false
module Main
module Views
class Part < TestApp::View::Part
end
end
end
RUBY
write "slices/main/views/parts/post.rb", <<~RUBY
# auto_register: false
module Main
module Views
module Parts
class Post < Main::Views::Part
def title_tag
helpers.tag.h1(helpers.slice_screaming_snake_case(value.title))
end
end
end
end
end
RUBY
end
it "provides a default rendering from the app" do
post = Struct.new(:title).new("Hello world")
part = Main::Views::Parts::Post.new(value: post)
expect(part.title_tag).to eq "<h1>HELLO_WORLD!</h1>"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/helpers/part_helpers_spec.rb | spec/integration/view/helpers/part_helpers_spec.rb | # frozen_string_literal: true
RSpec.describe "App view / Helpers / Part helpers", :app_integration do
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
config.layout = nil
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "app view and parts" do
def before_prepare
write "app/views/posts/show.rb", <<~RUBY
module TestApp
module Views
module Posts
class Show < TestApp::View
expose :post
end
end
end
end
RUBY
write "app/views/parts/post.rb", <<~RUBY
module TestApp
module Views
module Parts
class Post < TestApp::Views::Part
def number
helpers.format_number(value.number)
end
end
end
end
end
RUBY
write "app/templates/posts/show.html.erb", <<~ERB
<h1><%= post.number %></h1>
ERB
end
it "makes default helpers available in parts" do
post = Data.define(:number).new(number: 12_345)
output = TestApp::App["views.posts.show"].call(post: post).to_s.strip
expect(output).to eq "<h1>12,345</h1>"
end
end
describe "slice view and parts" do
def before_prepare
write "slices/main/view.rb", <<~RUBY
module Main
class View < TestApp::View
end
end
RUBY
write "slices/main/views/posts/show.rb", <<~RUBY
module Main
module Views
module Posts
class Show < Main::View
expose :post
end
end
end
end
RUBY
write "slices/main/views/parts/post.rb", <<~RUBY
module Main
module Views
module Parts
class Post < Main::Views::Part
def number
helpers.format_number(value.number)
end
end
end
end
end
RUBY
write "slices/main/templates/posts/show.html.erb", <<~ERB
<h1><%= post.number %></h1>
ERB
end
it "makes default helpers available in parts" do
post = Data.define(:number).new(number: 12_345)
output = Main::Slice["views.posts.show"].call(post: post).to_s.strip
expect(output).to eq "<h1>12,345</h1>"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/helpers/scope_helpers_spec.rb | spec/integration/view/helpers/scope_helpers_spec.rb | # frozen_string_literal: true
RSpec.describe "App view / Helpers / Scope helpers", :app_integration do
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
config.layout = nil
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "app view" do
def before_prepare
write "app/views/posts/show.rb", <<~RUBY
module TestApp
module Views
module Posts
class Show < TestApp::View
end
end
end
end
RUBY
write "app/templates/posts/show.html.erb", <<~ERB
<h1><%= format_number(12_345) %></h1>
ERB
end
it "makes default helpers available in templates" do
output = TestApp::App["views.posts.show"].call.to_s.strip
expect(output).to eq "<h1>12,345</h1>"
end
end
describe "slice view" do
def before_prepare
write "slices/main/view.rb", <<~RUBY
module Main
class View < TestApp::View
end
end
RUBY
write "slices/main/views/posts/show.rb", <<~RUBY
module Main
module Views
module Posts
class Show < Main::View
end
end
end
end
RUBY
write "slices/main/templates/posts/show.html.erb", <<~ERB
<h1><%= format_number(12_345) %></h1>
ERB
end
it "makes default helpers available in templates" do
output = Main::Slice["views.posts.show"].call.to_s.strip
expect(output).to eq "<h1>12,345</h1>"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/helpers/form_helper_spec.rb | spec/integration/view/helpers/form_helper_spec.rb | # frozen_string_literal: true
require "rack/test"
require "stringio"
RSpec.describe "Helpers / FormHelper", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
get "posts/:id/edit", to: "posts.edit"
put "posts/:id", to: "posts.update"
end
end
RUBY
write "app/action.rb", <<~RUBY
# auto_register: false
require "hanami/action"
module TestApp
class Action < Hanami::Action
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
config.layout = nil
end
end
RUBY
write "app/actions/posts/edit.rb", <<~RUBY
module TestApp
module Actions
module Posts
class Edit < TestApp::Action
end
end
end
end
RUBY
write "app/actions/posts/update.rb", <<~RUBY
module TestApp
module Actions
module Posts
class Update < TestApp::Action
def handle(request, response)
if valid?(request.params[:post])
response.redirect_to "/posts/x/edit"
else
response.render view
end
end
private
def valid?(post)
post.to_h[:title].to_s.length > 0
end
end
end
end
end
RUBY
write "app/views/posts/edit.rb", <<~RUBY
module TestApp
module Views
module Posts
class Edit < TestApp::View
expose :post do
Struct.new(:title, :body).new("Hello <world>", "This is the post.")
end
end
end
end
end
RUBY
write "app/templates/posts/edit.html.erb", <<~ERB
<h1>Edit post</h1>
<%= form_for("/posts") do |f| %>
<div>
Title:
<%= f.text_field "post.title" %>
</div>
<div>
Body:
<%= f.text_area "post.body" %>
</div>
<% end %>
ERB
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
it "does not have a _csrf_token field when no sessions are configured" do
get "/posts/123/edit"
html = Capybara.string(last_response.body)
expect(html).to have_no_selector("input[type='hidden'][name='_csrf_token']")
end
it "uses the value from the view's locals" do
get "/posts/123/edit"
html = Capybara.string(last_response.body)
title_field = html.find("input[name='post[title]']")
expect(title_field.value).to eq "Hello <world>"
body_field = html.find("textarea[name='post[body]']")
expect(body_field.value).to eq "This is the post."
end
it "prefers the values from the request params" do
put "/posts/123", post: {title: "", body: "This is the UPDATED post."}
html = Capybara.string(last_response.body)
title_field = html.find("input[name='post[title]']")
expect(title_field.value).to eq ""
body_field = html.find("textarea[name='post[body]']")
expect(body_field.value).to eq "This is the UPDATED post."
end
context "sessions enabled" do
def before_prepare
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
config.logger.stream = StringIO.new
config.actions.sessions = :cookie, {secret: "wxyz"*16} # Rack demands >=64 characters
end
end
RUBY
end
it "inserts a CSRF token field" do
get "/posts/123/edit"
html = Capybara.string(last_response.body)
csrf_field = html.find("input[type='hidden'][name='_csrf_token']", visible: false)
expect(csrf_field.value).to match(/[a-z0-9]{10,}/i)
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/helpers/user_defined_helpers/part_helpers_spec.rb | spec/integration/view/helpers/user_defined_helpers/part_helpers_spec.rb | # frozen_string_literal: true
RSpec.describe "App view / Helpers / User-defined helpers / Scope helpers", :app_integration do
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
config.layout = nil
end
end
RUBY
write "app/views/helpers.rb", <<~'RUBY'
# auto_register: false
module TestApp
module Views
module Helpers
def exclaim_from_app(str)
tag.h1("#{str}! (app #{_context.inflector.pluralize('helper')})")
end
end
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "app view and parts" do
def before_prepare
write "app/views/posts/show.rb", <<~RUBY
module TestApp
module Views
module Posts
class Show < TestApp::View
expose :post
end
end
end
end
RUBY
write "app/views/parts/post.rb", <<~RUBY
module TestApp
module Views
module Parts
class Post < TestApp::Views::Part
def title
helpers.exclaim_from_app(value.title)
end
end
end
end
end
RUBY
write "app/templates/posts/show.html.erb", <<~ERB
<%= post.title %>
ERB
end
it "makes user-defined helpers available in parts via a `helpers` object" do
post = Data.define(:title).new(title: "Hello world")
output = TestApp::App["views.posts.show"].call(post: post).to_s.strip
expect(output).to eq "<h1>Hello world! (app helpers)</h1>"
end
end
describe "slice view and parts" do
def before_prepare
write "slices/main/view.rb", <<~RUBY
module Main
class View < TestApp::View
# FIXME: base slice views should override paths from the base app view
config.paths = [File.join(File.expand_path(__dir__), "templates")]
end
end
RUBY
write "slices/main/views/helpers.rb", <<~'RUBY'
# auto_register: false
module Main
module Views
module Helpers
def exclaim_from_slice(str)
tag.h1("#{str}! (slice #{_context.inflector.pluralize('helper')})")
end
end
end
end
RUBY
write "slices/main/views/posts/show.rb", <<~RUBY
module Main
module Views
module Posts
class Show < Main::View
expose :post
end
end
end
end
RUBY
write "slices/main/views/parts/post.rb", <<~RUBY
module Main
module Views
module Parts
class Post < Main::Views::Part
def title
helpers.exclaim_from_slice(value.title)
end
def title_from_app
helpers.exclaim_from_app(value.title)
end
end
end
end
end
RUBY
write "slices/main/templates/posts/show.html.erb", <<~ERB
<%= post.title %>
<%= post.title_from_app %>
ERB
end
it "makes user-defined helpers (from app as well as slice) available in parts via a `helpers` object" do
post = Data.define(:title).new(title: "Hello world")
output = Main::Slice["views.posts.show"].call(post: post).to_s
expect(output).to eq <<~HTML
<h1>Hello world! (slice helpers)</h1>
<h1>Hello world! (app helpers)</h1>
HTML
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/helpers/user_defined_helpers/scope_helpers_spec.rb | spec/integration/view/helpers/user_defined_helpers/scope_helpers_spec.rb | # frozen_string_literal: true
RSpec.describe "App view / Helpers / User-defined helpers / Scope helpers", :app_integration do
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
config.layout = nil
end
end
RUBY
write "app/views/helpers.rb", <<~'RUBY'
# auto_register: false
module TestApp
module Views
module Helpers
def exclaim_from_app(str)
tag.h1("#{str}! (app helper)")
end
end
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "app view" do
def before_prepare
write "app/views/posts/show.rb", <<~RUBY
module TestApp
module Views
module Posts
class Show < TestApp::View
end
end
end
end
RUBY
write "app/templates/posts/show.html.erb", <<~ERB
<%= exclaim_from_app("Hello world") %>
ERB
end
it "makes user-defined helpers available in templates" do
output = TestApp::App["views.posts.show"].call.to_s.strip
expect(output).to eq "<h1>Hello world! (app helper)</h1>"
end
end
describe "slice view" do
def before_prepare
write "slices/main/view.rb", <<~RUBY
module Main
class View < TestApp::View
# FIXME: base slice views should override paths from the base app view
config.paths = [File.join(File.expand_path(__dir__), "templates")]
end
end
RUBY
write "slices/main/views/helpers.rb", <<~'RUBY'
# auto_register: false
module Main
module Views
module Helpers
def exclaim_from_slice(str)
tag.h1("#{str}! (slice helper)")
end
end
end
end
RUBY
write "slices/main/views/posts/show.rb", <<~RUBY
module Main
module Views
module Posts
class Show < Main::View
end
end
end
end
RUBY
write "slices/main/templates/posts/show.html.erb", <<~ERB
<%= exclaim_from_slice("Hello world") %>
<%= exclaim_from_app("Hello world") %>
ERB
end
it "makes user-defined helpers (from app as well as slice) available in templates" do
output = Main::Slice["views.posts.show"].call.to_s
expect(output).to eq <<~HTML
<h1>Hello world! (slice helper)</h1>
<h1>Hello world! (app helper)</h1>
HTML
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/config/inflector_spec.rb | spec/integration/view/config/inflector_spec.rb | # frozen_string_literal: true
require "hanami"
RSpec.describe "App view / Config / Inflector", :app_integration do
before do
module TestApp
class App < Hanami::App
config.root = "/test_app"
end
end
Hanami.app.instance_eval(&app_hook) if respond_to?(:app_hook)
Hanami.app.register_slice :main
Hanami.app.prepare
module TestApp
class View < Hanami::View
end
end
end
subject(:view_class) { TestApp::View }
context "default app inflector" do
it "configures the view with the default app inflector" do
expect(view_class.config.inflector).to be TestApp::App.config.inflector
end
end
context "custom inflections configured" do
let(:app_hook) {
proc do
config.inflections do |inflections|
inflections.acronym "NBA"
end
end
}
it "configures the view with the customized app inflector" do
expect(view_class.config.inflector).to be TestApp::App.config.inflector
expect(view_class.config.inflector.camelize("nba_jam")).to eq "NBAJam"
end
end
context "custom inflector configured on view class" do
let(:custom_inflector) { Object.new }
before do
view_class.config.inflector = custom_inflector
end
it "overrides the default app inflector" do
expect(view_class.config.inflector).to be custom_inflector
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/config/part_namespace_spec.rb | spec/integration/view/config/part_namespace_spec.rb | # frozen_string_literal: true
require "hanami"
RSpec.describe "App view / Config / Part namespace", :app_integration do
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
subject(:part_namespace) { view_class.config.part_namespace }
describe "app view" do
let(:view_class) { TestApp::View }
describe "no part namespace defined" do
it "is nil" do
expect(part_namespace).to be nil
end
end
describe "part namespace defined" do
def before_prepare
write "app/views/parts/post.rb", <<~RUBY
module TestApp
module Views
module Parts
class Post < Hanami::View::Part
end
end
end
end
RUBY
end
it "is the Views::Parts namespace within the app" do
expect(part_namespace).to eq TestApp::Views::Parts
end
end
end
describe "slice view" do
def before_prepare
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < TestApp::View
end
end
RUBY
end
let(:view_class) { Main::View }
describe "no part namespace defined" do
it "is nil" do
expect(part_namespace).to be nil
end
end
describe "part namespace defined" do
def before_prepare
super
write "slices/main/views/parts/post.rb", <<~RUBY
module Main
module Views
module Parts
class Post < Hanami::View::Part
end
end
end
end
RUBY
end
it "is the Views::Parts namespace within the slice" do
expect(part_namespace).to eq Main::Views::Parts
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/config/paths_spec.rb | spec/integration/view/config/paths_spec.rb | # frozen_string_literal: true
require "hanami"
RSpec.describe "App view / Config / Paths", :app_integration do
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
end
end
RUBY
require "hanami/setup"
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
subject(:paths) { view_class.config.paths }
describe "app view" do
let(:view_class) { TestApp::View }
it "is 'app/templates/'" do
expect(paths.map(&:dir)).to eq [Hanami.app.root.join("app", "templates")]
end
context "custom config in app" do
def before_prepare
TestApp::App.config.views.paths = ["/custom/dir"]
end
it "uses the custom config" do
expect(paths.map(&:dir)).to eq [Pathname("/custom/dir")]
end
end
end
describe "slice view" do
subject(:view_class) { Main::View }
def before_prepare
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < TestApp::View
end
end
RUBY
end
it "is 'templates/' within the slice dir" do
expect(paths.map(&:dir)).to eq [Main::Slice.root.join("templates")]
end
context "custom config in app" do
def before_prepare
super
TestApp::App.config.views.paths = ["/custom/dir"]
end
it "uses the custom config" do
expect(paths.map(&:dir)).to eq [Pathname("/custom/dir")]
end
end
context "custom config in slice" do
def before_prepare
super
write "config/slices/main.rb", <<~RUBY
module Main
class Slice < Hanami::Slice
config.views.paths = ["/custom/slice/dir"]
end
end
RUBY
end
it "uses the custom config" do
expect(paths.map(&:dir)).to eq [Pathname("/custom/slice/dir")]
end
end
context "custom config in app and slice" do
def before_prepare
super
TestApp::App.config.views.paths = ["/custom/dir"]
write "config/slices/main.rb", <<~RUBY
module Main
class Slice < Hanami::Slice
config.views.paths = ["/custom/slice/dir"]
end
end
RUBY
end
it "uses the custom config from the slice" do
expect(paths.map(&:dir)).to eq [Pathname("/custom/slice/dir")]
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/config/default_context_spec.rb | spec/integration/view/config/default_context_spec.rb | # frozen_string_literal: true
RSpec.describe "App view / Config / Default context", :app_integration do
before do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
subject(:default_context) { view_class.config.default_context }
describe "app view" do
let(:view_class) { TestApp::View }
describe "no concrete context class defined" do
it "generates an app context class and configures it as the view's default_context" do
expect(default_context).to be_an_instance_of TestApp::Views::Context
expect(default_context.class.superclass).to be Hanami::View::Context
end
end
describe "concrete context class defined" do
def before_prepare
write "app/views/context.rb", <<~RUBY
# auto_register: false
module TestApp
module Views
class Context < Hanami::View::Context
def concrete?
true
end
end
end
end
RUBY
end
it "configures the app scope class as the view's scope_class" do
expect(default_context).to be_an_instance_of TestApp::Views::Context
expect(default_context).to be_concrete
end
end
end
describe "slice view" do
let(:view_class) { Main::View }
def before_prepare
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < TestApp::View
end
end
RUBY
end
describe "no concrete slice context class defined" do
it "generates an app context class and configures it as the view's default_context" do
expect(default_context).to be_an_instance_of Main::Views::Context
expect(default_context.class.superclass).to be TestApp::Views::Context
end
end
describe "concrete slice context class defined" do
def before_prepare
super
write "slices/main/views/context.rb", <<~RUBY
# auto_register: false
module Main
module Views
class Context < Hanami::View::Context
def concrete?
true
end
end
end
end
RUBY
end
it "configures the slice context as the view's default_context" do
expect(default_context).to be_an_instance_of Main::Views::Context
expect(default_context).to be_concrete
end
end
describe "view not inheriting from app view, no concrete context class defined" do
def before_prepare
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < Hanami::View
end
end
RUBY
end
it "generates a slice context class, inheriting from the app context class, and configures it as the view's default_context" do
expect(default_context).to be_an_instance_of Main::Views::Context
expect(default_context.class.superclass).to be TestApp::Views::Context
end
end
describe "no app view class defined" do
def before_prepare
FileUtils.rm "app/view.rb"
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < Hanami::View
end
end
RUBY
end
it "generates a slice context class, inheriting from the app context class, and configures it as the view's default_context" do
expect(default_context).to be_an_instance_of Main::Views::Context
expect(default_context.class.superclass).to be Hanami::View::Context
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/config/part_class_spec.rb | spec/integration/view/config/part_class_spec.rb | # frozen_string_literal: true
RSpec.describe "App view / Config / Part class", :app_integration do
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "app view" do
let(:view_class) { TestApp::View }
context "no concrete app part class defined" do
it "generates an app part class and configures it as the view's part_class" do
expect(view_class.config.part_class).to be TestApp::Views::Part
expect(view_class.config.part_class.superclass).to be Hanami::View::Part
end
end
context "concrete app part class defined" do
def before_prepare
write "app/views/part.rb", <<~RUBY
# auto_register: false
module TestApp
module Views
class Part < Hanami::View::Part
def self.concrete?
true
end
end
end
end
RUBY
end
it "configures the app part class as the view's part_class" do
expect(view_class.config.part_class).to be TestApp::Views::Part
expect(view_class.config.part_class).to be_concrete
end
end
end
describe "slice view" do
let(:view_class) { Main::View }
def before_prepare
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < TestApp::View
end
end
RUBY
end
context "no concrete slice part class defined" do
it "generates a slice part class, inheriting from the app part class, and configures it as the view's part_class" do
expect(view_class.config.part_class).to be Main::Views::Part
expect(view_class.config.part_class.superclass).to be TestApp::Views::Part
end
end
context "concrete slice part class defined" do
def before_prepare
super
write "slices/main/views/part.rb", <<~RUBY
# auto_register: false
module Main
module Views
class Part < TestApp::Views::Part
def self.concrete?
true
end
end
end
end
RUBY
end
it "configures the slice part class as the view's part_class" do
expect(view_class.config.part_class).to be Main::Views::Part
expect(view_class.config.part_class).to be_concrete
end
end
context "view not inheriting from app view, no concrete part class" do
def before_prepare
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < Hanami::View
end
end
RUBY
end
it "generates a slice part class, inheriting from the app part class, and configures it as the view's part_class" do
expect(view_class.config.part_class).to be Main::Views::Part
expect(view_class.config.part_class.superclass).to be TestApp::Views::Part
end
end
context "no app view class defined" do
def before_prepare
FileUtils.rm "app/view.rb"
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < Hanami::View
end
end
RUBY
end
it "generates a slice part class, inheriting from Hanami::View::Part, and configures it as the view's part_class" do
expect(view_class.config.part_class).to be Main::Views::Part
expect(view_class.config.part_class.superclass).to be Hanami::View::Part
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/config/scope_class_spec.rb | spec/integration/view/config/scope_class_spec.rb | # frozen_string_literal: true
RSpec.describe "App view / Config / Scope class", :app_integration do
before do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "app view" do
let(:view_class) { TestApp::View }
describe "no concrete app scope class defined" do
it "generates an app scope class and configures it as the view's scope_class" do
expect(view_class.config.scope_class).to be TestApp::Views::Scope
expect(view_class.config.scope_class.superclass).to be Hanami::View::Scope
end
end
describe "concrete app scope class defined" do
def before_prepare
write "app/views/scope.rb", <<~RUBY
# auto_register: false
module TestApp
module Views
class Scope < Hanami::View::Scope
def self.concrete?
true
end
end
end
end
RUBY
end
it "configures the app scope class as the view's scope_class" do
expect(view_class.config.scope_class).to be TestApp::Views::Scope
expect(view_class.config.scope_class).to be_concrete
end
end
end
describe "slice view" do
let(:view_class) { Main::View }
def before_prepare
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < TestApp::View
end
end
RUBY
end
describe "no concrete slice scope class defined" do
it "generates a slice scope class and configures it as the view's scope_class" do
expect(view_class.config.scope_class).to be Main::Views::Scope
expect(view_class.config.scope_class.superclass).to be TestApp::Views::Scope
end
end
describe "concrete slice scope class defined" do
def before_prepare
super
write "slices/main/views/scope.rb", <<~RUBY
# auto_register: false
module Main
module Views
class Scope < TestApp::Views::Scope
def self.concrete?
true
end
end
end
end
RUBY
end
it "configures the slice scope class as the view's scope_class" do
expect(view_class.config.scope_class).to eq Main::Views::Scope
expect(view_class.config.scope_class).to be_concrete
end
end
context "view not inheriting from app view, no concrete scope class defined" do
def before_prepare
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < Hanami::View
end
end
RUBY
end
it "generates a slice scope class, inheriting from the app scope class, and configures it as the view's scope_class" do
expect(view_class.config.scope_class).to be Main::Views::Scope
expect(view_class.config.scope_class.superclass).to be TestApp::Views::Scope
end
end
context "no app view class defined" do
def before_prepare
FileUtils.rm "app/view.rb"
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < Hanami::View
end
end
RUBY
end
it "generates a slice scope class, inheriting from Hanami::View::Scope, and configures it as the view's scope_class" do
expect(view_class.config.scope_class).to be Main::Views::Scope
expect(view_class.config.scope_class.superclass).to be Hanami::View::Scope
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/config/scope_namespace_spec.rb | spec/integration/view/config/scope_namespace_spec.rb | # frozen_string_literal: true
require "hanami"
RSpec.describe "App view / Config / Scope namespace", :app_integration do
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/view.rb", <<~RUBY
# auto_register: false
require "hanami/view"
module TestApp
class View < Hanami::View
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
subject(:scope_namespace) { view_class.config.scope_namespace }
describe "app view" do
let(:view_class) { TestApp::View }
describe "no scope namespace defined" do
it "is nil" do
expect(scope_namespace).to be nil
end
end
describe "scope namespace defined" do
def before_prepare
write "app/views/scopes/player.rb", <<~RUBY
module TestApp
module Views
module Scopes
class Player < Hanami::View::Scope
end
end
end
end
RUBY
end
it "is the Views::Scopes namespace within the app" do
expect(scope_namespace).to eq TestApp::Views::Scopes
end
end
end
describe "slice view" do
def before_prepare
write "slices/main/view.rb", <<~RUBY
# auto_register: false
module Main
class View < TestApp::View
end
end
RUBY
end
let(:view_class) { Main::View }
describe "no scope namespace defined" do
it "is nil" do
expect(scope_namespace).to be nil
end
end
describe "scope namespace defined" do
def before_prepare
super
write "slices/main/views/scopes/player.rb", <<~RUBY
module Main
module Views
module Scopes
class Player < Hanami::View::Scope
end
end
end
end
RUBY
end
it "is the Views::Scopes namespace within the slice" do
expect(scope_namespace).to eq Main::Views::Scopes
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/config/template_spec.rb | spec/integration/view/config/template_spec.rb | # frozen_string_literal: true
require "hanami"
RSpec.describe "App view / Config / Template", :app_integration do
before do
module TestApp
class App < Hanami::App
config.root = "/test_app"
end
end
Hanami.app.instance_eval(&app_hook) if respond_to?(:app_hook)
Hanami.app.register_slice :main
Hanami.app.prepare
module TestApp
class View < Hanami::View
end
end
module TestApp
module Views
module Article
class Index < TestApp::View
end
end
end
end
end
subject(:template) { view_class.config.template }
let(:view_class) { TestApp::Views::Article::Index }
it "configures the template to match the class name" do
expect(template).to eq "article/index"
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/context/inflector_spec.rb | spec/integration/view/context/inflector_spec.rb | require "hanami"
RSpec.describe "App view / Context / Inflector", :app_integration do
before do
module TestApp
class App < Hanami::App
end
end
Hanami.prepare
module TestApp
module Views
class Context < Hanami::View::Context
end
end
end
end
let(:context_class) { TestApp::Views::Context }
subject(:context) { context_class.new }
describe "#inflector" do
it "is the app inflector by default" do
expect(context.inflector).to be TestApp::App.inflector
end
context "injected inflector" do
subject(:context) {
context_class.new(inflector: inflector)
}
let(:inflector) { double(:inflector) }
it "is the injected inflector" do
expect(context.inflector).to be inflector
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/context/request_spec.rb | spec/integration/view/context/request_spec.rb | require "hanami"
RSpec.describe "App view / Context / Request", :app_integration do
before do
module TestApp
class App < Hanami::App
end
end
Hanami.prepare
module TestApp
module Views
class Context < Hanami::View::Context
end
end
end
end
let(:context_class) { TestApp::Views::Context }
subject(:context) {
context_class.new(request: request)
}
let(:request) { double(:request) }
describe "#request" do
it "is the provided request" do
expect(context.request).to be request
end
end
describe "#session" do
let(:session) { double(:session) }
before do
allow(request).to receive(:session) { session }
end
it "is the request's session" do
expect(context.session).to be session
end
end
describe "#flash" do
let(:flash) { double(:flash) }
before do
allow(request).to receive(:flash) { flash }
end
it "is the request's flash" do
expect(context.flash).to be flash
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/context/assets_spec.rb | spec/integration/view/context/assets_spec.rb | # frozen_string_literal: true
require "hanami"
RSpec.describe "App view / Context / Assets", :app_integration do
subject(:context) { context_class.new }
let(:context_class) { TestApp::Views::Context }
before do
with_directory(make_tmp_directory) do
write "config/app.rb", <<~RUBY
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "app/views/context.rb", <<~RUBY
# auto_register: false
require "hanami/view/context"
module TestApp
module Views
class Context < Hanami::View::Context
end
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
context "assets present and hanami-assets bundled" do
def before_prepare
write "app/assets/.keep", ""
end
it "is the app assets by default" do
expect(context.assets).to be TestApp::App[:assets]
end
end
context "assets not present" do
it "raises error" do
expect { context.assets }.to raise_error(Hanami::ComponentLoadError, /assets directory\?/)
end
end
context "hanami-assets not bundled" do
def before_prepare
# These must be here instead of an ordinary before hook because the Hanami.bundled? check for
# assets is done as part of requiring "hanami/prepare" above.
allow(Hanami).to receive(:bundled?).and_call_original
allow(Hanami).to receive(:bundled?).with("hanami-assets").and_return(false)
write "app/assets/.keep", ""
end
it "raises error" do
expect { context.assets }.to raise_error(Hanami::ComponentLoadError, /hanami-assets gem/)
end
end
context "injected assets" do
subject(:context) {
context_class.new(assets: assets)
}
let(:assets) { double(:assets) }
it "is the injected assets" do
expect(context.assets).to be assets
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/view/context/routes_spec.rb | spec/integration/view/context/routes_spec.rb | # frozen_string_literal: true
require "hanami"
RSpec.describe "App view / Context / Routes", :app_integration do
it "accesses app routes" do
with_tmp_directory(Dir.mktmpdir) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
root to: "home.index"
end
end
RUBY
write "app/action.rb", <<~RUBY
require "hanami/action"
module TestApp
class Action < Hanami::Action
end
end
RUBY
write "app/actions/home/index.rb", <<~RUBY
module TestApp
module Actions
module Home
class Index < Hanami::Action
end
end
end
end
RUBY
write "app/views/context.rb", <<~RUBY
require "hanami/view/context"
module TestApp
module Views
class Context < Hanami::View::Context
end
end
end
RUBY
require "hanami/prepare"
context = TestApp::Views::Context.new
expect(context.routes.path(:root)).to eq "/"
end
end
it "can inject routes" do
module TestApp
class App < Hanami::App
end
end
Hanami.prepare
module TestApp
module Views
class Context < Hanami::View::Context
end
end
end
routes = double(:routes)
context = TestApp::Views::Context.new(routes: routes)
expect(context.routes).to be(routes)
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/router/resource_routes_spec.rb | spec/integration/router/resource_routes_spec.rb | # frozen_string_literal: true
require "dry/inflector"
require "hanami/slice/router"
require "json"
RSpec.describe "Router / Resource routes" do
let(:router) { Hanami::Slice::Router.new(routes:, resolver:, inflector: Dry::Inflector.new) { } }
let(:resolver) { Hanami::Slice::Routing::Resolver.new(slice:) }
let(:slice) {
Class.new(Hanami::Slice).tap { |slice|
allow(slice).to receive(:container) { actions_container }
allow(slice).to receive(:slices) { {reviews: child_slice} }
}
}
let(:child_slice) {
Class.new(Hanami::Slice).tap { |slice|
allow(slice).to receive(:container) { actions_container("[reviews]") }
}
}
def actions_container(prefix = nil)
Hash.new { |_hsh, key|
Class.new { |klass|
klass.define_method(:call) do |env|
body = key
body = "#{body} #{JSON.generate(env["router.params"])}" if env["router.params"].any?
body = "#{prefix}#{body}" if prefix
[200, {}, body]
end
}.new
}.tap { |container|
def container.resolve(key) = self[key]
}
end
let(:app) { Rack::MockRequest.new(router) }
def routed(method, url)
app.request(method, url).body
end
describe "resources" do
let(:routes) { proc { resources :posts } }
it "routes all RESTful actions to the resource" do
expect(routed("GET", "/posts")).to eq %(actions.posts.index)
expect(routed("GET", "/posts/new")).to eq %(actions.posts.new)
expect(routed("POST", "/posts")).to eq %(actions.posts.create)
expect(routed("GET", "/posts/1")).to eq %(actions.posts.show {"id":"1"})
expect(routed("GET", "/posts/1/edit")).to eq %(actions.posts.edit {"id":"1"})
expect(routed("PATCH", "/posts/1")).to eq %(actions.posts.update {"id":"1"})
expect(routed("DELETE", "/posts/1")).to eq %(actions.posts.destroy {"id":"1"})
expect(router.path("posts")).to eq "/posts"
expect(router.path("new_post")).to eq "/posts/new"
expect(router.path("edit_post", id: 1)).to eq "/posts/1/edit"
end
describe "with :only" do
let(:routes) { proc { resources :posts, only: %i(index show) } }
it "routes only the given actions to the resource" do
expect(routed("GET", "/posts")).to eq %(actions.posts.index)
expect(routed("GET", "/posts/1")).to eq %(actions.posts.show {"id":"1"})
expect(routed("GET", "/posts/new")).not_to eq %(actions.posts.new)
expect(routed("POST", "/posts")).to eq "Method Not Allowed"
expect(routed("GET", "/posts/1/edit")).to eq "Not Found"
expect(routed("PATCH", "/posts/1")).to eq "Method Not Allowed"
expect(routed("DELETE", "/posts/1")).to eq "Method Not Allowed"
end
end
describe "with :except" do
let(:routes) { proc { resources :posts, except: %i(edit update destroy) } }
it "routes all except the given actions to the resource" do
expect(routed("GET", "/posts")).to eq %(actions.posts.index)
expect(routed("GET", "/posts/new")).to eq %(actions.posts.new)
expect(routed("POST", "/posts")).to eq %(actions.posts.create)
expect(routed("GET", "/posts/1")).to eq %(actions.posts.show {"id":"1"})
expect(routed("GET", "/posts/1/edit")).to eq "Not Found"
expect(routed("PATCH", "/posts/1")).to eq "Method Not Allowed"
expect(routed("DELETE", "/posts/1")).to eq "Method Not Allowed"
end
end
describe "with :to" do
let(:routes) { proc { resources :posts, to: "articles" } }
it "uses actions from the given container key namespace" do
expect(routed("GET", "/posts")).to eq %(actions.articles.index)
expect(routed("GET", "/posts/new")).to eq %(actions.articles.new)
expect(routed("POST", "/posts")).to eq %(actions.articles.create)
expect(routed("GET", "/posts/1")).to eq %(actions.articles.show {"id":"1"})
expect(routed("GET", "/posts/1/edit")).to eq %(actions.articles.edit {"id":"1"})
expect(routed("PATCH", "/posts/1")).to eq %(actions.articles.update {"id":"1"})
expect(routed("DELETE", "/posts/1")).to eq %(actions.articles.destroy {"id":"1"})
end
end
describe "witih :path" do
let(:routes) { proc { resources :posts, path: "articles" } }
it "uses the given path for the routes" do
expect(routed("GET", "/articles")).to eq %(actions.posts.index)
expect(routed("GET", "/articles/new")).to eq %(actions.posts.new)
expect(routed("POST", "/articles")).to eq %(actions.posts.create)
expect(routed("GET", "/articles/1")).to eq %(actions.posts.show {"id":"1"})
expect(routed("GET", "/articles/1/edit")).to eq %(actions.posts.edit {"id":"1"})
expect(routed("PATCH", "/articles/1")).to eq %(actions.posts.update {"id":"1"})
expect(routed("DELETE", "/articles/1")).to eq %(actions.posts.destroy {"id":"1"})
end
end
end
describe "resource" do
let(:routes) { proc { resource :profile } }
it "routes all RESTful actions (except index) to the resource" do
expect(routed("GET", "/profile/new")).to eq %(actions.profile.new)
expect(routed("POST", "/profile")).to eq %(actions.profile.create)
expect(routed("GET", "/profile")).to eq %(actions.profile.show)
expect(routed("GET", "/profile/edit")).to eq %(actions.profile.edit)
expect(routed("PATCH", "/profile")).to eq %(actions.profile.update)
expect(routed("DELETE", "/profile")).to eq %(actions.profile.destroy)
expect(routed("GET", "/profiles")).to eq "Not Found"
expect(routed("GET", "/profiles/1")).to eq "Not Found"
expect(routed("GET", "/profile/1")).to eq "Not Found"
expect(router.path("profile")).to eq "/profile"
expect(router.path("new_profile")).to eq "/profile/new"
expect(router.path("edit_profile")).to eq "/profile/edit"
end
describe "with :only" do
let(:routes) { proc { resource :profile, only: %i(show edit update) } }
it "routes only the given actions to the resource" do
expect(routed("GET", "/profile")).to eq %(actions.profile.show)
expect(routed("GET", "/profile/edit")).to eq %(actions.profile.edit)
expect(routed("PATCH", "/profile")).to eq %(actions.profile.update)
expect(routed("GET", "/profile/new")).to eq "Not Found"
expect(routed("POST", "/profile")).to eq "Method Not Allowed"
expect(routed("DELETE", "/profile")).to eq "Method Not Allowed"
end
end
describe "with :except" do
let(:routes) { proc { resource :profile, except: %i(edit update destroy) } }
it "routes all except the given actions to the resource" do
expect(routed("GET", "/profile/new")).to eq %(actions.profile.new)
expect(routed("POST", "/profile")).to eq %(actions.profile.create)
expect(routed("GET", "/profile")).to eq %(actions.profile.show)
expect(routed("GET", "/profile/edit")).to eq "Not Found"
expect(routed("PATCH", "/profile")).to eq "Method Not Allowed"
expect(routed("DELETE", "/profile")).to eq "Method Not Allowed"
end
end
describe "with :to" do
let(:routes) { proc { resource :profile, to: "user" } }
it "uses actions from the given container key namespace" do
expect(routed("GET", "/profile/new")).to eq %(actions.user.new)
expect(routed("POST", "/profile")).to eq %(actions.user.create)
expect(routed("GET", "/profile")).to eq %(actions.user.show)
expect(routed("GET", "/profile/edit")).to eq %(actions.user.edit)
expect(routed("PATCH", "/profile")).to eq %(actions.user.update)
expect(routed("DELETE", "/profile")).to eq %(actions.user.destroy)
end
end
describe "with :path" do
let(:routes) { proc { resource :profile, path: "user"} }
it "uses the given path for the routes" do
expect(routed("GET", "/user/new")).to eq %(actions.profile.new)
expect(routed("POST", "/user")).to eq %(actions.profile.create)
expect(routed("GET", "/user")).to eq %(actions.profile.show)
expect(routed("GET", "/user/edit")).to eq %(actions.profile.edit)
expect(routed("PATCH", "/user")).to eq %(actions.profile.update)
expect(routed("DELETE", "/user")).to eq %(actions.profile.destroy)
end
end
end
describe "nested resources" do
let(:routes) {
proc {
resources :cafes, only: :show do
resources :reviews, only: :index do
resources :comments, only: [:index, :new, :create]
end
end
resource :profile, only: :show do
resource :avatar, only: :show do
resources :comments, only: :index
end
end
}
}
it "routes to the nested resources" do
expect(routed("GET", "/cafes/1")).to eq %(actions.cafes.show {"id":"1"})
expect(routed("GET", "/cafes/1/reviews")).to eq %(actions.cafes.reviews.index {"cafe_id":"1"})
expect(routed("GET", "/cafes/1/reviews/2/comments")).to eq %(actions.cafes.reviews.comments.index {"cafe_id":"1","review_id":"2"})
expect(router.path("cafe", id: 1)).to eq "/cafes/1"
expect(router.path("cafe_reviews", cafe_id: 1)).to eq "/cafes/1/reviews"
expect(router.path("cafe_review_comments", cafe_id: 1, review_id: 1)).to eq "/cafes/1/reviews/1/comments"
expect(router.path("new_cafe_review_comment", cafe_id: 1, review_id: 1)).to eq "/cafes/1/reviews/1/comments/new"
expect(routed("GET", "/profile")).to eq %(actions.profile.show)
expect(routed("GET", "/profile/avatar")).to eq %(actions.profile.avatar.show)
expect(routed("GET", "/profile/avatar/comments")).to eq %(actions.profile.avatar.comments.index)
end
end
describe "standalone routes nested under resources" do
let(:routes) {
proc {
resources :cafes, only: :show do
get "/top-reviews", to: "cafes.top_reviews.index", as: :top_reviews
end
}
}
it "nests the standalone route under the resource" do
expect(routed("GET", "/cafes/1")).to eq %(actions.cafes.show {"id":"1"})
expect(routed("GET", "/cafes/1/top-reviews")).to eq %(actions.cafes.top_reviews.index {"cafe_id":"1"})
expect(router.path("cafe_top_reviews", cafe_id: 1)).to eq "/cafes/1/top-reviews"
end
end
describe "resources nested under scopes" do
let(:routes) {
proc {
scope "coffee-lovers" do
resources :cafes, only: :show do
get "/top-reviews", to: "cafes.top_reviews.index", as: :top_reviews
end
end
}
}
it "routes to the resources under the scope" do
expect(routed("GET", "/coffee-lovers/cafes/1")).to eq %(actions.cafes.show {"id":"1"})
expect(routed("GET", "/coffee-lovers/cafes/1/top-reviews")).to eq %(actions.cafes.top_reviews.index {"cafe_id":"1"})
expect(router.path("coffee_lovers_cafe", id: 1)).to eq "/coffee-lovers/cafes/1"
expect(router.path("coffee_lovers_cafe_top_reviews", cafe_id: 1)).to eq "/coffee-lovers/cafes/1/top-reviews"
end
end
describe "slices nested under resources" do
let(:routes) {
proc {
resources :cafes, only: :show do
slice :reviews, at: "" do
resources :reviews, only: :index
end
end
}
}
it "routes to actions within the nested slice" do
expect(routed("GET", "/cafes/1")).to eq %(actions.cafes.show {"id":"1"})
expect(routed("GET", "/cafes/1/reviews")).to eq %([reviews]actions.cafes.reviews.index {"cafe_id":"1"})
expect(router.path("cafe_reviews", cafe_id: 1)).to eq "/cafes/1/reviews"
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/web/welcome_view_spec.rb | spec/integration/web/welcome_view_spec.rb | # frozen_string_literal: true
require "json"
require "rack/test"
RSpec.describe "Web / Welcome view", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
before do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File::NULL
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
context "no routes defined" do
it "renders the welcome page" do
get "/"
body = last_response.body.strip
expect(body).to include "<h1>Welcome to Hanami</h1>"
expect(body).to include "Hanami version: #{Hanami::VERSION}"
expect(body).to include "Ruby version: #{RUBY_DESCRIPTION}"
expect(last_response.status).to eq 200
end
end
context "routes defined" do
def before_prepare
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
root to: -> * { [200, {}, "Hello from a route"] }
end
end
RUBY
end
it "does not render the welcome page" do
get "/"
expect(last_response.body).to eq "Hello from a route"
expect(last_response.status).to eq 200
end
end
context "non-development env" do
def before_prepare
@hanami_env = ENV["HANAMI_ENV"]
ENV["HANAMI_ENV"] = "production"
end
after do
ENV["HANAMI_ENV"] = @hanami_env
end
it "does not render the welcome page" do
get "/"
expect(last_response.body).to eq "Not Found"
expect(last_response.status).to eq 404
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/web/render_detailed_errors_spec.rb | spec/integration/web/render_detailed_errors_spec.rb | # frozen_string_literal: true
require "json"
require "rack/test"
RSpec.describe "Web / Rendering detailed errors", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
before do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File.new("/dev/null", "w")
config.render_detailed_errors = true
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
get "error", to: "error"
end
end
RUBY
write "app/actions/error.rb", <<~RUBY
module TestApp
module Actions
class Error < Hanami::Action
def handle(*)
raise "oops"
end
end
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "HTML request" do
it "renders a detailed HTML error page" do
get "/error", {}, "HTTP_ACCEPT" => "text/html"
expect(last_response.status).to eq 500
html = Capybara.string(last_response.body)
expect(html).to have_selector("header", text: "RuntimeError at /error")
expect(html).to have_selector("ul.frames li.application", text: "app/actions/error.rb")
end
it "renders a detailed HTML error page and returns a 404 status for a not found error" do
get "/__not_found__", {}, "HTTP_ACCEPT" => "text/html"
expect(last_response.status).to eq 404
html = Capybara.string(last_response.body)
expect(html).to have_selector("header", text: "Hanami::Router::NotFoundError at /__not_found__")
end
end
describe "Other request types" do
it "renders a detailed error page in text" do
get "/error", {}, "HTTP_ACCEPT" => "application/json"
expect(last_response.status).to eq 500
expect(last_response.body).to include "RuntimeError at /error"
expect(last_response.body).to match %r{App backtrace.+app/actions/error.rb}m
end
it "renders a detailed error page in text and returns a 404 status for a not found error" do
get "/__not_found__", {}, "HTTP_ACCEPT" => "text/html"
expect(last_response.status).to eq 404
expect(last_response.body).to include "Hanami::Router::NotFoundError at /__not_found__"
end
end
describe "render_detailed_errors config disabled" do
def before_prepare
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File.new("/dev/null", "w")
config.render_detailed_errors = false
end
end
RUBY
end
it "raises errors from within the app" do
expect { get "/error" }.to raise_error(RuntimeError, "oops")
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/web/render_errors_spec.rb | spec/integration/web/render_errors_spec.rb | # frozen_string_literal: true
require "json"
require "rack/test"
RSpec.describe "Web / Rendering errors", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
before do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File.new("/dev/null", "w")
config.render_errors = true
config.render_detailed_errors = false
end
end
RUBY
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
get "index", to: "index"
get "error", to: "error"
end
end
RUBY
write "app/actions/index.rb", <<~RUBY
module TestApp
module Actions
class Index < Hanami::Action
def handle(*, response)
response.body = "Hello"
end
end
end
end
RUBY
write "app/actions/error.rb", <<~RUBY
module TestApp
module Actions
class Error < Hanami::Action
def handle(*)
raise "oops"
end
end
end
end
RUBY
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
end
end
describe "HTML request" do
context "error pages present" do
def before_prepare
write "public/404.html", <<~HTML
<h1>Not found</h1>
HTML
write "public/500.html", <<~HTML
<h1>Error</h1>
HTML
end
it "responds with the HTML for a 404 from a not found error" do
get "/__not_found__"
expect(last_response.status).to eq 404
expect(last_response.body.strip).to eq "<h1>Not found</h1>"
expect(last_response.get_header("Content-Type")).to eq "text/html; charset=utf-8"
expect(last_response.get_header("Content-Length")).to eq "19"
end
it "responds with the HTML for a 404 from a method not allowed error" do
post "/index"
expect(last_response.status).to eq 404
expect(last_response.body.strip).to eq "<h1>Not found</h1>"
expect(last_response.get_header("Content-Type")).to eq "text/html; charset=utf-8"
expect(last_response.get_header("Content-Length")).to eq "19"
end
it "responds with the HTML for a 500" do
get "/error"
expect(last_response.status).to eq 500
expect(last_response.body.strip).to eq "<h1>Error</h1>"
expect(last_response.get_header("Content-Type")).to eq "text/html; charset=utf-8"
expect(last_response.get_header("Content-Length")).to eq "15"
end
end
context "error pages missing" do
it "responds with default text for a 404 from a not found error" do
get "/__not_found__"
expect(last_response.status).to eq 404
expect(last_response.body.strip).to eq "Not Found"
expect(last_response.get_header("Content-Type")).to eq "text/html; charset=utf-8"
expect(last_response.get_header("Content-Length")).to eq "9"
end
it "responds with default text for a 404 from a metohd not allowed error" do
post "/index"
expect(last_response.status).to eq 404
expect(last_response.body.strip).to eq "Not Found"
expect(last_response.get_header("Content-Type")).to eq "text/html; charset=utf-8"
expect(last_response.get_header("Content-Length")).to eq "9"
end
it "responds with default text for a 500" do
get "/error"
expect(last_response.status).to eq 500
expect(last_response.body.strip).to eq "Internal Server Error"
expect(last_response.get_header("Content-Type")).to eq "text/html; charset=utf-8"
expect(last_response.get_header("Content-Length")).to eq "21"
end
end
end
describe "JSON request" do
it "renders a JSON response for a 404 from a not found error" do
get "/__not_found__", {}, "HTTP_ACCEPT" => "application/json"
expect(last_response.status).to eq 404
expect(last_response.body.strip).to eq %({"status":404,"error":"Not Found"})
expect(last_response.get_header("Content-Type")).to eq "application/json; charset=utf-8"
expect(last_response.get_header("Content-Length")).to eq "34"
end
it "renders a JSON response for a 404 from a metnod not allowed error" do
post "/index", {}, "HTTP_ACCEPT" => "application/json"
expect(last_response.status).to eq 404
expect(last_response.body.strip).to eq %({"status":404,"error":"Not Found"})
expect(last_response.get_header("Content-Type")).to eq "application/json; charset=utf-8"
expect(last_response.get_header("Content-Length")).to eq "34"
end
it "renders a JSON response for a 500" do
get "/error", {}, "HTTP_ACCEPT" => "application/json"
expect(last_response.status).to eq 500
expect(last_response.body.strip).to eq %({"status":500,"error":"Internal Server Error"})
expect(last_response.get_header("Content-Type")).to eq "application/json; charset=utf-8"
expect(last_response.get_header("Content-Length")).to eq "46"
end
end
describe "configuring error responses" do
def before_prepare
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
CustomNotFoundError = Class.new(StandardError)
class App < Hanami::App
config.logger.stream = File.new("/dev/null", "w")
config.render_errors = true
config.render_error_responses["TestApp::CustomNotFoundError"] = :not_found
config.render_detailed_errors = false
end
end
RUBY
write "app/actions/error.rb", <<~RUBY
module TestApp
module Actions
class Error < Hanami::Action
def handle(*)
raise CustomNotFoundError
end
end
end
end
RUBY
write "public/404.html", <<~HTML
<h1>Not found</h1>
HTML
end
it "uses the configured errors to determine the response" do
get "/error"
expect(last_response.status).to eq 404
expect(last_response.body.strip).to eq "<h1>Not found</h1>"
end
end
describe "render_errors config disabled" do
def before_prepare
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.logger.stream = File.new("/dev/null", "w")
config.render_errors = false
config.render_detailed_errors = false
end
end
RUBY
# Include error pages here to prove they are _not_ used
write "public/404.html", <<~HTML
<h1>Not found</h1>
HTML
write "public/500.html", <<~HTML
<h1>Error</h1>
HTML
end
it "renders the hanami-router default 404 response for a not found error" do
get "/__not_found__"
expect(last_response.status).to eq 404
end
it "renders the hanami-router default 405 response for a not allowed error" do
post "/index"
expect(last_response.status).to eq 405
end
it "raises the original error for a 500" do
expect { get "/error" }.to raise_error(RuntimeError, "oops")
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/web/content_security_policy_nonce_spec.rb | spec/integration/web/content_security_policy_nonce_spec.rb | # frozen_string_literal: true
require "rack/test"
RSpec.describe "Web / Content security policy nonce", :app_integration do
include Rack::Test::Methods
let(:app) { Hanami.app }
before do
with_directory(@dir = make_tmp_directory) do
write "config/routes.rb", <<~RUBY
module TestApp
class Routes < Hanami::Routes
get "index", to: "index"
end
end
RUBY
write "app/actions/index.rb", <<~RUBY
module TestApp
module Actions
class Index < Hanami::Action
end
end
end
RUBY
write "app/views/index.rb", <<~RUBY
module TestApp
module Views
class Index < Hanami::View
config.layout = false
end
end
end
RUBY
write "app/templates/index.html.erb", <<~HTML
<!DOCTYPE html>
<html lang="en">
<head>
<%= stylesheet_tag "app", class: "nonce-true", nonce: true %>
<%= stylesheet_tag "app", class: "nonce-false", nonce: false %>
<%= stylesheet_tag "app", class: "nonce-explicit", nonce: "explicit" %>
<%= stylesheet_tag "app", class: "nonce-generated" %>
<%= stylesheet_tag "https://example.com/app.css", class: "nonce-absolute" %>
</head>
<body>
<style nonce="<%= content_security_policy_nonce %>"></style>
<%= javascript_tag "app", class: "nonce-true", nonce: true %>
<%= javascript_tag "app", class: "nonce-false", nonce: false %>
<%= javascript_tag "app", class: "nonce-explicit", nonce: "explicit" %>
<%= javascript_tag "app", class: "nonce-generated" %>
<%= javascript_tag "https://example.com/app.js", class: "nonce-absolute" %>
</body>
</html>
HTML
write "package.json", <<~JSON
{
"type": "module"
}
JSON
write "config/assets.js", <<~JS
import * as assets from "hanami-assets";
await assets.run();
JS
write "app/assets/js/app.js", <<~JS
import "../css/app.css";
JS
write "app/assets/css/app.css", ""
before_prepare if respond_to?(:before_prepare)
require "hanami/prepare"
compile_assets!
end
end
describe "HTML request" do
context "CSP enabled" do
def before_prepare
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.actions.content_security_policy[:script_src] = "'self' 'nonce'"
config.logger.stream = File::NULL
end
end
RUBY
end
it "sets unique and per-request hanami.content_security_policy_nonce in Rack env" do
previous_nonces = []
3.times do
get "/index"
nonce = last_request.env["hanami.content_security_policy_nonce"]
expect(nonce).to match(/\A[A-Za-z0-9\-_]{22}\z/)
expect(previous_nonces).not_to include nonce
previous_nonces << nonce
end
end
it "accepts custom nonce generator proc without arguments" do
Hanami.app.config.actions.content_security_policy_nonce_generator = -> { "foobar" }
get "/index"
expect(last_request.env["hanami.content_security_policy_nonce"]).to eql("foobar")
end
it "accepts custom nonce generator proc with Rack request as argument" do
Hanami.app.config.actions.content_security_policy_nonce_generator = ->(request) { request }
get "/index"
expect(last_request.env["hanami.content_security_policy_nonce"]).to be_a(Rack::Request)
end
it "substitutes 'nonce' in the CSP header" do
get "/index"
nonce = last_request.env["hanami.content_security_policy_nonce"]
expect(last_response.get_header("Content-Security-Policy")).to match(/script-src 'self' 'nonce-#{nonce}'/)
end
it "behaves the same with explicitly added middleware" do
Hanami.app.config.middleware.use Hanami::Middleware::ContentSecurityPolicyNonce
get "/index"
expect(last_request.env["hanami.content_security_policy_nonce"]).to match(/\A[A-Za-z0-9\-_]{22}\z/)
end
describe "content_security_policy_nonce" do
it "renders the current nonce" do
get "/index"
nonce = last_request.env["hanami.content_security_policy_nonce"]
expect(last_response.body).to include(%(<style nonce="#{nonce}">))
end
end
describe "stylesheet_tag" do
it "renders the correct nonce unless remote URL or nonce set to false" do
get "/index"
nonce = last_request.env["hanami.content_security_policy_nonce"]
expect(last_response.body).to include(%(<link href="/assets/app-KUHJPSX7.css" type="text/css" rel="stylesheet" nonce="#{nonce}" class="nonce-true">))
expect(last_response.body).to include(%(<link href="/assets/app-KUHJPSX7.css" type="text/css" rel="stylesheet" class="nonce-false">))
expect(last_response.body).to include(%(<link href="/assets/app-KUHJPSX7.css" type="text/css" rel="stylesheet" nonce="explicit" class="nonce-explicit">))
expect(last_response.body).to include(%(<link href="/assets/app-KUHJPSX7.css" type="text/css" rel="stylesheet" nonce="#{nonce}" class="nonce-generated">))
expect(last_response.body).to include(%(<link href="https://example.com/app.css" type="text/css" rel="stylesheet" class="nonce-absolute">))
end
end
describe "javascript_tag" do
it "renders the correct nonce unless remote URL or nonce set to false" do
get "/index"
nonce = last_request.env["hanami.content_security_policy_nonce"]
expect(last_response.body).to include(%(<script src="/assets/app-LSLFPUMX.js" type="text/javascript" nonce="#{nonce}" class="nonce-true"></script>))
expect(last_response.body).to include(%(<script src="/assets/app-LSLFPUMX.js" type="text/javascript" class="nonce-false"></script>))
expect(last_response.body).to include(%(<script src="/assets/app-LSLFPUMX.js" type="text/javascript" nonce="explicit" class="nonce-explicit"></script>))
expect(last_response.body).to include(%(<script src="/assets/app-LSLFPUMX.js" type="text/javascript" nonce="#{nonce}" class="nonce-generated"></script>))
expect(last_response.body).to include(%(<script src="https://example.com/app.js" type="text/javascript" class="nonce-absolute"></script>))
end
end
end
context "CSP disabled" do
def before_prepare
write "config/app.rb", <<~RUBY
require "hanami"
module TestApp
class App < Hanami::App
config.actions.content_security_policy = false
config.logger.stream = File::NULL
end
end
RUBY
end
it "does not set hanami.content_security_policy_nonce in Rack env" do
get "/index"
expect(last_request.env).to_not have_key "hanami.content_security_policy_nonce"
end
it "does not produce a CSP header" do
get "/index"
expect(last_response.headers).to_not have_key "Content-Security-Policy"
end
it "disables the content_security_policy_nonce helper" do
get "/index"
expect(last_response.body).to match(/<style nonce="">/)
end
it "behaves the same with explicitly added middleware" do
Hanami.app.config.middleware.use Hanami::Middleware::ContentSecurityPolicyNonce
get "/index"
expect(last_response.headers).to_not have_key "Content-Security-Policy"
end
describe "content_security_policy_nonce" do
it "renders nothing" do
get "/index"
expect(last_response.body).to include(%(<style nonce="">))
end
end
describe "stylesheet_tag" do
it "renders the correct explicit nonce only" do
get "/index"
expect(last_response.body).to include(%(<link href="/assets/app-KUHJPSX7.css" type="text/css" rel="stylesheet" class="nonce-true">))
expect(last_response.body).to include(%(<link href="/assets/app-KUHJPSX7.css" type="text/css" rel="stylesheet" class="nonce-false">))
expect(last_response.body).to include(%(<link href="/assets/app-KUHJPSX7.css" type="text/css" rel="stylesheet" nonce="explicit" class="nonce-explicit">))
expect(last_response.body).to include(%(<link href="/assets/app-KUHJPSX7.css" type="text/css" rel="stylesheet" class="nonce-generated">))
expect(last_response.body).to include(%(<link href="https://example.com/app.css" type="text/css" rel="stylesheet" class="nonce-absolute">))
end
end
describe "javascript_tag" do
it "renders the correct explicit nonce only" do
get "/index"
expect(last_response.body).to include(%(<script src="/assets/app-LSLFPUMX.js" type="text/javascript" class="nonce-true"></script>))
expect(last_response.body).to include(%(<script src="/assets/app-LSLFPUMX.js" type="text/javascript" class="nonce-false"></script>))
expect(last_response.body).to include(%(<script src="/assets/app-LSLFPUMX.js" type="text/javascript" nonce="explicit" class="nonce-explicit"></script>))
expect(last_response.body).to include(%(<script src="/assets/app-LSLFPUMX.js" type="text/javascript" class="nonce-generated"></script>))
expect(last_response.body).to include(%(<script src="https://example.com/app.js" type="text/javascript" class="nonce-absolute"></script>))
end
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/code_loading/loading_from_slice_spec.rb | spec/integration/code_loading/loading_from_slice_spec.rb | # frozen_string_literal: true
RSpec.describe "Code loading / Loading from slice directory", :app_integration do
before :context do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/config/not_loadable.rb", <<~'RUBY'
raise "This file should never be loaded"
RUBY
write "slices/main/test_class.rb", <<~'RUBY'
module Main
class TestClass
end
end
RUBY
write "slices/main/action.rb", <<~'RUBY'
# auto_register: false
module Main
class Action < Hanami::Action
end
end
RUBY
write "slices/main/actions/home/show.rb", <<~'RUBY'
module Main
module Actions
module Home
class Show < Main::Action
end
end
end
end
RUBY
end
end
before do
with_directory(@dir) do
require "hanami/prepare"
end
end
specify "Classes in slice directory are autoloaded with the slice namespace" do
expect(Main::TestClass).to be
expect(Main::Action).to be
expect(Main::Actions::Home::Show).to be
end
specify "Files in slice config/ directory are not autoloaded" do
expect { Main::NotLoadable }.to raise_error NameError
expect { Main::Config::NotLoadable }.to raise_error NameError
end
specify "Classes in slice directory are auto-registered" do
expect(Main::Slice["test_class"]).to be_an_instance_of Main::TestClass
expect(Main::Slice["actions.home.show"]).to be_an_instance_of Main::Actions::Home::Show
# Files with "auto_register: false" magic comments are not auto-registered
expect(Main::Slice.key?("action")).to be false
end
specify "Files in slice config/ directory are not auto-registered" do
expect(Main::Slice.key?("config.settings")).to be false
end
describe "slice lib/ directory" do
before :context do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/lib/test_class.rb", <<~'RUBY'
module Main
class TestClass
end
end
RUBY
end
end
specify "Classes in slice lib/ directory are autoloaded with the slice namespace" do
expect(Main::TestClass).to be
end
specify "Classes in slice lib/ directory are auto-registered" do
expect(Main::Slice["test_class"]).to be_an_instance_of Main::TestClass
end
specify "Classes in slice lib/ directory are not redundantly auto-registered under 'lib' key namespace" do
expect(Main::Slice.key?("lib.test_class")).to be false
end
end
# rubocop:disable Style/GlobalVars
describe "same-named class defined in both slice and lib/ directories" do
before :context do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "slices/main/test_class.rb", <<~'RUBY'
$slice_class_loaded = true
module Main
class TestClass
(@loaded_from ||= []) << "slice"
end
end
RUBY
write "slices/main/lib/test_class.rb", <<~'RUBY'
$slice_lib_class_loaded = true
module Main
class TestClass
(@loaded_from ||= []) << "slice/lib"
end
end
RUBY
end
end
after do
$slice_class_loaded = $slice_lib_class_loaded = nil
end
specify "Classes in slice lib/ directory are preferred for autoloading" do
expect(Main::TestClass).to be
expect(Main::TestClass.instance_variable_get(:@loaded_from)).to eq ["slice/lib"]
expect($slice_lib_class_loaded).to be true
expect($slice_class_loaded).to be nil
end
specify "Classes in slice lib/ directory are preferred for auto-registration" do
expect(Main::Slice["test_class"]).to be
expect(Main::TestClass.instance_variable_get(:@loaded_from)).to eq ["slice/lib"]
expect($slice_lib_class_loaded).to be true
expect($slice_class_loaded).to be nil
end
end
# rubocop:enable Style/GlobalVars
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/code_loading/loading_from_lib_spec.rb | spec/integration/code_loading/loading_from_lib_spec.rb | # frozen_string_literal: true
RSpec.describe "Code loading / Loading from lib directory", :app_integration do
describe "default root" do
before :context do
with_directory(@dir = make_tmp_directory.realpath) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "lib/external_class.rb", <<~'RUBY'
class ExternalClass
end
RUBY
write "lib/test_app/test_class.rb", <<~'RUBY'
module TestApp
class TestClass
end
end
RUBY
end
end
context "setup app" do
before do
with_directory(@dir) { require "hanami/setup" }
end
it "adds the lib directory to the load path" do
expect($LOAD_PATH).to include(@dir.join("lib").to_s)
end
specify "classes in lib/ can be required directly" do
expect(require("external_class")).to be true
expect(ExternalClass).to be
end
specify "classes in lib/[app_namespace]/ cannot yet be autoloaded" do
expect { TestApp::TestClass }.to raise_error(NameError)
end
end
context "prepared app" do
before do
with_directory(@dir) { require "hanami/prepare" }
end
it "leaves the lib directory already in the load path" do
expect($LOAD_PATH).to include(@dir.join("lib").to_s).exactly(1).times
end
specify "classes in lib/[app_namespace]/ can be autoloaded" do
expect(TestApp::TestClass).to be
end
end
context "lib dir missing" do
before do
with_directory(@dir = make_tmp_directory.realpath) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
require "hanami/setup"
end
end
it "does not add the lib directory to the load path" do
expect($LOAD_PATH).not_to include(@dir.join("lib").to_s)
end
end
end
describe "default root with requires at top of app file" do
before :context do
with_directory(@dir = make_tmp_directory.realpath) do
write "config/app.rb", <<~'RUBY'
require "hanami"
require "external_class"
module TestApp
class App < Hanami::App
@class_from_lib = ExternalClass
def self.class_from_lib
@class_from_lib
end
end
end
RUBY
write "lib/external_class.rb", <<~'RUBY'
class ExternalClass
end
RUBY
end
end
before do
with_directory(@dir) { require "hanami/setup" }
end
specify "classes in lib/ can be required directly from the top of the app file" do
expect(Hanami.app.class_from_lib).to be ExternalClass
end
end
context "app root reconfigured" do
before :context do
with_directory(@dir = make_tmp_directory.realpath) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
config.root = Pathname(__dir__).join("..", "src").realpath
end
end
RUBY
write "src/lib/external_class.rb", <<~'RUBY'
class ExternalClass
end
RUBY
write "src/lib/test_app/test_class.rb", <<~'RUBY'
module TestApp
class TestClass
end
end
RUBY
end
end
context "setup app" do
before do
with_directory(@dir) { require "hanami/setup" }
end
it "does not add the lib directory to the load path (already done at time of subclassing)" do
expect($LOAD_PATH).not_to include(@dir.join("src", "lib").to_s)
end
it "adds the lib directory under the new root with `prepare_load_path`" do
expect { Hanami.app.prepare_load_path }
.to change { $LOAD_PATH }
.to include(@dir.join("src", "lib").to_s)
end
end
context "prepared app" do
before do
with_directory(@dir) { require "hanami/prepare" }
end
it "adds the lib directory to the load path" do
expect($LOAD_PATH).to include(@dir.join("src", "lib").to_s)
end
specify "classes in lib/ can be required directly" do
expect(require("external_class")).to be true
expect(ExternalClass).to be
end
specify "classes in lib/[app_namespace]/ can be autoloaded" do
expect(TestApp::TestClass).to be
end
end
end
context "app root reconfigured and load path immediately prepared" do
before :context do
with_directory(@dir = make_tmp_directory.realpath) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
config.root = Pathname(__dir__).join("..", "src").realpath and prepare_load_path
end
end
RUBY
write "src/lib/external_class.rb", <<~'RUBY'
class ExternalClass
end
RUBY
write "src/lib/test_app/test_class.rb", <<~'RUBY'
module TestApp
class TestClass
end
end
RUBY
end
end
context "setup app" do
before do
with_directory(@dir) { require "hanami/setup" }
end
it "adds the lib directory to the load path" do
expect($LOAD_PATH).to include(@dir.join("src", "lib").to_s)
end
specify "classes in lib/ can be required directly" do
expect(require("external_class")).to be true
expect(ExternalClass).to be
end
specify "classes in lib/[app_namespace]/ cannot yet be autoloaded" do
expect { TestApp::TestClass }.to raise_error(NameError)
end
end
context "prepared app" do
before do
with_directory(@dir) { require "hanami/prepare" }
end
it "leaves the lib directory to the load path" do
expect($LOAD_PATH).to include(@dir.join("src", "lib").to_s).exactly(1).times
end
specify "classes in lib/[app_namespace]/ can be autoloaded" do
expect(TestApp::TestClass).to be
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/integration/code_loading/loading_from_app_spec.rb | spec/integration/code_loading/loading_from_app_spec.rb | # frozen_string_literal: true
RSpec.describe "Code loading / Loading from app directory", :app_integration do
before :context do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/test_class.rb", <<~'RUBY'
module TestApp
class TestClass
end
end
RUBY
write "app/action.rb", <<~'RUBY'
# auto_register: false
module TestApp
class Action < Hanami::Action
end
end
RUBY
write "app/actions/home/show.rb", <<~'RUBY'
module TestApp
module Actions
module Home
class Show < TestApp::Action
end
end
end
end
RUBY
end
end
before do
with_directory(@dir) do
require "hanami/prepare"
end
end
specify "Classes in app/ directory are autoloaded with the app namespace" do
expect(TestApp::TestClass).to be
expect(TestApp::Action).to be
expect(TestApp::Actions::Home::Show).to be
end
specify "Classes in app directory are auto-registered" do
expect(TestApp::App["test_class"]).to be_an_instance_of TestApp::TestClass
expect(TestApp::App["actions.home.show"]).to be_an_instance_of TestApp::Actions::Home::Show
# Files with "auto_register: false" magic comments are not auto-registered
expect(TestApp::App.key?("action")).to be false
end
describe "app/lib/ directory" do
before :context do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/lib/test_class.rb", <<~'RUBY'
module TestApp
class TestClass
end
end
RUBY
end
end
specify "Classes in app/lib/ directory are autoloaded with the app namespace" do
expect(TestApp::TestClass).to be
end
specify "Classes in app/lib/ directory are auto-registered" do
expect(TestApp::App["test_class"]).to be_an_instance_of TestApp::TestClass
end
specify "Classes in app/lib/ directory are not redundantly auto-registered under 'lib' key namespace" do
expect(TestApp::App.key?("lib.test_class")).to be false
end
end
# rubocop:disable Style/GlobalVars
describe "same-named class defined in both app/ and app/lib/ directories" do
before :context do
with_directory(@dir = make_tmp_directory) do
write "config/app.rb", <<~'RUBY'
require "hanami"
module TestApp
class App < Hanami::App
end
end
RUBY
write "app/test_class.rb", <<~'RUBY'
$app_class_loaded = true
module TestApp
class TestClass
(@loaded_from ||= []) << "app"
end
end
RUBY
write "app/lib/test_class.rb", <<~'RUBY'
$app_lib_class_loaded = true
module TestApp
class TestClass
(@loaded_from ||= []) << "app/lib"
end
end
RUBY
end
end
after do
$app_class_loaded = $app_lib_class_loaded = nil
end
specify "Classes in app/lib/ directory are preferred for autoloading" do
expect(TestApp::TestClass).to be
expect(TestApp::TestClass.instance_variable_get(:@loaded_from)).to eq ["app/lib"]
expect($app_lib_class_loaded).to be true
expect($app_class_loaded).to be nil
end
specify "Classes in app/lib/ directory are preferred for auto-registration" do
expect(TestApp::App["test_class"]).to be
expect(TestApp::TestClass.instance_variable_get(:@loaded_from)).to eq ["app/lib"]
expect($app_lib_class_loaded).to be true
expect($app_class_loaded).to be nil
end
end
# rubocop:enable Style/GlobalVars
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/port_spec.rb | spec/unit/hanami/port_spec.rb | # frozen_string_literal: true
require "hanami/port"
RSpec.describe Hanami::Port do
context "Hanami::Port::DEFAULT" do
it "returns default value" do
expect(Hanami::Port::DEFAULT).to eq(2300)
end
end
context "Hanami::Port::ENV_VAR" do
it "returns default value" do
expect(Hanami::Port::ENV_VAR).to eq("HANAMI_PORT")
end
end
context ".call" do
let(:value) { nil }
let(:env) { nil }
it "is aliased as .[]" do
expect(described_class[value, env]).to be(2300)
end
context "when ENV var is nil" do
context "and value is nil" do
it "returns default value" do
expect(described_class.call(value, env)).to be(2300)
end
end
context "and value is not nil" do
let(:value) { 18_000 }
it "returns given value" do
expect(described_class.call(value, env)).to be(value)
end
context "and value is default" do
let(:value) { 2300 }
it "returns given value" do
expect(described_class.call(value, env)).to be(value)
end
end
end
end
context "when ENV var not nil" do
let(:env) { 9000 }
context "and value is nil" do
it "returns env value" do
expect(described_class.call(value, env)).to be(env)
end
end
context "and value is not nil" do
let(:value) { 18_000 }
it "returns given value" do
expect(described_class.call(value, env)).to be(value)
end
context "and value is default" do
let(:value) { 2300 }
it "returns env value" do
expect(described_class.call(value, env)).to be(env)
end
end
end
end
end
context ".call!" do
before { ENV.delete("HANAMI_PORT") }
let(:value) { 2300 }
context "when given value is default" do
it "doesn't set env var" do
described_class.call!(value)
expect(ENV.key?("HANAMI_PORT")).to be(false)
end
end
context "when given value isn't default" do
let(:value) { 9000 }
it "set env var" do
described_class.call!(value)
expect(ENV.fetch("HANAMI_PORT")).to eq(value.to_s)
end
end
end
context ".default?" do
context "when given value is default" do
let(:value) { 2300 }
it "returns true" do
expect(described_class.default?(value)).to be(true)
end
end
context "when given value isn't default" do
let(:value) { 9000 }
it "returns false" do
expect(described_class.default?(value)).to be(false)
end
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/slice_name_spec.rb | spec/unit/hanami/slice_name_spec.rb | # frozen_string_literal: true
require "hanami/slice_name"
require "dry/inflector"
RSpec.describe Hanami::SliceName do
subject(:slice_name) { described_class.new(slice, inflector: -> { inflector }) }
let(:slice) { double(name: "Main::Slice") }
let(:inflector) { Dry::Inflector.new }
let(:slice_module) { Module.new }
before do
stub_const "Main", slice_module
end
describe "#name" do
it "returns the downcased, underscored string name of the module containing the slice" do
expect(slice_name.name).to eq "main"
end
end
describe "#to_s" do
it "returns the downcased, underscored string name of the module containing the slice" do
expect(slice_name.to_s).to eq "main"
end
end
describe "#to_sym" do
it "returns the downcased, underscored, symbolized name of the module containing the slice" do
expect(slice_name.to_sym).to eq :main
end
end
describe "#namespace_name" do
it "returns the string name of the module containing the slice" do
expect(slice_name.namespace_name).to eq "Main"
end
end
describe "#namespace_const" do
it "returns the module containing the slice" do
expect(slice_name.namespace).to be slice_module
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/env_spec.rb | spec/unit/hanami/env_spec.rb | # frozen_string_literal: true
RSpec.describe Hanami, ".env" do
subject { described_class.env(e: env) }
context "HANAMI_ENV, APP_ENV and RACK_ENV in ENV" do
let(:env) { { "HANAMI_ENV" => "test", "APP_ENV" => "development", "RACK_ENV" => "production" } }
it "is the value of HANAMI_ENV" do
is_expected.to eq(:test)
end
end
context "APP_ENV and RACK_ENV in ENV" do
let(:env) { {"APP_ENV" => "development", "RACK_ENV" => "production" } }
it "is the value of APP_ENV" do
is_expected.to eq(:development)
end
end
context "RACK_ENV in ENV" do
let(:env) { { "RACK_ENV" => "production" } }
it "is the value of RACK_ENV" do
is_expected.to eq(:production)
end
end
context "no ENV vars set" do
let(:env) { {} }
it "defaults to \"development\"" do
is_expected.to eq(:development)
end
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
hanami/hanami | https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/settings_spec.rb | spec/unit/hanami/settings_spec.rb | # frozen_string_literal: true
require "hanami/settings"
RSpec.describe Hanami::Settings do
describe "#initialize" do
it "uses values from the store when present" do
settings_class = Class.new(described_class) do
setting :database_url, default: "postgres://localhost/test_app_development"
end
store = {database_url: "mysql://localhost/test_app_development"}.freeze
instance = settings_class.new(store)
expect(instance.config.database_url).to eq("mysql://localhost/test_app_development")
end
it "uses defaults when values are not present in the store" do
settings_class = Class.new(described_class) do
setting :database_url, default: "postgres://localhost/test_app_development"
end
store = {}.freeze
instance = settings_class.new(store)
expect(instance.config.database_url).to eq("postgres://localhost/test_app_development")
end
it "collects error for all setting values failing their constructors" do
settings_class = Class.new(described_class) do
setting :database_url, constructor: ->(_v) { raise "nope to database" }
setting :redis_url, constructor: ->(_v) { raise "nope to redis" }
end
store = {
database_url: "postgres://localhost/test_app_development",
redis_url: "redis://localhost:6379"
}.freeze
expect { settings_class.new(store) }.to raise_error(
described_class::InvalidSettingsError,
/(database_url: nope to database).*(redis_url: nope to redis)/m,
)
end
it "collects errors for missing settings failing their constructors" do
settings_class = Class.new(described_class) do
setting :database_url, constructor: ->(_v) { raise "nope to database" }
end
store = {}
expect { settings_class.new(store) }.to raise_error(
described_class::InvalidSettingsError,
/database_url: nope to database/m,
)
end
it "finalizes the config" do
settings_class = Class.new(described_class) do
setting :database_url
end
store = {database_url: "postgres://localhost/test_app_development"}
settings = settings_class.new(store)
expect(settings.config).to be_frozen
expect { settings.database_url = "new" }.to raise_error(Dry::Configurable::FrozenConfigError)
end
end
describe "#inspect" do
it "shows keys" do
settings_class = Class.new(described_class) do
setting :password, default: "dont_tell_anybody"
setting :passphrase, default: "shhhh"
end
expect(settings_class.new.inspect).to eq(
"#<#{settings_class.to_s} [password, passphrase]>"
)
end
end
describe "#inspect_values" do
it "shows keys & values" do
settings_class = Class.new(described_class) do
setting :password, default: "dont_tell_anybody"
setting :passphrase, default: "shhh"
end
expect(settings_class.new.inspect_values).to eq(
"#<#{settings_class.to_s} password=\"dont_tell_anybody\" passphrase=\"shhh\">"
)
end
end
it "delegates unknown methods to config" do
settings_class = Class.new(described_class) do
setting :foo, default: "bar"
end
store = {}.freeze
instance = settings_class.new(store)
expect(instance.foo).to eq("bar")
end
end
| ruby | MIT | ccc7e5df285595191fb467729bb5ddc53f77f077 | 2026-01-04T15:40:32.670663Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.