Skip to content
This repository was archived by the owner on Nov 30, 2024. It is now read-only.

Commit 778f143

Browse files
committed
Treat only symbol keys as keyword arguments
If you pass key-value pairs to a method only the keys that are Symbols will be treated as keyword arguments. If there are optional arguments the rest of the keys will be passed to the optional one. Given a method foo(x = {}, y: 1): * foo('a' => 1) => will work * foo('a' => 1, :y => 2) => will work * foo('a' => 1, :b => 2) => will raise ArgumentError unknown keyword: b
1 parent ed84b42 commit 778f143

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

lib/rspec/support/method_signature_verifier.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,14 @@ def unlimited_args?
361361

362362
def split_args(*args)
363363
kw_args = if @signature.has_kw_args_in?(args)
364-
args.pop.keys
364+
last = args.pop
365+
non_kw_args = last.reject { |k, _| k.is_a?(Symbol) }
366+
if non_kw_args.empty?
367+
last.keys
368+
else
369+
args << non_kw_args
370+
last.select { |k, _| k.is_a?(Symbol) }.keys
371+
end
365372
else
366373
[]
367374
end

spec/rspec/support/method_signature_verifier_spec.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -384,13 +384,17 @@ def arity_kw(x, y = {}, z:2); end
384384
expect(valid?(nil, :a => 1)).to eq(false)
385385
end
386386

387-
it 'allows Hash containing strings as last argument' do
387+
it 'treats symbols as keyword arguments and the rest as optional argument' do
388388
expect(valid?(nil, 'a' => 1)).to eq(true)
389+
expect(valid?(nil, 'a' => 1, :z => 3)).to eq(true)
390+
expect(valid?(nil, 'a' => 1, :b => 3)).to eq(false)
391+
expect(valid?(nil, 'a' => 1, :b => 2, :z => 3)).to eq(false)
389392
end
390393

391394
it 'mentions the invalid keyword args in the error', :pending => RSpec::Support::Ruby.jruby? && !RSpec::Support::Ruby.jruby_9000? do
392-
expect(error_for(nil, nil, :a => 0)).to \
393-
eq("Invalid keyword arguments provided: a")
395+
expect(error_for(1, 2, :a => 0)).to eq("Invalid keyword arguments provided: a")
396+
expect(error_for(1, :a => 0)).to eq("Invalid keyword arguments provided: a")
397+
expect(error_for(1, 'a' => 0, :b => 0)).to eq("Invalid keyword arguments provided: b")
394398
end
395399

396400
it 'describes invalid arity precisely' do

0 commit comments

Comments
 (0)