Commit 9dff94db authored by Arturo Herrero's avatar Arturo Herrero

Improve code avoiding mutable state

parent 5e2b317f
...@@ -29,14 +29,10 @@ module RuboCop ...@@ -29,14 +29,10 @@ module RuboCop
MESSAGE_ALLOW = 'Do not use `allow_any_instance_of` method, use `allow_next_instance_of` instead.' MESSAGE_ALLOW = 'Do not use `allow_any_instance_of` method, use `allow_next_instance_of` instead.'
def_node_search :expect_any_instance_of?, <<~PATTERN def_node_search :expect_any_instance_of?, <<~PATTERN
(send (send (send nil? :expect_any_instance_of ...) ...)
(send nil? :expect_any_instance_of ...) _ ...
)
PATTERN PATTERN
def_node_search :allow_any_instance_of?, <<~PATTERN def_node_search :allow_any_instance_of?, <<~PATTERN
(send (send (send nil? :allow_any_instance_of ...) ...)
(send nil? :allow_any_instance_of ...) _ ...
)
PATTERN PATTERN
def on_send(node) def on_send(node)
...@@ -48,10 +44,11 @@ module RuboCop ...@@ -48,10 +44,11 @@ module RuboCop
end end
def autocorrect(node) def autocorrect(node)
replacement =
if expect_any_instance_of?(node) if expect_any_instance_of?(node)
replacement = replacement_any_instance_of(node, 'expect') replacement_any_instance_of(node, 'expect')
elsif allow_any_instance_of?(node) elsif allow_any_instance_of?(node)
replacement = replacement_any_instance_of(node, 'allow') replacement_any_instance_of(node, 'allow')
end end
lambda do |corrector| lambda do |corrector|
...@@ -62,10 +59,18 @@ module RuboCop ...@@ -62,10 +59,18 @@ module RuboCop
private private
def replacement_any_instance_of(node, rspec_prefix) def replacement_any_instance_of(node, rspec_prefix)
replacement = node.receiver.source.sub("#{rspec_prefix}_any_instance_of", "#{rspec_prefix}_next_instance_of") method_call =
replacement << " do |instance|\n" node.receiver.source.sub(
replacement << " #{rspec_prefix}(instance).#{node.method_name} #{node.children.last.source}\n" "#{rspec_prefix}_any_instance_of",
replacement << 'end' "#{rspec_prefix}_next_instance_of")
block = <<~RUBY.chomp
do |instance|
#{rspec_prefix}(instance).#{node.method_name} #{node.children.last.source}
end
RUBY
"#{method_call} #{block}"
end end
end end
end end
......
...@@ -25,6 +25,7 @@ describe RuboCop::Cop::RSpec::AnyInstanceOf do ...@@ -25,6 +25,7 @@ describe RuboCop::Cop::RSpec::AnyInstanceOf do
it 'registers an offence' do it 'registers an offence' do
inspect_source(source) inspect_source(source)
expect(cop.offenses.size).to eq(1) expect(cop.offenses.size).to eq(1)
end end
...@@ -49,6 +50,7 @@ describe RuboCop::Cop::RSpec::AnyInstanceOf do ...@@ -49,6 +50,7 @@ describe RuboCop::Cop::RSpec::AnyInstanceOf do
it 'registers an offence' do it 'registers an offence' do
inspect_source(source) inspect_source(source)
expect(cop.offenses.size).to eq(1) expect(cop.offenses.size).to eq(1)
end end
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment