Skip to content

Commit

Permalink
Merge pull request #208 from koic/make_minitest_assert_with_expected_…
Browse files Browse the repository at this point in the history
…argument_aware_of_message_variable

[Fix #206] Make `Minitest/AssertWithExpectedArgument` aware of message variable
  • Loading branch information
koic authored Dec 23, 2022
2 parents b97ae78 + a4f7cd4 commit 36dcb4c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#206](https://github.com/rubocop/rubocop/issues/206): Make `Minitest/AssertWithExpectedArgument` aware of message variable. ([@koic][])
8 changes: 7 additions & 1 deletion lib/rubocop/cop/minitest/assert_with_expected_argument.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ module Minitest
# Tries to detect when a user accidentally used
# `assert` when they meant to use `assert_equal`.
#
# NOTE: The second argument to the `assert` method named `message` and `msg` is allowed.
# Because their names are inferred as message arguments.
#
# @safety
# This cop is unsafe because it is not possible to determine
# whether the second argument of `assert` is a message or not.
Expand All @@ -19,18 +22,21 @@ module Minitest
# assert_equal(3, my_list.length)
# assert_equal(expected, actual)
# assert(foo, 'message')
# assert(foo, message)
# assert(foo, msg)
#
class AssertWithExpectedArgument < Base
MSG = 'Did you mean to use `assert_equal(%<arguments>s)`?'
RESTRICT_ON_SEND = %i[assert].freeze
MESSAGE_VARIABLES = %w[message msg].freeze

def_node_matcher :assert_with_two_arguments?, <<~PATTERN
(send nil? :assert $_ $_)
PATTERN

def on_send(node)
assert_with_two_arguments?(node) do |_expected, message|
return if message.str_type? || message.dstr_type?
return if message.str_type? || message.dstr_type? || MESSAGE_VARIABLES.include?(message.source)

arguments = node.arguments.map(&:source).join(', ')
add_offense(node, message: format(MSG, arguments: arguments))
Expand Down
20 changes: 20 additions & 0 deletions test/rubocop/cop/minitest/assert_with_expected_argument_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,26 @@ def test_do_something
RUBY
end

def test_does_not_register_offense_when_second_argument_is_a_variable_named_message
assert_no_offenses(<<~RUBY)
class FooTest < Minitest::Test
def test_do_something
assert([], message)
end
end
RUBY
end

def test_does_not_register_offense_when_second_argument_is_a_variable_named_msg
assert_no_offenses(<<~RUBY)
class FooTest < Minitest::Test
def test_do_something
assert([], msg)
end
end
RUBY
end

def test_does_not_register_offense_when_second_argument_is_an_interpolated_string
assert_no_offenses(<<~'RUBY')
class FooTest < Minitest::Test
Expand Down

0 comments on commit 36dcb4c

Please sign in to comment.