Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

class BadgeGranter
  class GrantError < StandardError
  end

  def self.disable_queue
    @queue_disabled = true
  end

  def self.enable_queue
    @queue_disabled = false
  end

  def initialize(badge, user, opts = {})
    @badge, @user, @opts = badge, user, opts
    @granted_by = opts[:granted_by] || Discourse.system_user
    @post_id = opts[:post_id]
  end

  def self.grant(badge, user, opts = {})
    BadgeGranter.new(badge, user, opts).grant
  end

  def self.enqueue_mass_grant_for_users(
    badge,
    emails: [],
    usernames: [],
    ensure_users_have_badge_once: true
  )
    emails = emails.map(&:downcase)
    usernames = usernames.map(&:downcase)
    usernames_map_to_ids = {}
    emails_map_to_ids = {}
    if usernames.size > 0
      usernames_map_to_ids = User.where(username_lower: usernames).pluck(:username_lower, :id).to_h
    end
    if emails.size > 0
      emails_map_to_ids = User.with_email(emails).pluck("LOWER(user_emails.email)", :id).to_h
    end

    count_per_user = {}
    unmatched = Set.new
    (usernames + emails).each do |entry|
      id = usernames_map_to_ids[entry] || emails_map_to_ids[entry]
      if id.blank?
        unmatched << entry
        next
      end

      if ensure_users_have_badge_once
        count_per_user[id] = 1
      else
        count_per_user[id] ||= 0
        count_per_user[id] += 1
      end
    end

    existing_owners_ids = []
    if ensure_users_have_badge_once
      existing_owners_ids = UserBadge.where(badge: badge).distinct.pluck(:user_id)
    end
    count_per_user.each do |user_id, count|
      next if ensure_users_have_badge_once && existing_owners_ids.include?(user_id)

      Jobs.enqueue(:mass_award_badge, user: user_id, badge: badge.id, count: count)
    end

    {
      unmatched_entries: unmatched.to_a,
      matched_users_count: count_per_user.size,
      unmatched_entries_count: unmatched.size,
    }
  end

  def self.mass_grant(badge, user, count:)
    return if !badge.enabled?

    raise ArgumentError.new("count can't be less than 1") if count < 1

    UserBadge.transaction do
      DB.exec(
        <<~SQL * count,
        INSERT INTO user_badges
        (granted_at, created_at, granted_by_id, user_id, badge_id, seq)
        VALUES
        (
          :now,
          :now,
          :system,
          :user_id,
          :badge_id,
          COALESCE((
            SELECT MAX(seq) + 1
            FROM user_badges
            WHERE badge_id = :badge_id AND user_id = :user_id
          ), 0)
        );
      SQL
        now: Time.zone.now,
        system: Discourse.system_user.id,
        user_id: user.id,
        badge_id: badge.id,
      )
      notification = send_notification(user.id, user.username, user.locale, badge)

      DB.exec(<<~SQL, notification_id: notification.id, user_id: user.id, badge_id: badge.id)
        UPDATE user_badges
        SET notification_id = :notification_id
        WHERE notification_id IS NULL AND user_id = :user_id AND badge_id = :badge_id
      SQL

      UserBadge.update_featured_ranks!(user.id)
    end
  end

  def grant
    return if @granted_by && !Guardian.new(@granted_by).can_grant_badges?(@user)
    return unless @badge.present? && @badge.enabled?
    return if @user.blank?

    find_by = { badge_id: @badge.id, user_id: @user.id }

    find_by[:post_id] = @post_id if @badge.multiple_grant?

    user_badge = UserBadge.find_by(find_by)

    if user_badge.nil? || (@badge.multiple_grant? && @post_id.nil?)
      UserBadge.transaction do
        seq = 0
        if @badge.multiple_grant?
          seq = UserBadge.where(badge: @badge, user: @user).maximum(:seq)
          seq = (seq || -1) + 1
        end

        user_badge =
          UserBadge.create!(
            badge: @badge,
            user: @user,
            granted_by: @granted_by,
            granted_at: @opts[:created_at] || Time.now,
            post_id: @post_id,
            seq: seq,
          )

        return unless SiteSetting.enable_badges

        if @granted_by != Discourse.system_user
          StaffActionLogger.new(@granted_by).log_badge_grant(user_badge)
        end

        skip_new_user_tips = @user.user_option.skip_new_user_tips
        unless self.class.suppress_notification?(@badge, user_badge.granted_at, skip_new_user_tips)
          notification =
            self.class.send_notification(@user.id, @user.username, @user.effective_locale, @badge)
          user_badge.update!(notification_id: notification.id)
        end
      end
    end

    user_badge
  end

  def self.revoke(user_badge, options = {})
    UserBadge.transaction do
      user_badge.destroy!
      if options[:revoked_by]
        StaffActionLogger.new(options[:revoked_by]).log_badge_revoke(user_badge)
      end

      # If the user's title is the same as the badge name OR the custom badge name, remove their title.
      custom_badge_name =
        TranslationOverride.find_by(translation_key: user_badge.badge.translation_key)&.value
      user_title_is_badge_name = user_badge.user.title == user_badge.badge.name
      user_title_is_custom_badge_name =
        custom_badge_name.present? && user_badge.user.title == custom_badge_name

      if user_title_is_badge_name || user_title_is_custom_badge_name
        if options[:revoked_by]
          StaffActionLogger.new(options[:revoked_by]).log_title_revoke(
            user_badge.user,
            revoke_reason: "user title was same as revoked badge name or custom badge name",
            previous_value: user_badge.user.title,
          )
        end
        user_badge.user.title = nil
        user_badge.user.save!
      end
    end
  end

  def self.revoke_all(badge)
    custom_badge_names =
      TranslationOverride.where(translation_key: badge.translation_key).pluck(:value)

    users =
      User.joins(:user_badges).where(user_badges: { badge_id: badge.id }).where(title: badge.name)
    users =
      users.or(
        User.joins(:user_badges).where(title: custom_badge_names),
      ) unless custom_badge_names.empty?
    users.update_all(title: nil)

    UserBadge.where(badge: badge).delete_all
  end

  def self.queue_badge_grant(type, opt)
    return if !SiteSetting.enable_badges || @queue_disabled
    payload = nil

    case type
    when Badge::Trigger::PostRevision
      post = opt[:post]
      payload = { type: "PostRevision", post_ids: [post.id] }
    when Badge::Trigger::UserChange
      user = opt[:user]
      payload = { type: "UserChange", user_ids: [user.id] }
    when Badge::Trigger::TrustLevelChange
      user = opt[:user]
      payload = { type: "TrustLevelChange", user_ids: [user.id] }
    when Badge::Trigger::PostAction
      action = opt[:post_action]
      payload = { type: "PostAction", post_ids: [action.post_id, action.related_post_id].compact! }
    end

    Discourse.redis.lpush queue_key, payload.to_json if payload
  end

  def self.clear_queue!
    Discourse.redis.del queue_key
  end

  def self.process_queue!
    limit = 1000
    items = []
    while limit > 0 && item = Discourse.redis.lpop(queue_key)
      items << JSON.parse(item)
      limit -= 1
    end

    items = items.group_by { |i| i["type"] }

    items.each do |type, list|
      post_ids = list.flat_map { |i| i["post_ids"] }.compact.uniq
      user_ids = list.flat_map { |i| i["user_ids"] }.compact.uniq

      next unless post_ids.present? || user_ids.present?

      find_by_type(type).each { |badge| backfill(badge, post_ids: post_ids, user_ids: user_ids) }
    end
  end

  def self.find_by_type(type)
    Badge.where(trigger: "Badge::Trigger::#{type}".constantize)
  end

  def self.queue_key
    "badge_queue"
  end

  # Options:
  #   :target_posts - whether the badge targets posts
  #   :trigger - the Badge::Trigger id
  def self.contract_checks!(sql, opts = {})
    return if sql.blank?

    if Badge::Trigger.uses_post_ids?(opts[:trigger])
      unless sql.match(/:post_ids/)
        raise(
          "Contract violation:\nQuery triggers on posts, but does not reference the ':post_ids' array",
        )
      end
      if sql.match(/:user_ids/)
        raise "Contract violation:\nQuery triggers on posts, but references the ':user_ids' array"
      end
    end

    if Badge::Trigger.uses_user_ids?(opts[:trigger])
      unless sql.match(/:user_ids/)
        raise "Contract violation:\nQuery triggers on users, but does not reference the ':user_ids' array"
      end
      if sql.match(/:post_ids/)
        raise "Contract violation:\nQuery triggers on users, but references the ':post_ids' array"
      end
    end

    if opts[:trigger] && !Badge::Trigger.is_none?(opts[:trigger])
      unless sql.match(/:backfill/)
        raise "Contract violation:\nQuery is triggered, but does not reference the ':backfill' parameter.\n(Hint: if :backfill is TRUE, you should ignore the :post_ids/:user_ids)"
      end
    end

    # TODO these three conditions have a lot of false negatives
    if opts[:target_posts]
      unless sql.match(/post_id/)
        raise "Contract violation:\nQuery targets posts, but does not return a 'post_id' column"
      end
    end

    unless sql.match(/user_id/)
      raise "Contract violation:\nQuery does not return a 'user_id' column"
    end
    unless sql.match(/granted_at/)
      raise "Contract violation:\nQuery does not return a 'granted_at' column"
    end
    if sql.match(/;\s*\z/)
      raise "Contract violation:\nQuery ends with a semicolon. Remove the semicolon; your sql will be used in a subquery."
    end
  end

  # Options:
  #   :target_posts - whether the badge targets posts
  #   :trigger - the Badge::Trigger id
  #   :explain - return the EXPLAIN query
  def self.preview(sql, opts = {})
    params = { user_ids: [], post_ids: [], backfill: true }

    BadgeGranter.contract_checks!(sql, opts)

    # hack to allow for params, otherwise sanitizer will trigger sprintf
    count_sql = <<~SQL
      SELECT COUNT(*) count
                 FROM (
                        #{sql}
                      ) q
                WHERE :backfill = :backfill
    SQL
    grant_count = DB.query_single(count_sql, params).first.to_i

    grants_sql =
      if opts[:target_posts]
        <<~SQL
        SELECT u.id, u.username, q.post_id, t.title, q.granted_at
          FROM (
                 #{sql}
               ) q
          JOIN users u on u.id = q.user_id
     LEFT JOIN badge_posts p on p.id = q.post_id
     LEFT JOIN topics t on t.id = p.topic_id
         WHERE :backfill = :backfill
         LIMIT 10
      SQL
      else
        <<~SQL
        SELECT u.id, u.username, q.granted_at
         FROM (
                #{sql}
              ) q
         JOIN users u on u.id = q.user_id
        WHERE :backfill = :backfill
        LIMIT 10
      SQL
      end

    query_plan = nil
    # HACK: active record sanitization too flexible, force it to go down the sanitization path that cares not for % stuff
    # note mini_sql uses AR sanitizer at the moment (review if changed)
    query_plan = DB.query_hash("EXPLAIN #{sql} /*:backfill*/", params) if opts[:explain]

    sample = DB.query(grants_sql, params)

    sample.each do |result|
      unless User.exists?(id: result.id)
        raise "Query returned a non-existent user ID:\n#{result.id}"
      end
      unless result.granted_at
        raise "Query did not return a badge grant time\n(Try using 'current_timestamp granted_at')"
      end
      if opts[:target_posts]
        raise "Query did not return a post ID" unless result.post_id
        unless Post.exists?(result.post_id).present?
          raise "Query returned a non-existent post ID:\n#{result.post_id}"
        end
      end
    end

    { grant_count: grant_count, sample: sample, query_plan: query_plan }
  rescue => e
    { errors: e.message }
  end

  MAX_ITEMS_FOR_DELTA ||= 200
  def self.backfill(badge, opts = nil)
    return unless SiteSetting.enable_badges
    return unless badge.enabled
    return unless badge.query.present?

    post_ids = user_ids = nil
    post_ids = opts[:post_ids] if opts
    user_ids = opts[:user_ids] if opts

    # safeguard fall back to full backfill if more than 200
    if (post_ids && post_ids.size > MAX_ITEMS_FOR_DELTA) ||
         (user_ids && user_ids.size > MAX_ITEMS_FOR_DELTA)
      post_ids = nil
      user_ids = nil
    end

    post_ids = nil if post_ids.blank?
    user_ids = nil if user_ids.blank?

    full_backfill = !user_ids && !post_ids

    post_clause = badge.target_posts ? "AND (q.post_id = ub.post_id OR NOT :multiple_grant)" : ""
    post_id_field = badge.target_posts ? "q.post_id" : "NULL"

    sql = <<~SQL
      DELETE FROM user_badges
        WHERE id IN (
          SELECT ub.id
          FROM user_badges ub
          LEFT JOIN (
            #{badge.query}
          ) q ON q.user_id = ub.user_id
          #{post_clause}
          WHERE ub.badge_id = :id AND q.user_id IS NULL
        )
    SQL

    if badge.auto_revoke && full_backfill
      DB.exec(
        sql,
        id: badge.id,
        post_ids: [-1],
        user_ids: [-2],
        backfill: true,
        multiple_grant: true, # cheat here, cause we only run on backfill and are deleting
      )
    end

    sql = <<~SQL
      WITH w as (
        INSERT INTO user_badges(badge_id, user_id, granted_at, granted_by_id, created_at, post_id)
        SELECT :id, q.user_id, q.granted_at, -1, current_timestamp, #{post_id_field}
          FROM (
                 #{badge.query}
               ) q
     LEFT JOIN user_badges ub ON ub.badge_id = :id AND ub.user_id = q.user_id
        #{post_clause}
        /*where*/
        ON CONFLICT DO NOTHING
        RETURNING id, user_id, granted_at
      )
      SELECT w.*, username, locale, (u.admin OR u.moderator) AS staff, uo.skip_new_user_tips
        FROM w
        JOIN users u on u.id = w.user_id
        JOIN user_options uo ON uo.user_id = w.user_id
    SQL

    builder = DB.build(sql)
    builder.where("ub.badge_id IS NULL AND q.user_id > 0")

    if (post_ids || user_ids) && !badge.query.include?(":backfill")
      Rails.logger.warn "Your triggered badge query for #{badge.name} does not include the :backfill param, skipping!"
      return
    end

    if post_ids && !badge.query.include?(":post_ids")
      Rails.logger.warn "Your triggered badge query for #{badge.name} does not include the :post_ids param, skipping!"
      return
    end

    if user_ids && !badge.query.include?(":user_ids")
      Rails.logger.warn "Your triggered badge query for #{badge.name} does not include the :user_ids param, skipping!"
      return
    end

    builder
      .query(
        id: badge.id,
        multiple_grant: badge.multiple_grant,
        backfill: full_backfill,
        post_ids: post_ids || [-2],
        user_ids: user_ids || [-2],
      )
      .each do |row|
        next if suppress_notification?(badge, row.granted_at, row.skip_new_user_tips)
        next if row.staff && badge.awarded_for_trust_level?

        notification = send_notification(row.user_id, row.username, row.locale, badge)
        UserBadge.trigger_user_badge_granted_event(badge.id, row.user_id)

        DB.exec(
          "UPDATE user_badges SET notification_id = :notification_id WHERE id = :id",
          notification_id: notification.id,
          id: row.id,
        )
      end

    badge.reset_grant_count!
  rescue => e
    raise GrantError, "Failed to backfill '#{badge.name}' badge: #{opts}. Reason: #{e.message}"
  end

  def self.revoke_ungranted_titles!
    DB.exec <<~SQL
      UPDATE users u
      SET title = ''
      FROM user_profiles up
      WHERE u.title IS NOT NULL
        AND u.title <> ''
        AND up.user_id = u.id
        AND up.granted_title_badge_id IS NOT NULL
        AND NOT EXISTS(
          SELECT 1
          FROM badges b
                 JOIN user_badges ub ON ub.user_id = u.id AND ub.badge_id = b.id
          WHERE b.id = up.granted_title_badge_id
            AND b.allow_title
            AND b.enabled
        )
    SQL

    DB.exec <<~SQL
      UPDATE user_profiles up
      SET granted_title_badge_id = NULL
      FROM users u
      WHERE up.user_id = u.id
        AND (u.title IS NULL OR u.title = '')
        AND up.granted_title_badge_id IS NOT NULL
    SQL
  end

  def self.notification_locale(locale)
    use_default_locale = !SiteSetting.allow_user_locale || locale.blank?
    use_default_locale ? SiteSetting.default_locale : locale
  end

  def self.send_notification(user_id, username, locale, badge)
    I18n.with_locale(notification_locale(locale)) do
      Notification.create!(
        user_id: user_id,
        notification_type: Notification.types[:granted_badge],
        data: {
          badge_id: badge.id,
          badge_name: badge.display_name,
          badge_slug: badge.slug,
          badge_title: badge.allow_title,
          username: username,
        }.to_json,
      )
    end
  end

  def self.suppress_notification?(badge, granted_at, skip_new_user_tips)
    is_old_bronze_badge = badge.badge_type_id == BadgeType::Bronze && granted_at < 2.days.ago
    skip_beginner_badge = skip_new_user_tips && badge.for_beginners?

    is_old_bronze_badge || skip_beginner_badge
  end
end

```

Response:
# frozen_string_literal: true

RSpec.describe BadgeGranter do
  fab!(:badge)
  fab!(:user)

  before { BadgeGranter.enable_queue }

  after do
    BadgeGranter.disable_queue
    BadgeGranter.clear_queue!
  end

  describe "revoke_titles" do
    let(:user) { Fabricate(:user) }
    let(:badge) { Fabricate(:badge, allow_title: true) }

    it "revokes title when badge is not allowed as title" do
      BadgeGranter.grant(badge, user)
      user.update!(title: badge.name)

      BadgeGranter.revoke_ungranted_titles!
      user.reload
      expect(user.title).to eq(badge.name)
      expect(user.user_profile.granted_title_badge_id).to eq(badge.id)

      badge.update_column(:allow_title, false)
      BadgeGranter.revoke_ungranted_titles!
      user.reload
      expect(user.title).to be_blank
      expect(user.user_profile.granted_title_badge_id).to be_nil
    end

    it "revokes title when badge is disabled" do
      BadgeGranter.grant(badge, user)
      user.update!(title: badge.name)

      BadgeGranter.revoke_ungranted_titles!
      user.reload
      expect(user.title).to eq(badge.name)
      expect(user.user_profile.granted_title_badge_id).to eq(badge.id)

      badge.update_column(:enabled, false)
      BadgeGranter.revoke_ungranted_titles!
      user.reload
      expect(user.title).to be_blank
      expect(user.user_profile.granted_title_badge_id).to be_nil
    end

    it "revokes title when user badge is revoked" do
      BadgeGranter.grant(badge, user)
      user.update!(title: badge.name)

      BadgeGranter.revoke_ungranted_titles!
      user.reload
      expect(user.title).to eq(badge.name)
      expect(user.user_profile.granted_title_badge_id).to eq(badge.id)

      BadgeGranter.revoke(user.user_badges.first)
      BadgeGranter.revoke_ungranted_titles!
      user.reload
      expect(user.title).to be_blank
      expect(user.user_profile.granted_title_badge_id).to be_nil
    end

    it "does not revoke custom title" do
      user.title = "CEO"
      user.save!

      BadgeGranter.revoke_ungranted_titles!

      user.reload
      expect(user.title).to eq("CEO")
    end

    it "does not revoke localized title" do
      badge = Badge.find(Badge::Regular)
      badge_name = nil
      BadgeGranter.grant(badge, user)

      I18n.with_locale(:de) do
        badge_name = badge.display_name
        user.update!(title: badge_name)
      end

      user.reload
      expect(user.title).to eq(badge_name)
      expect(user.user_profile.granted_title_badge_id).to eq(badge.id)

      BadgeGranter.revoke_ungranted_titles!
      user.reload
      expect(user.title).to eq(badge_name)
      expect(user.user_profile.granted_title_badge_id).to eq(badge.id)
    end
  end

  describe "preview" do
    it "can correctly preview" do
      Fabricate(:user, email: "sam@gmail.com")
      result =
        BadgeGranter.preview(
          'select u.id user_id, null post_id, u.created_at granted_at from users u
                                     join user_emails ue on ue.user_id = u.id AND ue.primary
                                     where ue.email like \'%gmail.com\'',
          explain: true,
        )

      expect(result[:grant_count]).to eq(1)
      expect(result[:query_plan]).to be_present
    end

    it "with badges containing trailing comments do not break generated SQL" do
      query = Badge.find(1).query + "\n-- a comment"
      expect(BadgeGranter.preview(query)[:errors]).to be_nil
    end
  end

  describe "backfill" do
    it "has no broken badge queries" do
      Badge.all.each { |b| BadgeGranter.backfill(b) }
    end

    it "can backfill the welcome badge" do
      post = Fabricate(:post)
      user2 = Fabricate(:user)
      PostActionCreator.like(user2, post)

      UserBadge.destroy_all
      BadgeGranter.backfill(Badge.find(Badge::Welcome))
      BadgeGranter.backfill(Badge.find(Badge::FirstLike))

      b = UserBadge.find_by(user_id: post.user_id)
      expect(b.post_id).to eq(post.id)
      b.badge_id = Badge::Welcome

      b = UserBadge.find_by(user_id: user2.id)
      expect(b.post_id).to eq(post.id)
      b.badge_id = Badge::FirstLike
    end

    it "should grant missing badges" do
      nice_topic = Badge.find(Badge::NiceTopic)
      good_topic = Badge.find(Badge::GoodTopic)

      post = Fabricate(:post, like_count: 30)

      2.times do
        BadgeGranter.backfill(nice_topic, post_ids: [post.id])
        BadgeGranter.backfill(good_topic)
      end

      # TODO add welcome
      expect(post.user.user_badges.pluck(:badge_id)).to contain_exactly(
        nice_topic.id,
        good_topic.id,
      )
      expect(post.user.notifications.count).to eq(2)

      data = post.user.notifications.last.data_hash
      expect(data["badge_id"]).to eq(good_topic.id)
      expect(data["badge_slug"]).to eq(good_topic.slug)
      expect(data["username"]).to eq(post.user.username)

      expect(nice_topic.grant_count).to eq(1)
      expect(good_topic.grant_count).to eq(1)
    end

    it "should grant badges in the user locale" do
      SiteSetting.allow_user_locale = true

      nice_topic = Badge.find(Badge::NiceTopic)
      name_english = nice_topic.name

      user = Fabricate(:user, locale: "fr")
      post = Fabricate(:post, like_count: 10, user: user)

      BadgeGranter.backfill(nice_topic)

      notification_badge_name = JSON.parse(post.user.notifications.first.data)["badge_name"]

      expect(notification_badge_name).not_to eq(name_english)
    end

    it "with badges containing trailing comments do not break generated SQL" do
      badge = Fabricate(:badge)
      badge.query = Badge.find(1).query + "\n-- a comment"
      expect { BadgeGranter.backfill(badge) }.not_to raise_error
    end

    it 'does not notify about badges "for beginners" when user skipped new user tips' do
      user.user_option.update!(skip_new_user_tips: true)
      post = Fabricate(:post)
      PostActionCreator.like(user, post)

      expect { BadgeGranter.backfill(Badge.find(Badge::FirstLike)) }.to_not change {
        Notification.where(user_id: user.id).count
      }
    end

    it "does not grant sharing badges to deleted users" do
      post = Fabricate(:post)
      incoming_links = Fabricate.times(25, :incoming_link, post: post, user: user)
      user_id = user.id
      user.destroy!

      nice_share = Badge.find(Badge::NiceShare)
      first_share = Badge.find(Badge::FirstShare)

      BadgeGranter.backfill(nice_share)
      BadgeGranter.backfill(first_share)

      expect(UserBadge.where(user_id: user_id).count).to eq(0)
    end
  end

  describe "grant" do
    it "allows overriding of granted_at does not notify old bronze" do
      freeze_time
      badge = Badge.create!(name: "a badge", badge_type_id: BadgeType::Bronze)
      user_badge = BadgeGranter.grant(badge, user, created_at: 1.year.ago)

      expect(user_badge.granted_at).to eq_time(1.year.ago)
      expect(Notification.where(user_id: user.id).count).to eq(0)
    end

    it "handles deleted badge" do
      freeze_time
      user_badge = BadgeGranter.grant(nil, user, created_at: 1.year.ago)
      expect(user_badge).to eq(nil)
    end

    it "doesn't grant disabled badges" do
      freeze_time
      badge = Fabricate(:badge, badge_type_id: BadgeType::Bronze, enabled: false)

      user_badge = BadgeGranter.grant(badge, user, created_at: 1.year.ago)
      expect(user_badge).to eq(nil)
    end

    it "doesn't notify about badges 'for beginners' when user skipped new user tips" do
      freeze_time
      UserBadge.destroy_all
      user.user_option.update!(skip_new_user_tips: true)
      badge = Fabricate(:badge, badge_grouping_id: BadgeGrouping::GettingStarted)

      expect { BadgeGranter.grant(badge, user) }.to_not change {
        Notification.where(user_id: user.id).count
      }
    end

    it "notifies about the New User of the Month badge when user skipped new user tips" do
      freeze_time
      user.user_option.update!(skip_new_user_tips: true)
      badge = Badge.find(Badge::NewUserOfTheMonth)

      expect { BadgeGranter.grant(badge, user) }.to change {
        Notification.where(user_id: user.id).count
      }
    end

    it "grants multiple badges" do
      badge = Fabricate(:badge, multiple_grant: true)
      user_badge = BadgeGranter.grant(badge, user)
      user_badge = BadgeGranter.grant(badge, user)
      expect(user_badge).to be_present

      expect(UserBadge.where(user_id: user.id).count).to eq(2)
    end

    it "sets granted_at" do
      day_ago = freeze_time 1.day.ago
      user_badge = BadgeGranter.grant(badge, user)

      expect(user_badge.granted_at).to eq_time(day_ago)
    end

    it "sets granted_by if the option is present" do
      admin = Fabricate(:admin)
      StaffActionLogger.any_instance.expects(:log_badge_grant).once
      user_badge = BadgeGranter.grant(badge, user, granted_by: admin)
      expect(user_badge.granted_by).to eq(admin)
    end

    it "defaults granted_by to the system user" do
      StaffActionLogger.any_instance.expects(:log_badge_grant).never
      user_badge = BadgeGranter.grant(badge, user)
      expect(user_badge.granted_by_id).to eq(Discourse.system_user.id)
    end

    it "does not allow a regular user to grant badges" do
      user_badge = BadgeGranter.grant(badge, user, granted_by: Fabricate(:user))
      expect(user_badge).not_to be_present
    end

    it "increments grant_count on the badge and creates a notification" do
      BadgeGranter.grant(badge, user)
      expect(badge.reload.grant_count).to eq(1)
      expect(
        user.notifications.find_by(notification_type: Notification.types[:granted_badge]).data_hash[
          "badge_id"
        ],
      ).to eq(badge.id)
    end

    it "does not fail when user is missing" do
      BadgeGranter.grant(badge, nil)
      expect(badge.reload.grant_count).to eq(0)
    end
  end

  describe "revoke" do
    fab!(:admin)
    let!(:user_badge) { BadgeGranter.grant(badge, user) }

    it "revokes the badge and does necessary cleanup" do
      user.title = badge.name
      user.save!
      expect(badge.reload.grant_count).to eq(1)
      StaffActionLogger.any_instance.expects(:log_badge_revoke).with(user_badge)
      BadgeGranter.revoke(user_badge, revoked_by: admin)
      expect(UserBadge.find_by(user: user, badge: badge)).not_to be_present
      expect(badge.reload.grant_count).to eq(0)
      expect(
        user.notifications.where(notification_type: Notification.types[:granted_badge]),
      ).to be_empty
      expect(user.reload.title).to eq(nil)
    end

    context "when the badge name is customized, and the customized name is the same as the user title" do
      let(:customized_badge_name) { "Merit Badge" }

      before do
        TranslationOverride.upsert!(I18n.locale, Badge.i18n_key(badge.name), customized_badge_name)
      end

      it "revokes the badge and title and does necessary cleanup" do
        user.title = customized_badge_name
        user.save!
        expect(badge.reload.grant_count).to eq(1)
        StaffActionLogger.any_instance.expects(:log_badge_revoke).with(user_badge)
        StaffActionLogger
          .any_instance
          .expects(:log_title_revoke)
          .with(
            user,
            revoke_reason: "user title was same as revoked badge name or custom badge name",
            previous_value: user_badge.user.title,
          )
        BadgeGranter.revoke(user_badge, revoked_by: admin)
        expect(UserBadge.find_by(user: user, badge: badge)).not_to be_present
        expect(badge.reload.grant_count).to eq(0)
        expect(
          user.notifications.where(notification_type: Notification.types[:granted_badge]),
        ).to be_empty
        expect(user.reload.title).to eq(nil)
      end

      after { TranslationOverride.revert!(I18n.locale, Badge.i18n_key(badge.name)) }
    end
  end

  describe "revoke_all" do
    it "deletes every user_badge record associated with that badge" do
      described_class.grant(badge, user)
      described_class.revoke_all(badge)

      expect(UserBadge.exists?(badge: badge, user: user)).to eq(false)
    end

    it "removes titles" do
      another_title = "another title"
      described_class.grant(badge, user)
      user.update!(title: badge.name)
      user2 = Fabricate(:user, title: another_title)

      described_class.revoke_all(badge)

      expect(user.reload.title).to be_nil
      expect(user2.reload.title).to eq(another_title)
    end

    it "removes custom badge titles" do
      custom_badge_title = "this is a badge title"
      TranslationOverride.create!(
        translation_key: badge.translation_key,
        value: custom_badge_title,
        locale: "en",
      )
      described_class.grant(badge, user)
      user.update!(title: custom_badge_title)

      described_class.revoke_all(badge)

      expect(user.reload.title).to be_nil
    end
  end

  describe "update_badges" do
    fab!(:user)
    fab!(:liker) { Fabricate(:user) }

    it "grants autobiographer" do
      user.user_profile.bio_raw = "THIS IS MY bio it a long bio I like my bio"
      user.uploaded_avatar_id = 10
      user.user_profile.save
      user.save

      BadgeGranter.process_queue!
      expect(UserBadge.where(user_id: user.id, badge_id: Badge::Autobiographer).count).to eq(1)
    end

    it "grants read guidelines" do
      user.user_stat.read_faq = Time.now
      user.user_stat.save

      BadgeGranter.process_queue!
      expect(UserBadge.where(user_id: user.id, badge_id: Badge::ReadGuidelines).count).to eq(1)
    end

    it "grants first link" do
      post = create_post
      post2 = create_post(raw: "#{Discourse.base_url}/t/slug/#{post.topic_id}")

      BadgeGranter.process_queue!
      expect(UserBadge.where(user_id: post2.user.id, badge_id: Badge::FirstLink).count).to eq(1)
    end

    it "grants first edit" do
      SiteSetting.editing_grace_period = 0
      post = create_post
      user = post.user

      expect(UserBadge.where(user_id: user.id, badge_id: Badge::Editor).count).to eq(0)

      PostRevisor.new(post).revise!(user, raw: "This is my new test 1235 123")
      BadgeGranter.process_queue!

      expect(UserBadge.where(user_id: user.id, badge_id: Badge::Editor).count).to eq(1)
    end

    it "grants and revokes trust level badges" do
      user.change_trust_level!(TrustLevel[4])
      BadgeGranter.process_queue!
      expect(UserBadge.where(user_id: user.id, badge_id: Badge.trust_level_badge_ids).count).to eq(
        4,
      )

      user.change_trust_level!(TrustLevel[1])
      BadgeGranter.backfill(Badge.find(1))
      BadgeGranter.backfill(Badge.find(2))
      expect(UserBadge.where(user_id: user.id, badge_id: 1).first).not_to eq(nil)
      expect(UserBadge.where(user_id: user.id, badge_id: 2).first).to eq(nil)
    end

    it "grants system like badges" do
      post = create_post(user: user)
      # Welcome badge
      action = PostActionCreator.like(liker, post).post_action
      BadgeGranter.process_queue!
      expect(UserBadge.find_by(user_id: user.id, badge_id: 5)).not_to eq(nil)

      post = create_post(topic: post.topic, user: user)
      action = PostActionCreator.like(liker, post).post_action

      # Nice post badge
      post.update like_count: 10

      BadgeGranter.queue_badge_grant(Badge::Trigger::PostAction, post_action: action)
      BadgeGranter.process_queue!

      expect(UserBadge.find_by(user_id: user.id, badge_id: Badge::NicePost)).not_to eq(nil)
      expect(UserBadge.where(user_id: user.id, badge_id: Badge::NicePost).count).to eq(1)

      # Good post badge
      post.update like_count: 25
      BadgeGranter.queue_badge_grant(Badge::Trigger::PostAction, post_action: action)
      BadgeGranter.process_queue!
      expect(UserBadge.find_by(user_id: user.id, badge_id: Badge::GoodPost)).not_to eq(nil)

      # Great post badge
      post.update like_count: 50
      BadgeGranter.queue_badge_grant(Badge::Trigger::PostAction, post_action: action)
      BadgeGranter.process_queue!
      expect(UserBadge.find_by(user_id: user.id, badge_id: Badge::GreatPost)).not_to eq(nil)

      # Revoke badges on unlike
      post.update like_count: 49
      BadgeGranter.backfill(Badge.find(Badge::GreatPost))
      expect(UserBadge.find_by(user_id: user.id, badge_id: Badge::GreatPost)).to eq(nil)
    end

    it "triggers the 'user_badge_granted' DiscourseEvent per badge when badges are backfilled" do
      post = create_post(user: user)
      action = PostActionCreator.like(liker, post).post_action

      events = DiscourseEvent.track_events(:user_badge_granted) { BadgeGranter.process_queue! }

      expect(events.length).to eq(2)
      expect(events[0][:params]).to eq([Badge::FirstLike, liker.id])
      expect(events[1][:params]).to eq([Badge::Welcome, user.id])
    end
  end

  describe "notification locales" do
    it "is using default locales when user locales are not set" do
      SiteSetting.allow_user_locale = true
      expect(BadgeGranter.notification_locale("")).to eq(SiteSetting.default_locale)
    end

    it "is using default locales when user locales are set but is not allowed" do
      SiteSetting.allow_user_locale = false
      expect(BadgeGranter.notification_locale("pl_PL")).to eq(SiteSetting.default_locale)
    end

    it "is using user locales when set and allowed" do
      SiteSetting.allow_user_locale = true
      expect(BadgeGranter.notification_locale("pl_PL")).to eq("pl_PL")
    end
  end

  describe ".mass_grant" do
    it "raises an error if the count argument is less than 1" do
      expect do BadgeGranter.mass_grant(badge, user, count: 0) end.to raise_error(
        ArgumentError,
        "count can't be less than 1",
      )
    end

    it "grants the badge to the user as many times as the count argument" do
      BadgeGranter.mass_grant(badge, user, count: 10)
      sequence = UserBadge.where(badge: badge, user: user).pluck(:seq).sort
      expect(sequence).to eq((0...10).to_a)

      BadgeGranter.mass_grant(badge, user, count: 10)
      sequence = UserBadge.where(badge: badge, user: user).pluck(:seq).sort
      expect(sequence).to eq((0...20).to_a)
    end
  end

  describe ".enqueue_mass_grant_for_users" do
    before { Jobs.run_immediately! }

    it "returns a list of the entries that could not be matched to any users" do
      results =
        BadgeGranter.enqueue_mass_grant_for_users(
          badge,
          emails: ["fakeemail@discourse.invalid", user.email],
          usernames: [user.username, "fakeusername"],
        )
      expect(results[:unmatched_entries]).to contain_exactly(
        "fakeemail@discourse.invalid",
        "fakeusername",
      )
      expect(results[:matched_users_count]).to eq(1)
      expect(results[:unmatched_entries_count]).to eq(2)
    end

    context "when ensure_users_have_badge_once is true" do
      it "ensures each user has the badge at least once and does not grant the badge multiple times to one user" do
        BadgeGranter.grant(badge, user)
        user_without_badge = Fabricate(:user)

        Notification.destroy_all
        results =
          BadgeGranter.enqueue_mass_grant_for_users(
            badge,
            usernames: [
              user.username,
              user.username,
              user_without_badge.username,
              user_without_badge.username,
            ],
            ensure_users_have_badge_once: true,
          )
        expect(results[:unmatched_entries]).to eq([])
        expect(results[:matched_users_count]).to eq(2)
        expect(results[:unmatched_entries_count]).to eq(0)

        sequence = UserBadge.where(user: user, badge: badge).pluck(:seq)
        expect(sequence).to contain_exactly(0)
        # no new badge/notification because user already had the badge
        # before enqueue_mass_grant_for_users was called
        expect(user.reload.notifications.size).to eq(0)

        sequence = UserBadge.where(user: user_without_badge, badge: badge)
        expect(sequence.pluck(:seq)).to contain_exactly(0)
        notifications = user_without_badge.reload.notifications
        expect(notifications.size).to eq(1)
        expect(sequence.first.notification_id).to eq(notifications.first.id)
        expect(notifications.first.notification_type).to eq(Notification.types[:granted_badge])
      end
    end

    context "when ensure_users_have_badge_once is false" do
      it "grants the badge to the users as many times as they appear in the emails and usernames arguments" do
        badge.update!(multiple_grant: true)
        user_without_badge = Fabricate(:user)
        user_with_badge = Fabricate(:user).tap { |u| BadgeGranter.grant(badge, u) }

        Notification.destroy_all
        emails = [user_with_badge.email.titlecase, user_without_badge.email.titlecase] * 20
        usernames = [user_with_badge.username.titlecase, user_without_badge.username.titlecase] * 20

        results =
          BadgeGranter.enqueue_mass_grant_for_users(
            badge,
            emails: emails,
            usernames: usernames,
            ensure_users_have_badge_once: false,
          )
        expect(results[:unmatched_entries]).to eq([])
        expect(results[:matched_users_count]).to eq(2)
        expect(results[:unmatched_entries_count]).to eq(0)

        sequence = UserBadge.where(user: user_with_badge, badge: badge).pluck(:seq)
        expect(sequence.size).to eq(40 + 1)
        expect(sequence.sort).to eq((0...(40 + 1)).to_a)
        sequence = UserBadge.where(user: user_without_badge, badge: badge).pluck(:seq)
        expect(sequence.size).to eq(40)
        expect(sequence.sort).to eq((0...40).to_a)

        # each user gets 1 notification no matter how many times
        # they're repeated in the file.
        [user_without_badge, user_with_badge].each do |u|
          notifications = u.reload.notifications
          expect(notifications.size).to eq(1)
          expect(notifications.map(&:notification_type).uniq).to contain_exactly(
            Notification.types[:granted_badge],
          )
        end
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

class TopicSummarization
  def initialize(strategy)
    @strategy = strategy
  end

  def summarize(topic, user, opts = {}, &on_partial_blk)
    existing_summary = SummarySection.find_by(target: topic, meta_section_id: nil)

    # Existing summary shouldn't be nil in this scenario because the controller checks its existence.
    return if !user && !existing_summary

    targets_data = summary_targets(topic).pluck(:post_number, :raw, :username)

    current_topic_sha = build_sha(targets_data.map(&:first))
    can_summarize = Summarization::Base.can_request_summary_for?(user)

    if use_cached?(existing_summary, can_summarize, current_topic_sha, !!opts[:skip_age_check])
      # It's important that we signal a cached summary is outdated
      existing_summary.mark_as_outdated if new_targets?(existing_summary, current_topic_sha)

      return existing_summary
    end

    delete_cached_summaries_of(topic) if existing_summary

    content = {
      resource_path: "#{Discourse.base_path}/t/-/#{topic.id}",
      content_title: topic.title,
      contents: [],
    }

    targets_data.map do |(pn, raw, username)|
      content[:contents] << { poster: username, id: pn, text: raw }
    end

    summarization_result = strategy.summarize(content, user, &on_partial_blk)

    cache_summary(summarization_result, targets_data.map(&:first), topic)
  end

  def summary_targets(topic)
    topic.has_summary? ? best_replies(topic) : pick_selection(topic)
  end

  private

  attr_reader :strategy

  def best_replies(topic)
    Post
      .summary(topic.id)
      .where("post_type = ?", Post.types[:regular])
      .where("NOT hidden")
      .joins(:user)
      .order(:post_number)
  end

  def pick_selection(topic)
    posts =
      Post
        .where(topic_id: topic.id)
        .where("post_type = ?", Post.types[:regular])
        .where("NOT hidden")
        .order(:post_number)

    post_numbers = posts.limit(5).pluck(:post_number)
    post_numbers += posts.reorder("posts.score desc").limit(50).pluck(:post_number)
    post_numbers += posts.reorder("post_number desc").limit(5).pluck(:post_number)

    Post
      .where(topic_id: topic.id)
      .joins(:user)
      .where("post_number in (?)", post_numbers)
      .order(:post_number)
  end

  def delete_cached_summaries_of(topic)
    SummarySection.where(target: topic).destroy_all
  end

  # For users without permissions to generate a summary or fresh summaries, we return what we have cached.
  def use_cached?(existing_summary, can_summarize, current_sha, skip_age_check)
    existing_summary &&
      !(
        can_summarize && new_targets?(existing_summary, current_sha) &&
          (skip_age_check || existing_summary.created_at < 1.hour.ago)
      )
  end

  def new_targets?(summary, current_sha)
    summary.original_content_sha != current_sha
  end

  def cache_summary(result, post_numbers, topic)
    main_summary =
      SummarySection.create!(
        target: topic,
        algorithm: strategy.model,
        content_range: (post_numbers.first..post_numbers.last),
        summarized_text: result[:summary],
        original_content_sha: build_sha(post_numbers),
      )

    result[:chunks].each do |chunk|
      SummarySection.create!(
        target: topic,
        algorithm: strategy.model,
        content_range: chunk[:ids].min..chunk[:ids].max,
        summarized_text: chunk[:summary],
        original_content_sha: build_sha(chunk[:ids]),
        meta_section_id: main_summary.id,
      )
    end

    main_summary
  end

  def build_sha(ids)
    Digest::SHA256.hexdigest(ids.join)
  end
end

```

