rubocop / rubocop-minitest

Code style checking for Minitest files.
https://docs.rubocop.org/rubocop-minitest
MIT License
144 stars 44 forks source link

Tests using AssertOffense should Fail with a usable message if the relevant cop is not defined #314

Closed brandoncc closed 3 months ago

brandoncc commented 3 months ago

Including the AssertOffense module currently fails with a cryptic message if the cop can't be found. This PR introduces an explicit failure with a useful message, replacing the NoMethodError that is currently raised in this situation.

Before

Error:
RuboCop::Cop::MyCops::MyNewCopTest#test_works:
NoMethodError: undefined method `[]=' for nil
    /Users/brandoncc/.gem/ruby/3.3.1/gems/rubocop-minitest-0.35.1/lib/rubocop/minitest/assert_offense.rb:109:in `assert_offense'
    test/rubocop/cop/my_cops/my_new_cop_test.rb:12:in `block in <class:MyNewCopTest>'

After

Error:
RuboCop::Cop::MyCops::MyNewCopTest#test_works:
RuntimeError: Cop not defined: RuboCop::Cop::MyCops::MyNewCop
    /Users/brandoncc/dev/rubocop-minitest/lib/rubocop/minitest/assert_offense.rb:81:in `cop'
    /Users/brandoncc/dev/rubocop-minitest/lib/rubocop/minitest/assert_offense.rb:111:in `assert_offense'
    test/rubocop/cop/my_cops/my_new_cop_test.rb:12:in `block in <class:MyNewCopTest>'

My first implementation simply changed AssertOffense#setup to fail if the cop wasn't found, but that broke four tests in the test suite. Given that the advice given is to require support.rb, which includes AssertOffense on every instance of Minitest::Test, I realized that implementation was likely to break many gem-consumer repositories in this same way.

The second implementation refactors the initialization of a Cop to be lazy, so that the error is only raised when the cop is attempted to be accessed. This has the downside of @cop being nil until #cop is called, but these failures will only happen in tests where @cop is accessed directly. I believe these failures, if experienced by consumers of the gem, will be easier to resolve than the errors likely to have been introduced by my first implementation.


Before submitting the PR make sure the following are checked:

koic commented 3 months ago

Thanks!