diff --git a/changelog/fix_an_incorrect_autocorrect_for_rails_validation.md b/changelog/fix_an_incorrect_autocorrect_for_rails_validation.md new file mode 100644 index 0000000000..e6455ad3ca --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_rails_validation.md @@ -0,0 +1 @@ +* [#1270](https://github.com/rubocop/rubocop-rails/issues/1270): Fix an incorrect autocorrect for `Rails/Validation` when using `validates_size_of`. ([@koic][]) diff --git a/lib/rubocop/cop/rails/validation.rb b/lib/rubocop/cop/rails/validation.rb index 534af1b260..5499f3991d 100644 --- a/lib/rubocop/cop/rails/validation.rb +++ b/lib/rubocop/cop/rails/validation.rb @@ -29,7 +29,7 @@ module Rails # validates :foo, numericality: true # validates :foo, presence: true # validates :foo, absence: true - # validates :foo, size: true + # validates :foo, length: true # validates :foo, uniqueness: true # class Validation < Base @@ -120,7 +120,9 @@ def correct_validate_type_for_array(corrector, node, arguments, loc) end def validate_type(node) - node.method_name.to_s.split('_')[1] + type = node.method_name.to_s.split('_')[1] + + type == 'size' ? 'length' : type end def frozen_array_argument?(argument) diff --git a/spec/rubocop/cop/rails/validation_spec.rb b/spec/rubocop/cop/rails/validation_spec.rb index 0254dabf4e..e789842d6d 100644 --- a/spec/rubocop/cop/rails/validation_spec.rb +++ b/spec/rubocop/cop/rails/validation_spec.rb @@ -28,6 +28,8 @@ described_class::TYPES.each do |type| context "with validates_#{type}_of" do let(:autocorrected_source) do + type = 'length' if type == 'size' + "validates :full_name, :birth_date, #{type}: true" end @@ -40,6 +42,8 @@ context "with validates_#{type}_of when method arguments are enclosed in parentheses" do let(:autocorrected_source) do + type = 'length' if type == 'size' + "validates(:full_name, :birth_date, #{type}: true)" end @@ -52,6 +56,8 @@ context "with validates_#{type}_of when attributes are specified with array literal" do let(:autocorrected_source) do + type = 'length' if type == 'size' + "validates :full_name, :birth_date, #{type}: true" end @@ -64,6 +70,8 @@ context "with validates_#{type}_of when attributes are specified with frozen array literal" do let(:autocorrected_source) do + type = 'length' if type == 'size' + "validates :full_name, :birth_date, #{type}: true" end @@ -76,6 +84,8 @@ context "with validates_#{type}_of when attributes are specified with symbol array literal" do let(:autocorrected_source) do + type = 'length' if type == 'size' + "validates :full_name, :birth_date, #{type}: true" end @@ -88,6 +98,8 @@ context "with validates_#{type}_of when attributes are specified with frozen symbol array literal" do let(:autocorrected_source) do + type = 'length' if type == 'size' + "validates :full_name, :birth_date, #{type}: true" end