Response:
# frozen_string_literal: true

describe TopicSummarization do
  fab!(:user) { Fabricate(:admin) }
  fab!(:topic) { Fabricate(:topic, highest_post_number: 2) }
  fab!(:post_1) { Fabricate(:post, topic: topic, post_number: 1) }
  fab!(:post_2) { Fabricate(:post, topic: topic, post_number: 2) }

  shared_examples "includes only public-visible topics" do
    subject { described_class.new(DummyCustomSummarization.new({})) }

    it "only includes visible posts" do
      topic.first_post.update!(hidden: true)

      posts = subject.summary_targets(topic)

      expect(posts.none?(&:hidden?)).to eq(true)
    end

    it "doesn't include posts without users" do
      topic.first_post.user.destroy!

      posts = subject.summary_targets(topic)

      expect(posts.detect { |p| p.id == topic.first_post.id }).to be_nil
    end

    it "doesn't include deleted posts" do
      topic.first_post.update!(user_id: nil)

      posts = subject.summary_targets(topic)

      expect(posts.detect { |p| p.id == topic.first_post.id }).to be_nil
    end
  end

  describe "#summary_targets" do
    context "when the topic has a best replies summary" do
      before { topic.has_summary = true }

      it_behaves_like "includes only public-visible topics"
    end

    context "when the topic doesn't have a best replies summary" do
      before { topic.has_summary = false }

      it_behaves_like "includes only public-visible topics"
    end
  end

  describe "#summarize" do
    subject(:summarization) { described_class.new(strategy) }

    let(:strategy) { DummyCustomSummarization.new(summary) }

    def assert_summary_is_cached(topic, summary_response)
      cached_summary = SummarySection.find_by(target: topic, meta_section_id: nil)

      expect(cached_summary.content_range).to cover(*topic.posts.map(&:post_number))
      expect(cached_summary.summarized_text).to eq(summary_response[:summary])
      expect(cached_summary.original_content_sha).to be_present
      expect(cached_summary.algorithm).to eq(strategy.model)
    end

    def assert_chunk_is_cached(topic, chunk_response)
      cached_chunk =
        SummarySection
          .where.not(meta_section_id: nil)
          .find_by(
            target: topic,
            content_range: (chunk_response[:ids].min..chunk_response[:ids].max),
          )

      expect(cached_chunk.summarized_text).to eq(chunk_response[:summary])
      expect(cached_chunk.original_content_sha).to be_present
      expect(cached_chunk.algorithm).to eq(strategy.model)
    end

    context "when the content was summarized in a single chunk" do
      let(:summary) { { summary: "This is the final summary", chunks: [] } }

      it "caches the summary" do
        section = summarization.summarize(topic, user)

        expect(section.summarized_text).to eq(summary[:summary])

        assert_summary_is_cached(topic, summary)
      end

      it "returns the cached version in subsequent calls" do
        summarization.summarize(topic, user)

        cached_summary_text = "This is a cached summary"
        cached_summary =
          SummarySection.find_by(target: topic, meta_section_id: nil).update!(
            summarized_text: cached_summary_text,
            updated_at: 24.hours.ago,
          )

        section = summarization.summarize(topic, user)
        expect(section.summarized_text).to eq(cached_summary_text)
      end
    end

    context "when the content was summarized in multiple chunks" do
      let(:summary) do
        {
          summary: "This is the final summary",
          chunks: [
            { ids: [topic.first_post.post_number], summary: "this is the first chunk" },
            { ids: [post_1.post_number, post_2.post_number], summary: "this is the second chunk" },
          ],
        }
      end

      it "caches the summary and each chunk" do
        section = summarization.summarize(topic, user)

        expect(section.summarized_text).to eq(summary[:summary])

        assert_summary_is_cached(topic, summary)

        summary[:chunks].each { |c| assert_chunk_is_cached(topic, c) }
      end
    end

    describe "invalidating cached summaries" do
      let(:cached_text) { "This is a cached summary" }
      let(:summarized_text) { "This is the final summary" }
      let(:summary) do
        {
          summary: summarized_text,
          chunks: [
            { ids: [topic.first_post.post_number], summary: "this is the first chunk" },
            { ids: [post_1.post_number, post_2.post_number], summary: "this is the second chunk" },
          ],
        }
      end

      def cached_summary
        SummarySection.find_by(target: topic, meta_section_id: nil)
      end

      before do
        summarization.summarize(topic, user)

        cached_summary.update!(summarized_text: cached_text, created_at: 24.hours.ago)
      end

      context "when the user can requests new summaries" do
        context "when there are no new posts" do
          it "returns the cached summary" do
            section = summarization.summarize(topic, user)

            expect(section.summarized_text).to eq(cached_text)
          end
        end

        context "when there are new posts" do
          before { cached_summary.update!(original_content_sha: "outdated_sha") }

          it "returns a new summary" do
            section = summarization.summarize(topic, user)

            expect(section.summarized_text).to eq(summarized_text)
          end

          context "when the cached summary is less than one hour old" do
            before { cached_summary.update!(created_at: 30.minutes.ago) }

            it "returns the cached summary" do
              cached_summary.update!(created_at: 30.minutes.ago)

              section = summarization.summarize(topic, user)

              expect(section.summarized_text).to eq(cached_text)
              expect(section.outdated).to eq(true)
            end

            it "returns a new summary if the skip_age_check flag is passed" do
              section = summarization.summarize(topic, user, skip_age_check: true)

              expect(section.summarized_text).to eq(summarized_text)
            end
          end
        end
      end
    end

    describe "stream partial updates" do
      let(:summary) { { summary: "This is the final summary", chunks: [] } }

      it "receives a blk that is passed to the underlying strategy and called with partial summaries" do
        partial_result = nil

        summarization.summarize(topic, user) { |partial_summary| partial_result = partial_summary }

        expect(partial_result).to eq(summary[:summary])
      end
    end
  end
end