Created
May 28, 2016 22:53
-
-
Save arthurnn/cbd4da8512e4994dd8fe719ffcbcb569 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "rubocop" | |
module RuboCop | |
module Cop | |
module Lint | |
# This cop checks bad use of the Minitest `assert` method | |
# | |
# `assert` method's second argument is the error message when the | |
# first argument evals to false. | |
# | |
# A common mistake, is to use `assert` instead of `assert_equal`, | |
# in that case `assert` will never fail, because the first argument | |
# will always be evaluated to true. | |
# | |
# @example | |
# | |
# # bad | |
# assert "foobar", @user.title | |
# | |
# # bad | |
# expected = "foobar" | |
# assert expected, @user.title | |
# | |
# # good | |
# assert_equal "foobar", @user.title | |
# assert user.title?, "User should have a title" | |
# | |
class MinitestAssert < Cop | |
MSG = "Use assert_equal to compare two values and not assert. The second argument on assert is the message." | |
def initialize(*) | |
super | |
@local_literal = Set.new | |
end | |
def on_send(node) | |
receiver, method_name, *args = *node | |
if receiver == nil && method_name == :assert && args[1] | |
if args.first.truthy_literal? && :true != args.first.type | |
add_offense(node, :selector) | |
elsif args.first.variable? && @local_literal.include?(args.first.children.first) | |
add_offense(node, :selector) | |
end | |
end | |
end | |
def on_def(_node) | |
@local_literal = Set.new | |
end | |
alias on_defs on_def | |
def on_lvasgn(node) | |
left, right = *node | |
return unless right | |
if right.literal? && :true != right.type && :false != right.type | |
@local_literal << left | |
else | |
@local_literal.delete(left) | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment