From 978113bcb2d2c05e8e7770b4ba9526e76b415988 Mon Sep 17 00:00:00 2001 From: Ross Brandes Date: Mon, 12 Oct 2026 10:20:15 -0400 Subject: [PATCH] Fold keywords into an options hash for replaced new and class methods Replacing a class swaps `new` and its class methods for generic `(*args, **kwargs)` lambdas, so Ruby always splits brace-less keywords like `Klass.new(item: "hello")` into kwargs. Mocktail then validated those kwargs against the real method, and when that method takes an options hash (`def initialize(opts = {})`) rather than keywords, it raised `ArgumentError: unknown keyword: :item`, even though Ruby 3 passes keywords to a method with no keyword params as a trailing positional hash. Instance-method doubles never had this problem because their lambdas are generated from the real signature. Add FoldsKeywordsIntoOptionsHash, which applies Ruby's rule: fold non-empty kwargs into a trailing hash when the original method has no :key, :keyreq, :keyrest, or :nokey params. It reads params through GrabsOriginalMethodParameters so Sorbet-wrapped methods report their real signature. Call it before building the Call in HandlesDryNewCall and in the mocked branch of replaced class methods, so validation, call logging, and stub matching all see the same shape instance doubles already record. test_replace_class asserted that `House.room(wrong: :arg)` raises for `def self.room(room_name)`, which real Ruby accepts, so it now asserts on a call Ruby also rejects. Picks up the failing test from #20 and makes it pass. --- CHANGELOG.md | 6 ++ lib/mocktail/handles_dry_new_call.rb | 5 + .../redefines_singleton_methods.rb | 5 + .../share/folds_keywords_into_options_hash.rb | 22 +++++ .../sorbet/mocktail/handles_dry_new_call.rb | 5 + .../redefines_singleton_methods.rb | 5 + .../share/folds_keywords_into_options_hash.rb | 25 +++++ src/mocktail/handles_dry_new_call.rb | 5 + .../redefines_singleton_methods.rb | 5 + .../share/folds_keywords_into_options_hash.rb | 25 +++++ test/safe/of_next_test.rb | 23 +++++ test/safe/replace_test.rb | 53 ++++++++++- .../folds_keywords_into_options_hash_test.rb | 92 +++++++++++++++++++ 13 files changed, 275 insertions(+), 1 deletion(-) create mode 100644 lib/mocktail/share/folds_keywords_into_options_hash.rb create mode 100644 lib/mocktail/sorbet/mocktail/share/folds_keywords_into_options_hash.rb create mode 100644 src/mocktail/share/folds_keywords_into_options_hash.rb create mode 100644 test/unit/share/folds_keywords_into_options_hash_test.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index ac6f8c3..0e214d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ * Fix arity validation staying disabled after a `stubs` or `verify` block with `ignore_arity: true` raises +* Fix `ArgumentError: unknown keyword` when a replaced class's `new` or class + method takes an options hash and is called with brace-less keywords + [#20](https://github.com/testdouble/mocktail/pull/20) +* Replaced `new` and class methods with no keyword parameters now accept + keyword-style calls as a trailing hash, as real Ruby does, instead of raising + `ArgumentError` # 3.0.0 diff --git a/lib/mocktail/handles_dry_new_call.rb b/lib/mocktail/handles_dry_new_call.rb index e2927e3..390d5c7 100644 --- a/lib/mocktail/handles_dry_new_call.rb +++ b/lib/mocktail/handles_dry_new_call.rb @@ -1,3 +1,5 @@ +require_relative "share/folds_keywords_into_options_hash" + module Mocktail class HandlesDryNewCall extend T::Sig @@ -7,9 +9,12 @@ def initialize @logs_call = LogsCall.new @fulfills_stubbing = FulfillsStubbing.new @imitates_type = ImitatesType.new + @folds_keywords_into_options_hash = FoldsKeywordsIntoOptionsHash.new end def handle(type, args, kwargs, block) + args, kwargs = @folds_keywords_into_options_hash.fold(type.instance_method(:initialize), args, kwargs) + @validates_arguments.validate(Call.new( original_method: type.instance_method(:initialize), args: args, diff --git a/lib/mocktail/replaces_type/redefines_singleton_methods.rb b/lib/mocktail/replaces_type/redefines_singleton_methods.rb index 31b5a91..cda0f40 100644 --- a/lib/mocktail/replaces_type/redefines_singleton_methods.rb +++ b/lib/mocktail/replaces_type/redefines_singleton_methods.rb @@ -1,9 +1,12 @@ +require_relative "../share/folds_keywords_into_options_hash" + module Mocktail class RedefinesSingletonMethods extend T::Sig def initialize @handles_dry_call = HandlesDryCall.new + @folds_keywords_into_options_hash = FoldsKeywordsIntoOptionsHash.new end def redefine(type) @@ -16,10 +19,12 @@ def redefine(type) declare_singleton_method_missing_errors!(type) handles_dry_call = @handles_dry_call + folds_keywords_into_options_hash = @folds_keywords_into_options_hash type_replacement.replacement_methods = type_replacement.original_methods&.map { |original_method| type.singleton_class.send(:undef_method, original_method.name) type.define_singleton_method original_method.name, ->(*args, **kwargs, &block) { if TopShelf.instance.singleton_methods_replaced?(type) + args, kwargs = folds_keywords_into_options_hash.fold(original_method, args, kwargs) handles_dry_call.handle(Call.new( singleton: true, double: type, diff --git a/lib/mocktail/share/folds_keywords_into_options_hash.rb b/lib/mocktail/share/folds_keywords_into_options_hash.rb new file mode 100644 index 0000000..165e19e --- /dev/null +++ b/lib/mocktail/share/folds_keywords_into_options_hash.rb @@ -0,0 +1,22 @@ +module Mocktail + class FoldsKeywordsIntoOptionsHash + extend T::Sig + + KEYWORD_PARAM_TYPES = [:key, :keyreq, :keyrest, :nokey].freeze + + def initialize + @grabs_original_method_parameters = GrabsOriginalMethodParameters.new + end + + # Ruby 3 passes keywords to a method with no keyword params as a trailing + # positional hash, but our generic (*args, **kwargs) lambdas always split + # them out, so fold them back in to match what the real method would see + + def fold(original_method, args, kwargs) + return [args, kwargs] if kwargs.empty? || original_method.nil? + return [args, kwargs] if @grabs_original_method_parameters.grab(original_method).any? { |type, _| KEYWORD_PARAM_TYPES.include?(type) } + + [[*args, kwargs], {}] + end + end +end diff --git a/lib/mocktail/sorbet/mocktail/handles_dry_new_call.rb b/lib/mocktail/sorbet/mocktail/handles_dry_new_call.rb index b17e7e7..ed57dc8 100644 --- a/lib/mocktail/sorbet/mocktail/handles_dry_new_call.rb +++ b/lib/mocktail/sorbet/mocktail/handles_dry_new_call.rb @@ -1,5 +1,7 @@ # typed: strict +require_relative "share/folds_keywords_into_options_hash" + module Mocktail class HandlesDryNewCall extend T::Sig @@ -10,10 +12,13 @@ def initialize @logs_call = T.let(LogsCall.new, LogsCall) @fulfills_stubbing = T.let(FulfillsStubbing.new, FulfillsStubbing) @imitates_type = T.let(ImitatesType.new, ImitatesType) + @folds_keywords_into_options_hash = T.let(FoldsKeywordsIntoOptionsHash.new, FoldsKeywordsIntoOptionsHash) end sig { params(type: T::Class[T.all(T, Object)], args: T::Array[T.anything], kwargs: T::Hash[Symbol, T.anything], block: T.nilable(Proc)).returns(T.anything) } def handle(type, args, kwargs, block) + args, kwargs = @folds_keywords_into_options_hash.fold(type.instance_method(:initialize), args, kwargs) + @validates_arguments.validate(Call.new( original_method: type.instance_method(:initialize), args: args, diff --git a/lib/mocktail/sorbet/mocktail/replaces_type/redefines_singleton_methods.rb b/lib/mocktail/sorbet/mocktail/replaces_type/redefines_singleton_methods.rb index 16edfa5..4295b93 100644 --- a/lib/mocktail/sorbet/mocktail/replaces_type/redefines_singleton_methods.rb +++ b/lib/mocktail/sorbet/mocktail/replaces_type/redefines_singleton_methods.rb @@ -1,5 +1,7 @@ # typed: strict +require_relative "../share/folds_keywords_into_options_hash" + module Mocktail class RedefinesSingletonMethods extend T::Sig @@ -7,6 +9,7 @@ class RedefinesSingletonMethods sig { void } def initialize @handles_dry_call = T.let(HandlesDryCall.new, HandlesDryCall) + @folds_keywords_into_options_hash = T.let(FoldsKeywordsIntoOptionsHash.new, FoldsKeywordsIntoOptionsHash) end sig { params(type: T.any(T::Class[T.anything], Module)).void } @@ -20,10 +23,12 @@ def redefine(type) declare_singleton_method_missing_errors!(type) handles_dry_call = @handles_dry_call + folds_keywords_into_options_hash = @folds_keywords_into_options_hash type_replacement.replacement_methods = type_replacement.original_methods&.map { |original_method| type.singleton_class.send(:undef_method, original_method.name) type.define_singleton_method original_method.name, ->(*args, **kwargs, &block) { if TopShelf.instance.singleton_methods_replaced?(type) + args, kwargs = folds_keywords_into_options_hash.fold(original_method, args, kwargs) handles_dry_call.handle(Call.new( singleton: true, double: type, diff --git a/lib/mocktail/sorbet/mocktail/share/folds_keywords_into_options_hash.rb b/lib/mocktail/sorbet/mocktail/share/folds_keywords_into_options_hash.rb new file mode 100644 index 0000000..40e0c17 --- /dev/null +++ b/lib/mocktail/sorbet/mocktail/share/folds_keywords_into_options_hash.rb @@ -0,0 +1,25 @@ +# typed: strict + +module Mocktail + class FoldsKeywordsIntoOptionsHash + extend T::Sig + + KEYWORD_PARAM_TYPES = T.let([:key, :keyreq, :keyrest, :nokey].freeze, T::Array[Symbol]) + + sig { void } + def initialize + @grabs_original_method_parameters = T.let(GrabsOriginalMethodParameters.new, GrabsOriginalMethodParameters) + end + + # Ruby 3 passes keywords to a method with no keyword params as a trailing + # positional hash, but our generic (*args, **kwargs) lambdas always split + # them out, so fold them back in to match what the real method would see + sig { params(original_method: T.nilable(T.any(UnboundMethod, Method)), args: T::Array[T.anything], kwargs: T::Hash[Symbol, T.anything]).returns([T::Array[T.anything], T::Hash[Symbol, T.anything]]) } + def fold(original_method, args, kwargs) + return [args, kwargs] if kwargs.empty? || original_method.nil? + return [args, kwargs] if @grabs_original_method_parameters.grab(original_method).any? { |type, _| KEYWORD_PARAM_TYPES.include?(type) } + + [[*args, kwargs], {}] + end + end +end diff --git a/src/mocktail/handles_dry_new_call.rb b/src/mocktail/handles_dry_new_call.rb index b17e7e7..ed57dc8 100644 --- a/src/mocktail/handles_dry_new_call.rb +++ b/src/mocktail/handles_dry_new_call.rb @@ -1,5 +1,7 @@ # typed: strict +require_relative "share/folds_keywords_into_options_hash" + module Mocktail class HandlesDryNewCall extend T::Sig @@ -10,10 +12,13 @@ def initialize @logs_call = T.let(LogsCall.new, LogsCall) @fulfills_stubbing = T.let(FulfillsStubbing.new, FulfillsStubbing) @imitates_type = T.let(ImitatesType.new, ImitatesType) + @folds_keywords_into_options_hash = T.let(FoldsKeywordsIntoOptionsHash.new, FoldsKeywordsIntoOptionsHash) end sig { params(type: T::Class[T.all(T, Object)], args: T::Array[T.anything], kwargs: T::Hash[Symbol, T.anything], block: T.nilable(Proc)).returns(T.anything) } def handle(type, args, kwargs, block) + args, kwargs = @folds_keywords_into_options_hash.fold(type.instance_method(:initialize), args, kwargs) + @validates_arguments.validate(Call.new( original_method: type.instance_method(:initialize), args: args, diff --git a/src/mocktail/replaces_type/redefines_singleton_methods.rb b/src/mocktail/replaces_type/redefines_singleton_methods.rb index 16edfa5..4295b93 100644 --- a/src/mocktail/replaces_type/redefines_singleton_methods.rb +++ b/src/mocktail/replaces_type/redefines_singleton_methods.rb @@ -1,5 +1,7 @@ # typed: strict +require_relative "../share/folds_keywords_into_options_hash" + module Mocktail class RedefinesSingletonMethods extend T::Sig @@ -7,6 +9,7 @@ class RedefinesSingletonMethods sig { void } def initialize @handles_dry_call = T.let(HandlesDryCall.new, HandlesDryCall) + @folds_keywords_into_options_hash = T.let(FoldsKeywordsIntoOptionsHash.new, FoldsKeywordsIntoOptionsHash) end sig { params(type: T.any(T::Class[T.anything], Module)).void } @@ -20,10 +23,12 @@ def redefine(type) declare_singleton_method_missing_errors!(type) handles_dry_call = @handles_dry_call + folds_keywords_into_options_hash = @folds_keywords_into_options_hash type_replacement.replacement_methods = type_replacement.original_methods&.map { |original_method| type.singleton_class.send(:undef_method, original_method.name) type.define_singleton_method original_method.name, ->(*args, **kwargs, &block) { if TopShelf.instance.singleton_methods_replaced?(type) + args, kwargs = folds_keywords_into_options_hash.fold(original_method, args, kwargs) handles_dry_call.handle(Call.new( singleton: true, double: type, diff --git a/src/mocktail/share/folds_keywords_into_options_hash.rb b/src/mocktail/share/folds_keywords_into_options_hash.rb new file mode 100644 index 0000000..40e0c17 --- /dev/null +++ b/src/mocktail/share/folds_keywords_into_options_hash.rb @@ -0,0 +1,25 @@ +# typed: strict + +module Mocktail + class FoldsKeywordsIntoOptionsHash + extend T::Sig + + KEYWORD_PARAM_TYPES = T.let([:key, :keyreq, :keyrest, :nokey].freeze, T::Array[Symbol]) + + sig { void } + def initialize + @grabs_original_method_parameters = T.let(GrabsOriginalMethodParameters.new, GrabsOriginalMethodParameters) + end + + # Ruby 3 passes keywords to a method with no keyword params as a trailing + # positional hash, but our generic (*args, **kwargs) lambdas always split + # them out, so fold them back in to match what the real method would see + sig { params(original_method: T.nilable(T.any(UnboundMethod, Method)), args: T::Array[T.anything], kwargs: T::Hash[Symbol, T.anything]).returns([T::Array[T.anything], T::Hash[Symbol, T.anything]]) } + def fold(original_method, args, kwargs) + return [args, kwargs] if kwargs.empty? || original_method.nil? + return [args, kwargs] if @grabs_original_method_parameters.grab(original_method).any? { |type, _| KEYWORD_PARAM_TYPES.include?(type) } + + [[*args, kwargs], {}] + end + end +end diff --git a/test/safe/of_next_test.rb b/test/safe/of_next_test.rb index daca31c..c48a510 100644 --- a/test/safe/of_next_test.rb +++ b/test/safe/of_next_test.rb @@ -29,6 +29,29 @@ def initialize(a, b:) end end + class OptionsHash + extend T::Sig + + sig { params(opts: T.untyped).void } + def initialize(opts = {}) + raise "options hash required!" + end + end + + sig { void } + def test_of_next_with_options_hash_initializer + options_hash = Mocktail.of_next(OptionsHash) + + assert_same options_hash, OptionsHash.new(item: "hello") + end + + sig { void } + def test_of_next_with_braced_options_hash_initializer + options_hash = Mocktail.of_next(OptionsHash) + + assert_same options_hash, OptionsHash.new({item: "hello"}) + end + sig { void } def test_of_next neato_mocktail = Mocktail.of_next(Neato) diff --git a/test/safe/replace_test.rb b/test/safe/replace_test.rb index f8b48d2..df0e991 100644 --- a/test/safe/replace_test.rb +++ b/test/safe/replace_test.rb @@ -56,10 +56,13 @@ def test_replace_class House.summarize("Madiera", features: [:walls, :floor]) { "🆒" } # Argument errors still propogate - assert_raises(ArgumentError) { House.room(wrong: :arg) } + assert_raises(ArgumentError) { T.unsafe(House).room } assert_raises(ArgumentError) { T.unsafe(House).size } assert_raises(ArgumentError) { T.unsafe(House).summarize("title", "wups") } + # Keywords passed to a method without keyword params become a positional hash, as in Ruby + House.room(wrong: :arg) + # verification works verify { House.room("living") } verify { |m| House.size(uom: m.is_a(String)) } @@ -103,6 +106,54 @@ def test_replace_class assert_match(/def self.color\n end/, error.message) end + class Settings + extend T::Sig + + sig { params(opts: T.untyped).void } + def initialize(opts = {}) + raise "Unimplemented" + end + + sig { params(opts: T.untyped).returns(T.untyped) } + def self.configure(opts = {}) + raise "Unimplemented" + end + end + + sig { void } + def test_replace_class_whose_new_takes_an_options_hash + Mocktail.replace(Settings) + + stubs { T.unsafe(Settings).new(item: "hello") }.with { :stubbed } + + assert_equal :stubbed, Settings.new(item: "hello") + assert_equal :stubbed, Settings.new({item: "hello"}) + verify(times: 2) { Settings.new(item: "hello") } + end + + sig { void } + def test_replace_class_whose_class_method_takes_an_options_hash + Mocktail.replace(Settings) + + stubs { Settings.configure(item: "hello") }.with { :configured } + + assert_equal :configured, Settings.configure(item: "hello") + assert_equal :configured, Settings.configure({item: "hello"}) + verify(times: 2) { Settings.configure(item: "hello") } + end + + class AcceptsNoKeywords + # sorbet-runtime can't build a sig for `**nil`, so skip the sig wrapper + define_method :initialize, ->(a, b = {}, **nil) { raise "Unimplemented" } + end + + sig { void } + def test_replace_class_whose_new_accepts_no_keywords + Mocktail.replace(AcceptsNoKeywords) + + assert_raises(ArgumentError) { T.unsafe(AcceptsNoKeywords).new(1, x: 1) } + end + module Home extend T::Sig diff --git a/test/unit/share/folds_keywords_into_options_hash_test.rb b/test/unit/share/folds_keywords_into_options_hash_test.rb new file mode 100644 index 0000000..544e476 --- /dev/null +++ b/test/unit/share/folds_keywords_into_options_hash_test.rb @@ -0,0 +1,92 @@ +# typed: strict + +require "test_helper" + +module Mocktail + class FoldsKeywordsIntoOptionsHashTest < Minitest::Test + extend T::Sig + + class Fixtures + extend T::Sig + + sig { params(opts: T.untyped).void } + def options_hash(opts = {}) + end + + sig { params(a: T.untyped, b: T.untyped).void } + def positional_then_options_hash(a, b = {}) + end + + sig { params(rest: T.untyped).void } + def splat(*rest) + end + + sig { params(a: T.untyped).void } + def keyword(a:) + end + + sig { params(kw: T.untyped).void } + def double_splat(**kw) + end + + # sorbet-runtime can't build a sig for `**nil`, so skip the sig wrapper + define_method :no_keywords_accepted, ->(a, b = {}, **nil) {} + + sig { params(opts: T.untyped).void } + def self.class_options_hash(opts = {}) + end + end + + sig { void } + def test_folds_into_an_options_hash + assert_equal [[{a: 1}], {}], fold(:options_hash, [], {a: 1}) + end + + sig { void } + def test_folds_after_positional_args + assert_equal [[1, {a: 1}], {}], fold(:positional_then_options_hash, [1], {a: 1}) + end + + sig { void } + def test_folds_into_a_splat + assert_equal [[{a: 1}], {}], fold(:splat, [], {a: 1}) + end + + sig { void } + def test_leaves_keyword_params_alone + assert_equal [[], {a: 1}], fold(:keyword, [], {a: 1}) + end + + sig { void } + def test_leaves_double_splats_alone + assert_equal [[], {a: 1}], fold(:double_splat, [], {a: 1}) + end + + sig { void } + def test_leaves_methods_that_accept_no_keywords_alone + assert_equal [[1], {x: 1}], fold(:no_keywords_accepted, [1], {x: 1}) + end + + sig { void } + def test_leaves_empty_kwargs_alone + assert_equal [[], {}], fold(:options_hash, [], {}) + end + + sig { void } + def test_folds_for_singleton_methods + assert_equal [[{a: 1}], {}], FoldsKeywordsIntoOptionsHash.new.fold(Fixtures.method(:class_options_hash), [], {a: 1}) + end + + sig { void } + def test_leaves_kwargs_alone_without_an_original_method + assert_equal [[], {a: 1}], FoldsKeywordsIntoOptionsHash.new.fold(nil, [], {a: 1}) + end + + private + + sig { params(method_name: Symbol, args: T::Array[T.anything], kwargs: T::Hash[Symbol, T.anything]).returns([T::Array[T.anything], T::Hash[Symbol, T.anything]]) } + def fold(method_name, args, kwargs) + FoldsKeywordsIntoOptionsHash.new.fold(Fixtures.instance_method(method_name), args, kwargs) + end + end +end