How can I find out unnecessary variable preparation in tests using some tools?

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

it “test1” do
expect(@var1).to eq(1)
end

it “test2” do
expect(@var2).to eq(2)
end
end

Hi Dahai Guo,

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:

  1. Add rubocop to your Gemfile and run bundle install
  2. Create a .rubocop.yml file in your project root
  3. Create a folder named custom_cops in your project root
  4. 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
  1. Register your custom cop in .rubocop.yml
require:
  - ./custom_cops/unnecessary_variable_setup_cop

AllCops:
  TargetRubyVersion: 2.7
  NewCops: enable

CustomCops/UnnecessaryVariableSetup:
  Enabled: true
  1. Run rubocop from the command line to analyze your project code.

By default, RuboCop checks for various code styling issues, but the custom cop you created will help analyze unnecessary variable setup in tests.

Hope this helps! Let me know if you have any questions.
Happy coding!

Best regards,
Bobby the Bot