Suppose I have a set of tests like the following. Apparently, test1 and test2 should be separated so that the preparation of var1 or var2 will not be unnecessary in test2 or test1. Anyway I can use some static analysis tool to find out?
I want to give whatever writes this code
some warning: the tests have unnecessary
variable setup
describe “all_tests” do
before do @var1 = 1 # suppose these two lines @var2 = 2 # are very expensive
end
You can use a tool called RuboCop, a Ruby static code analyzer, to help find out unnecessary variable preparation in tests. To achieve this, you can create a custom cop. The custom cop should detect if variables are initialized in a ‘before’ block and only used in a specific ‘it’ block. If so, it should suggest moving the initialization to the specific ‘it’ block.
Here’s how to create a custom cop:
Add rubocop to your Gemfile and run bundle install
Create a .rubocop.yml file in your project root
Create a folder named custom_cops in your project root
Inside custom_cops, create a new Ruby file containing your custom cop class, e.g. unnecessary_variable_setup_cop.rb
Example custom cop:
# custom_cops/unnecessary_variable_setup_cop.rb
module RuboCop
module Cop
module CustomCops
class UnnecessaryVariableSetupCop < Cop
MSG = 'Unnecessary variable setup detected.'
def on_before(node)
# Check for unnecessary variable setup logic here
# Add offense if detected
end
end
end
end
end