]> cat aescling's git repositories - mastodon.git/commitdiff
Add specs for DisallowedHashtagsValidator (#9653)
authorysksn <bluewhale1982@gmail.com>
Sat, 29 Dec 2018 06:22:51 +0000 (15:22 +0900)
committerEugen Rochko <eugen@zeonfederated.com>
Sat, 29 Dec 2018 06:22:51 +0000 (07:22 +0100)
In order to implement tests easier, `#select_tags` created.

app/validators/disallowed_hashtags_validator.rb
spec/validators/disallowed_hashtags_validator_spec.rb [new file with mode: 0644]

index 22c027b0fcac07819c5ae77e6658990b554a881d..ee06b20f6b49bd03f5f71a86daafa4c5dda3a748 100644 (file)
@@ -4,14 +4,19 @@ class DisallowedHashtagsValidator < ActiveModel::Validator
   def validate(status)
     return unless status.local? && !status.reblog?
 
-    tags = Extractor.extract_hashtags(status.text)
-    tags.keep_if { |tag| disallowed_hashtags.include? tag.downcase }
+    @status = status
+    tags    = select_tags
 
     status.errors.add(:text, I18n.t('statuses.disallowed_hashtags', tags: tags.join(', '), count: tags.size)) unless tags.empty?
   end
 
   private
 
+  def select_tags
+    tags = Extractor.extract_hashtags(@status.text)
+    tags.keep_if { |tag| disallowed_hashtags.include? tag.downcase }
+  end
+
   def disallowed_hashtags
     return @disallowed_hashtags if @disallowed_hashtags
 
diff --git a/spec/validators/disallowed_hashtags_validator_spec.rb b/spec/validators/disallowed_hashtags_validator_spec.rb
new file mode 100644 (file)
index 0000000..8ec1302
--- /dev/null
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+RSpec.describe DisallowedHashtagsValidator, type: :validator do
+  describe '#validate' do
+    before do
+      allow_any_instance_of(described_class).to receive(:select_tags) { tags }
+      described_class.new.validate(status)
+    end
+
+    let(:status) { double(errors: errors, local?: local, reblog?: reblog, text: '') }
+    let(:errors) { double(add: nil) }
+
+    context 'unless status.local? && !status.reblog?' do
+      let(:local)  { false }
+      let(:reblog) { true }
+
+      it 'not calls errors.add' do
+        expect(errors).not_to have_received(:add).with(:text, any_args)
+      end
+    end
+
+    context 'status.local? && !status.reblog?' do
+      let(:local)  { true }
+      let(:reblog) { false }
+
+      context 'tags.empty?' do
+        let(:tags) { [] }
+
+        it 'not calls errors.add' do
+          expect(errors).not_to have_received(:add).with(:text, any_args)
+        end
+      end
+
+      context '!tags.empty?' do
+        let(:tags) { %w(a b c) }
+
+        it 'calls errors.add' do
+          expect(errors).to have_received(:add)
+            .with(:text, I18n.t('statuses.disallowed_hashtags', tags: tags.join(', '), count: tags.size))
+        end
+      end
+    end
+  end
+end