Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions lib/rubocop/cop/github/rails_no_redundant_image_alt.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# frozen_string_literal: true

require "rubocop"

module RuboCop
module Cop
module GitHub
module Accessibility
class NoRedundantImageAlt < Base
MSG = "Alt prop should not contain `image` or `picture` as screen readers already announce the element as an image"
REDUNDANT_ALT_WORDS = %w(image picture)

def_node_search :redundant_alt?, "(pair (sym :alt) (str #contains_redundant_alt_text?))"

def on_send(node)
receiver, method_name, _= *node

if receiver.nil? && method_name == :image_tag
if redundant_alt?(node)
add_offense(node.loc.selector)
end
end
end

private

def contains_redundant_alt_text?(string)
return false if string.empty?

if (string.downcase.split & REDUNDANT_ALT_WORDS).any?
return true
end
end
end
end
end
end
end
28 changes: 28 additions & 0 deletions test/test_rails_no_redundant_image_alt.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# frozen_string_literal: true

require_relative "./cop_test"
require "minitest/autorun"
require "rubocop/cop/github/rails_no_redundant_image_alt"

class NoRedundantImageAlt < CopTest
def cop_class
RuboCop::Cop::GitHub::Accessibility::NoRedundantImageAlt
end

def test_no_redundant_image_alt_offense
offenses = erb_investigate cop, <<-ERB, "app/views/products/index.html.erb"
<%= image_tag "cat.gif", size: "12x12", alt: "Picture of a cat" %>
ERB

assert_equal 1, offenses.count
assert_equal "Alt prop should not contain `image` or `picture` as screen readers already announce the element as an image", offenses[0].message
end

def test_no_redundant_image_alt_no_offense
offenses = erb_investigate cop, <<-ERB, "app/views/products/index.html.erb"
<%= image_tag "cat.gif", size: "12x12", alt: "A black cat" %>
ERB

assert_equal 0, offenses.count
end
end