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

Commit a82ab9c

Browse files
committed
Add helper for running class_exec with keywords when needed
1 parent 63c03e5 commit a82ab9c

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
module RSpec
2+
module Support
3+
module WithKeywordsWhenNeeded
4+
# This module adds keyword sensitive support for core ruby methods
5+
# where we cannot use `ruby2_keywords` directly.
6+
7+
module_function
8+
9+
if RSpec::Support::RubyFeatures.kw_args_supported?
10+
# Remove this in RSpec 4 in favour of explictly passed in kwargs where
11+
# this is used. Works around a warning in Ruby 2.7
12+
13+
def class_exec(klass, *args, &block)
14+
if MethodSignature.new(block).has_kw_args_in?(args)
15+
binding.eval(<<-CODE, __FILE__, __LINE__)
16+
kwargs = args.pop
17+
klass.class_exec(*args, **kwargs, &block)
18+
CODE
19+
else
20+
klass.class_exec(*args, &block)
21+
end
22+
end
23+
ruby2_keywords :class_exec if respond_to?(:ruby2_keywords, true)
24+
else
25+
def class_exec(klass, *args, &block)
26+
klass.class_exec(*args, &block)
27+
end
28+
end
29+
end
30+
end
31+
end
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
require 'rspec/support/with_keywords_when_needed'
2+
3+
module RSpec::Support
4+
RSpec.describe "WithKeywordsWhenNeeded" do
5+
6+
describe ".class_exec" do
7+
extend RubyFeatures
8+
9+
let(:klass) do
10+
Class.new do
11+
def self.check_argument(argument)
12+
raise ArgumentError unless argument == 42
13+
end
14+
end
15+
end
16+
17+
def run(klass, *args, &block)
18+
WithKeywordsWhenNeeded.class_exec(klass, *args, &block)
19+
end
20+
21+
it "will run a block without keyword arguments" do
22+
run(klass, 42) { |arg| check_argument(arg) }
23+
end
24+
25+
it "will run a block with a hash with out keyword arguments" do
26+
run(klass, "value" => 42) { |arg| check_argument(arg["value"]) }
27+
end
28+
29+
it "will run a block with optional keyword arguments when none are provided", :if => kw_args_supported? do
30+
binding.eval(<<-CODE, __FILE__, __LINE__)
31+
run(klass, 42) { |arg, val: nil| check_argument(arg) }
32+
CODE
33+
end
34+
35+
it "will run a block with optional keyword arguments when they are provided", :if => required_kw_args_supported? do
36+
binding.eval(<<-CODE, __FILE__, __LINE__)
37+
run(klass, val: 42) { |val: nil| check_argument(val) }
38+
CODE
39+
end
40+
41+
it "will run a block with required keyword arguments", :if => required_kw_args_supported? do
42+
binding.eval(<<-CODE, __FILE__, __LINE__)
43+
run(klass, val: 42) { |val:| check_argument(val) }
44+
CODE
45+
end
46+
end
47+
end
48+
end

0 commit comments

Comments
 (0)