INSTRUCTION
stringlengths
202
35.5k
RESPONSE
stringlengths
75
161k
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class TagFollowingService def initialize(user=nil) @user = user end def create(name) name_normalized = ActsAsTaggableOn::Tag.normalize(name) raise ArgumentError, "Name field null or empty" if name_normalized.blank? ...
# frozen_string_literal: true describe TagFollowingService do before do add_tag("tag1", alice) add_tag("tag2", alice) end describe "#create" do it "Creates new tag with valid name" do name = SecureRandom.uuid expect(alice.followed_tags.find_by(name: name)).to be_nil tag_data = tag_...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class AspectsMembershipService def initialize(user=nil) @user = user end def create(aspect_id, person_id) person = Person.find(person_id) aspect = @user.aspects.where(id: aspect_id).first raise ActiveRecord::Rec...
# frozen_string_literal: true describe AspectsMembershipService do before do @alice_aspect1 = alice.aspects.first @alice_aspect2 = alice.aspects.create(name: "another aspect") @bob_aspect1 = bob.aspects.first end describe "#create" do context "with valid IDs" do it "succeeds" do ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class LikeService def initialize(user=nil) @user = user end def create_for_post(post_id) post = post_service.find!(post_id) user.like!(post) end def create_for_comment(comment_id) comment = comment_service....
# frozen_string_literal: true describe LikeService do let(:post) { alice.post(:status_message, text: "hello", to: alice.aspects.first) } let(:alice_comment) { CommentService.new(alice).create(post.id, "This is a wonderful post") } let(:bobs_comment) { CommentService.new(bob).create(post.id, "My post was better t...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class StatusMessageCreationService include Rails.application.routes.url_helpers def initialize(user) @user = user end def create(params) validate_content(params) build_status_message(params).tap do |status_messa...
# frozen_string_literal: true describe StatusMessageCreationService do describe "#create" do let(:aspect) { alice.aspects.first } let(:text) { "I'm writing tests" } let(:params) { { status_message: {text: text}, aspect_ids: [aspect.id.to_s] } } it "returns the cre...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class PostService def initialize(user=nil) @user = user end def find(id) if user user.find_visible_shareable_by_id(Post, id) else Post.find_by_id_and_public(id, true) end end def find!(id_or_gui...
# frozen_string_literal: true describe PostService do let(:post) { alice.post(:status_message, text: "ohai", to: alice.aspects.first) } let(:public) { alice.post(:status_message, text: "hey", public: true) } describe "#find" do context "with user" do it "returns the post, if it is the users post" do ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class NotificationService NOTIFICATION_TYPES = { Comment => [Notifications::MentionedInComment, Notifications::CommentOnPost, Notifications::AlsoCommented], Like => [Notifications::Liked, Notifications::LikedC...
# frozen_string_literal: true describe NotificationService do describe "notification interrelation" do context "with mention in comment" do let(:status_message) { FactoryBot.create(:status_message, public: true, author: alice.person).tap {|status_message| eve.comment!(status_message, "wha...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Encapsulates logic of processing diaspora:// links class DiasporaLinkService attr_reader :type, :author, :guid def initialize(link) @link = link.dup parse end def find_or_fetch_entity if type && guid enti...
# frozen_string_literal: true describe DiasporaLinkService do let(:service) { described_class.new(link) } describe "#find_or_fetch_entity" do context "when entity is known" do let(:post) { FactoryBot.create(:status_message) } let(:link) { "diaspora://#{post.author.diaspora_handle}/post/#{post.guid...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class PollParticipationService def initialize(user) @user = user end def vote(post_id, answer_id) answer = PollAnswer.find(answer_id) @user.participate_in_poll!(target(post_id), answer) if target(post_id) end p...
# frozen_string_literal: true describe PollParticipationService do let(:poll_post) { FactoryBot.create(:status_message_with_poll, public: true) } let(:poll_answer) { poll_post.poll.poll_answers.first } describe "voting on poll" do it "succeeds" do expect(poll_service.vote(poll_post.id, poll_answer.id)...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ReshareService def initialize(user=nil) @user = user end def create(post_id) post = post_service.find!(post_id) post = post.absolute_root if post.is_a? Reshare user.reshare!(post) end def find_for_pos...
# frozen_string_literal: true describe ReshareService do let(:post) { alice.post(:status_message, text: "hello", public: true) } describe "#create" do it "doesn't create a reshare of my own post" do expect { ReshareService.new(alice).create(post.id) }.to raise_error RuntimeError end ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class PhotoService def initialize(user=nil, deny_raw_files=true) @user = user @deny_raw_files = deny_raw_files end def visible_photo(photo_guid) Photo.owned_or_visible_by_user(@user).where(guid: photo_guid).first ...
# frozen_string_literal: true describe PhotoService do before do alice_eve_spec = alice.aspects.create(name: "eve aspect") alice.share_with(eve.person, alice_eve_spec) alice_bob_spec = alice.aspects.create(name: "bob aspect") alice.share_with(bob.person, alice_bob_spec) @alice_eve_photo = alice.p...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ConversationService def initialize(user=nil) @user = user end def all_for_user(filter={}) conversation_filter = {} unless filter[:only_after].nil? conversation_filter = \ "conversations.created_a...
# frozen_string_literal: true describe ConversationService do before do opts = { subject: "conversation subject", message: {text: "conversation text"}, participant_ids: [bob.person.id] } @conversation = alice.build_conversation(opts) @conversation.created_at = 2.hour...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class CommentService def initialize(user=nil) @user = user end def create(post_id, text) post = post_service.find!(post_id) user.comment!(post, text) end def find_for_post(post_id) post_service.find!(post_i...
# frozen_string_literal: true describe CommentService do let(:post) { alice.post(:status_message, text: "hello", to: alice.aspects.first) } describe "#create" do it "creates a comment on my own post" do comment = CommentService.new(alice).create(post.id, "hi") expect(comment.text).to eq("hi") ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true require 'csv' # NOTE: This is a deprecated service, only kept to not break ongoing imports # on upgrade. See `BulkImportService` for its replacement. class ImportService < BaseService ROWS_PROCESSING_LIMIT = 20_000 def call(imp...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ImportService, type: :service do include RoutingHelper let!(:account) { Fabricate(:account, locked: false) } let!(:bob) { Fabricate(:account, username: 'bob', locked: false) } let!(:eve) { Fabricate(:account, username: 'eve', domain:...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class AuthorizeFollowService < BaseService include Payloadable def call(source_account, target_account, **options) if options[:skip_follow_request] follow_request = FollowRequest.new(account: source_account, target_acco...
# frozen_string_literal: true require 'rails_helper' RSpec.describe AuthorizeFollowService, type: :service do subject { described_class.new } let(:sender) { Fabricate(:account, username: 'alice') } describe 'local' do let(:bob) { Fabricate(:account, username: 'bob') } before do FollowRequest.cr...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class PrecomputeFeedService < BaseService include Redisable def call(account) FeedManager.instance.populate_home(account) ensure redis.del("account:#{account.id}:regeneration") end end ```
# frozen_string_literal: true require 'rails_helper' RSpec.describe PrecomputeFeedService, type: :service do subject { described_class.new } describe 'call' do let(:account) { Fabricate(:account) } it 'fills a user timeline with statuses' do account = Fabricate(:account) status = Fabricate(:...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class PostStatusService < BaseService include Redisable include LanguagesHelper MIN_SCHEDULE_OFFSET = 5.minutes.freeze class UnexpectedMentionsError < StandardError attr_reader :accounts def initialize(message, acco...
# frozen_string_literal: true require 'rails_helper' RSpec.describe PostStatusService, type: :service do subject { described_class.new } it 'creates a new status' do account = Fabricate(:account) text = 'test status update' status = subject.call(account, text: text) expect(status).to be_persist...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class AccountSearchService < BaseService attr_reader :query, :limit, :offset, :options, :account MENTION_ONLY_RE = /\A#{Account::MENTION_RE}\z/i # Min. number of characters to look for non-exact matches MIN_QUERY_LENGTH = 5 ...
# frozen_string_literal: true require 'rails_helper' describe AccountSearchService, type: :service do describe '#call' do context 'with a query to ignore' do it 'returns empty array for missing query' do results = subject.call('', nil, limit: 10) expect(results).to eq [] end ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class SoftwareUpdateCheckService < BaseService def call clean_outdated_updates! return unless SoftwareUpdate.check_enabled? process_update_notices!(fetch_update_notices) end private def clean_outdated_updates! ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe SoftwareUpdateCheckService, type: :service do subject { described_class.new } shared_examples 'when the feature is enabled' do let(:full_update_check_url) { "#{update_check_url}?version=#{Mastodon::Version.to_s.split('+')[0]}" } let(:de...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UnsuspendAccountService < BaseService include Payloadable # Restores a recently-unsuspended account # @param [Account] account Account to restore def call(account) @account = account refresh_remote_account! ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe UnsuspendAccountService, type: :service do shared_context 'with common context' do subject { described_class.new.call(account) } let!(:local_follower) { Fabricate(:user, current_sign_in_at: 1.hour.ago).account } let!(:list) {...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class AfterBlockDomainFromAccountService < BaseService include Payloadable # This service does not create an AccountDomainBlock record, # it's meant to be called after such a record has been created # synchronously, to "clean...
# frozen_string_literal: true require 'rails_helper' RSpec.describe AfterBlockDomainFromAccountService, type: :service do subject { described_class.new } let!(:wolf) { Fabricate(:account, username: 'wolf', domain: 'evil.org', inbox_url: 'https://evil.org/inbox', protocol: :activitypub) } let!(:alice) { Fabrica...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class BlockDomainService < BaseService attr_reader :domain_block def call(domain_block, update = false) @domain_block = domain_block process_domain_block! process_retroactive_updates! if update end private def...
# frozen_string_literal: true require 'rails_helper' RSpec.describe BlockDomainService, type: :service do subject { described_class.new } let!(:bad_account) { Fabricate(:account, username: 'badguy666', domain: 'evil.org') } let!(:bad_status_plain) { Fabricate(:status, account: bad_account, text: 'You suck') } ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class BlockService < BaseService include Payloadable def call(account, target_account) return if account.id == target_account.id UnfollowService.new.call(account, target_account) if account.following?(target_account) ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe BlockService, type: :service do subject { described_class.new } let(:sender) { Fabricate(:account, username: 'alice') } describe 'local' do let(:bob) { Fabricate(:account, username: 'bob') } before do subject.call(sender, bob) ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UnfollowService < BaseService include Payloadable include Redisable include Lockable # Unfollow and notify the remote user # @param [Account] source_account Where to unfollow from # @param [Account] target_account W...
# frozen_string_literal: true require 'rails_helper' RSpec.describe UnfollowService, type: :service do subject { described_class.new } let(:sender) { Fabricate(:account, username: 'alice') } describe 'local' do let(:bob) { Fabricate(:account, username: 'bob') } before do sender.follow!(bob) ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class SuspendAccountService < BaseService include Payloadable # Carry out the suspension of a recently-suspended account # @param [Account] account Account to suspend def call(account) return unless account.suspended? ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe SuspendAccountService, type: :service do shared_examples 'common behavior' do subject { described_class.new.call(account) } let!(:local_follower) { Fabricate(:user, current_sign_in_at: 1.hour.ago).account } let!(:list) { Fabr...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class BulkImportService < BaseService def call(import) @import = import @account = @import.account case @import.type.to_sym when :following import_follows! when :blocking import_blocks! when :mu...
# frozen_string_literal: true require 'rails_helper' RSpec.describe BulkImportService do subject { described_class.new } let(:account) { Fabricate(:account) } let(:import) { Fabricate(:bulk_import, account: account, type: import_type, overwrite: overwrite, state: :in_progress, imported_items: 0, processed_item...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class AfterBlockService < BaseService def call(account, target_account) @account = account @target_account = target_account clear_home_feed! clear_list_feeds! clear_notifications! clear_conversations!...
# frozen_string_literal: true require 'rails_helper' RSpec.describe AfterBlockService, type: :service do subject { described_class.new.call(account, target_account) } let(:account) { Fabricate(:account) } let(:target_account) { Fabricate(:account) } let(:status) { Fabricate(:...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class MuteService < BaseService def call(account, target_account, notifications: nil, duration: 0) return if account.id == target_account.id mute = account.mute!(target_account, notifications: notifications, duration: durat...
# frozen_string_literal: true require 'rails_helper' RSpec.describe MuteService, type: :service do subject { described_class.new.call(account, target_account) } let(:account) { Fabricate(:account) } let(:target_account) { Fabricate(:account) } describe 'home timeline' do let(:status) { Fabricate(:status...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class RemoveFromFollowersService < BaseService include Payloadable def call(source_account, target_accounts) source_account.passive_relationships.where(account_id: target_accounts).find_each do |follow| follow.destroy ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe RemoveFromFollowersService, type: :service do subject { described_class.new } let(:bob) { Fabricate(:account, username: 'bob') } describe 'local' do let(:sender) { Fabricate(:account, username: 'alice') } before do Follow.creat...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class FetchLinkCardService < BaseService include Redisable include Lockable URL_PATTERN = %r{ (#{Twitter::TwitterText::Regex[:valid_url_preceding_chars]}) # $...
# frozen_string_literal: true require 'rails_helper' RSpec.describe FetchLinkCardService, type: :service do subject { described_class.new } let(:html) { '<!doctype html><title>Hello world</title>' } let(:oembed_cache) { nil } before do stub_request(:get, 'http://example.com/html').to_return(headers: { '...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UpdateAccountService < BaseService def call(account, params, raise_error: false) was_locked = account.locked update_method = raise_error ? :update! : :update account.send(update_method, params).tap do |ret| ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe UpdateAccountService, type: :service do subject { described_class.new } describe 'switching form locked to unlocked accounts' do let(:account) { Fabricate(:account, locked: true) } let(:alice) { Fabricate(:account) } let(:bob) ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ReblogService < BaseService include Authorization include Payloadable # Reblog a status and notify its remote author # @param [Account] account Account to reblog from # @param [Status] reblogged_status Status to be re...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ReblogService, type: :service do let(:alice) { Fabricate(:account, username: 'alice') } context 'when creates a reblog with appropriate visibility' do subject { described_class.new } let(:visibility) { :public } let(:reblog_...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ProcessMentionsService < BaseService include Payloadable # Scan status for mentions and fetch remote mentioned users, # and create local mention pointers # @param [Status] status # @param [Boolean] save_records Whethe...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ProcessMentionsService, type: :service do subject { described_class.new } let(:account) { Fabricate(:account, username: 'alice') } context 'when mentions contain blocked accounts' do let(:non_blocked_account) { Fabricate(:account...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class BatchedRemoveStatusService < BaseService include Redisable # Delete multiple statuses and reblogs of them as efficiently as possible # @param [Enumerable<Status>] statuses An array of statuses # @param [Hash] options ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe BatchedRemoveStatusService, type: :service do subject { described_class.new } let!(:alice) { Fabricate(:account) } let!(:bob) { Fabricate(:account, username: 'bob', domain: 'example.com') } let!(:jeff) { Fabricate(:account) } let!(:h...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class FetchRemoteStatusService < BaseService def call(url, prefetched_body: nil, request_id: nil) if prefetched_body.nil? resource_url, resource_options = FetchResourceService.new.call(url) else resource_url ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe FetchRemoteStatusService, type: :service do let(:account) { Fabricate(:account, domain: 'example.org', uri: 'https://example.org/foo') } let(:prefetched_body) { nil } let(:note) do { '@context': 'https://www.w3.org/ns/activitystreams...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class SearchService < BaseService QUOTE_EQUIVALENT_CHARACTERS = /[“”„«»「」『』《》]/ def call(query, account, limit, options = {}) @query = query&.strip&.gsub(QUOTE_EQUIVALENT_CHARACTERS, '"') @account = account @opt...
# frozen_string_literal: true require 'rails_helper' describe SearchService, type: :service do subject { described_class.new } describe '#call' do describe 'with a blank query' do it 'returns empty results without searching' do allow(AccountSearchService).to receive(:new) allow(Tag).to ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class VerifyLinkService < BaseService def call(field) @link_back = ActivityPub::TagManager.instance.url_for(field.account) @url = field.value_for_verification perform_request! return unless link_back_present?...
# frozen_string_literal: true require 'rails_helper' RSpec.describe VerifyLinkService, type: :service do subject { described_class.new } context 'when given a local account' do let(:account) { Fabricate(:account, username: 'alice') } let(:field) { Account::Field.new(account, 'name' => 'Website', 'value...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class FetchResourceService < BaseService include JsonLdHelper ACCEPT_HEADER = 'application/activity+json, application/ld+json; profile="https://www.w3.org/ns/activitystreams", text/html;q=0.1' ACTIVITY_STREAM_LINK_TYPES = ['app...
# frozen_string_literal: true require 'rails_helper' RSpec.describe FetchResourceService, type: :service do describe '#call' do subject { described_class.new.call(url) } let(:url) { 'http://example.com' } context 'with blank url' do let(:url) { '' } it { is_expected.to be_nil } end ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class AppSignUpService < BaseService include RegistrationHelper def call(app, remote_ip, params) @app = app @remote_ip = remote_ip @params = params raise Mastodon::NotPermittedError unless allowed_regist...
# frozen_string_literal: true require 'rails_helper' RSpec.describe AppSignUpService, type: :service do subject { described_class.new } let(:app) { Fabricate(:application, scopes: 'read write') } let(:good_params) { { username: 'alice', password: '12345678', email: 'good@email.com', agreement: true } } let(:...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UnblockDomainService < BaseService attr_accessor :domain_block def call(domain_block) @domain_block = domain_block process_retroactive_updates domain_block.destroy end def process_retroactive_updates sc...
# frozen_string_literal: true require 'rails_helper' describe UnblockDomainService, type: :service do subject { described_class.new } describe 'call' do let!(:independently_suspended) { Fabricate(:account, domain: 'example.com', suspended_at: 1.hour.ago) } let!(:independently_silenced) { Fabricate(:accou...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class PurgeDomainService < BaseService def call(domain) Account.remote.where(domain: domain).reorder(nil).find_each do |account| DeleteAccountService.new.call(account, reserve_username: false, skip_side_effects: true) ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe PurgeDomainService, type: :service do subject { described_class.new } let!(:old_account) { Fabricate(:account, domain: 'obsolete.org') } let!(:old_status_plain) { Fabricate(:status, account: old_account) } let!(:old_status_with_attachment) {...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class RejectFollowService < BaseService include Payloadable def call(source_account, target_account) follow_request = FollowRequest.find_by!(account: source_account, target_account: target_account) follow_request.reject! ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe RejectFollowService, type: :service do subject { described_class.new } let(:sender) { Fabricate(:account, username: 'alice') } describe 'local' do let(:bob) { Fabricate(:account) } before do FollowRequest.create(account: bob, t...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UnallowDomainService < BaseService include DomainControlHelper def call(domain_allow) suspend_accounts!(domain_allow.domain) if limited_federation_mode? domain_allow.destroy end private def suspend_accounts...
# frozen_string_literal: true require 'rails_helper' RSpec.describe UnallowDomainService, type: :service do subject { described_class.new } let!(:bad_account) { Fabricate(:account, username: 'badguy666', domain: 'evil.org') } let!(:bad_status_harassment) { Fabricate(:status, account: bad_account, text: 'You su...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ReportService < BaseService include Payloadable def call(source_account, target_account, options = {}) @source_account = source_account @target_account = target_account @status_ids = options.delete(:status_i...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ReportService, type: :service do subject { described_class.new } let(:source_account) { Fabricate(:account) } let(:target_account) { Fabricate(:account) } context 'with a local account' do it 'has a uri' do report = subject.call(s...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class FavouriteService < BaseService include Authorization include Payloadable # Favourite a status and notify remote user # @param [Account] account # @param [Status] status # @return [Favourite] def call(account, stat...
# frozen_string_literal: true require 'rails_helper' RSpec.describe FavouriteService, type: :service do subject { described_class.new } let(:sender) { Fabricate(:account, username: 'alice') } describe 'local' do let(:bob) { Fabricate(:account) } let(:status) { Fabricate(:status, account: bob) } ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ClearDomainMediaService < BaseService attr_reader :domain_block def call(domain_block) @domain_block = domain_block clear_media! if domain_block.reject_media? end private def clear_media! clear_account_i...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ClearDomainMediaService, type: :service do subject { described_class.new } let!(:bad_account) { Fabricate(:account, username: 'badguy666', domain: 'evil.org') } let!(:bad_status_plain) { Fabricate(:status, account: bad_account, text: 'You suck...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UnblockService < BaseService include Payloadable def call(account, target_account) return unless account.blocking?(target_account) unblock = account.unblock!(target_account) create_notification(unblock) if !tar...
# frozen_string_literal: true require 'rails_helper' RSpec.describe UnblockService, type: :service do subject { described_class.new } let(:sender) { Fabricate(:account, username: 'alice') } describe 'local' do let(:bob) { Fabricate(:account) } before do sender.block!(bob) subject.call(sen...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class NotifyService < BaseService include Redisable NON_EMAIL_TYPES = %i( admin.report admin.sign_up update poll status ).freeze def call(recipient, type, activity) @recipient = recipient @acti...
# frozen_string_literal: true require 'rails_helper' RSpec.describe NotifyService, type: :service do subject { described_class.new.call(recipient, type, activity) } let(:user) { Fabricate(:user) } let(:recipient) { user.account } let(:sender) { Fabricate(:account, domain: 'example.com') } let(:activity) { ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class TranslateStatusService < BaseService CACHE_TTL = 1.day.freeze include ERB::Util include FormattingHelper def call(status, target_language) @status = status @source_texts = source_texts @target_language = ta...
# frozen_string_literal: true require 'rails_helper' RSpec.describe TranslateStatusService, type: :service do subject(:service) { described_class.new } let(:status) { Fabricate(:status, text: text, spoiler_text: spoiler_text, language: 'en', preloadable_poll: poll, media_attachments: media_attachments) } let(:...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class FanOutOnWriteService < BaseService include Redisable # Push a status into home and mentions feeds # @param [Status] status # @param [Hash] options # @option options [Boolean] update # @option options [Array<Integer>...
# frozen_string_literal: true require 'rails_helper' RSpec.describe FanOutOnWriteService, type: :service do subject { described_class.new } let(:last_active_at) { Time.now.utc } let(:status) { Fabricate(:status, account: alice, visibility: visibility, text: 'Hello @bob #hoge') } let!(:alice) { Fabricate(:us...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ResolveURLService < BaseService include JsonLdHelper include Authorization USERNAME_STATUS_RE = %r{/@(?<username>#{Account::USERNAME_RE})/(?<status_id>[0-9]+)\Z} def call(url, on_behalf_of: nil) @url = url...
# frozen_string_literal: true require 'rails_helper' describe ResolveURLService, type: :service do subject { described_class.new } describe '#call' do it 'returns nil when there is no resource url' do url = 'http://example.com/missing-resource' Fabricate(:account, uri: url, domain: 'example.com')...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true require 'zip' class BackupService < BaseService include Payloadable include ContextHelper attr_reader :account, :backup def call(backup) @backup = backup @account = backup.user.account build_archive! end ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe BackupService, type: :service do subject(:service_call) { described_class.new.call(backup) } let!(:user) { Fabricate(:user) } let!(:attachment) { Fabricate(:media_attachment, account: user.account) } let!(:status) { Fab...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class AccountStatusesCleanupService < BaseService # @param [AccountStatusesCleanupPolicy] account_policy # @param [Integer] budget # @return [Integer] def call(account_policy, budget = 50) return 0 unless account_policy.en...
# frozen_string_literal: true require 'rails_helper' describe AccountStatusesCleanupService, type: :service do let(:account) { Fabricate(:account, username: 'alice', domain: nil) } let(:account_policy) { Fabricate(:account_statuses_cleanup_policy, account: account) } let!(:unrelated_status) { Fabri...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class FetchOEmbedService ENDPOINT_CACHE_EXPIRES_IN = 24.hours.freeze URL_REGEX = %r{(=(https?(%3A|:)(//|%2F%2F)))([^&]*)}i attr_reader :url, :options, :format, :endpoint_url def call(url, options = {}) @u...
# frozen_string_literal: true require 'rails_helper' describe FetchOEmbedService, type: :service do subject { described_class.new } before do stub_request(:get, 'https://host.test/provider.json').to_return(status: 404) stub_request(:get, 'https://host.test/provider.xml').to_return(status: 404) stub_r...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UpdateStatusService < BaseService include Redisable include LanguagesHelper class NoChangesSubmittedError < StandardError; end # @param [Status] status # @param [Integer] account_id # @param [Hash] options # @opt...
# frozen_string_literal: true require 'rails_helper' RSpec.describe UpdateStatusService, type: :service do subject { described_class.new } context 'when nothing changes' do let!(:status) { Fabricate(:status, text: 'Foo', language: 'en') } before do allow(ActivityPub::DistributionWorker).to receive...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class BootstrapTimelineService < BaseService def call(source_account) @source_account = source_account autofollow_inviter! notify_staff! end private def autofollow_inviter! return unless @source_account&.use...
# frozen_string_literal: true require 'rails_helper' RSpec.describe BootstrapTimelineService, type: :service do subject { described_class.new } context 'when the new user has registered from an invite' do let(:service) { instance_double(FollowService) } let(:autofollow) { false } let(:inviter) ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ResolveAccountService < BaseService include DomainControlHelper include WebfingerHelper include Redisable include Lockable # Find or create an account record for a remote user. When creating, # look up the user's we...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ResolveAccountService, type: :service do subject { described_class.new } before do stub_request(:get, 'https://example.com/.well-known/host-meta').to_return(status: 404) stub_request(:get, 'https://quitter.no/avatar/7477-300-201602111903...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class FollowService < BaseService include Redisable include Payloadable include DomainControlHelper # Follow a remote user, notify remote user about the follow # @param [Account] source_account From which to follow # @par...
# frozen_string_literal: true require 'rails_helper' RSpec.describe FollowService, type: :service do subject { described_class.new } let(:sender) { Fabricate(:account, username: 'alice') } context 'when local account' do describe 'locked account' do let(:bob) { Fabricate(:account, locked: true, user...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class DeleteAccountService < BaseService include Payloadable ASSOCIATIONS_ON_SUSPEND = %w( account_notes account_pins active_relationships aliases block_relationships blocked_by_relationships conversat...
# frozen_string_literal: true require 'rails_helper' RSpec.describe DeleteAccountService, type: :service do shared_examples 'common behavior' do subject { described_class.new.call(account) } let!(:status) { Fabricate(:status, account: account) } let!(:mention) { Fabricate(:mention, account: local_follo...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class RemoveStatusService < BaseService include Redisable include Payloadable include Lockable # Delete a status # @param [Status] status # @param [Hash] options # @option [Boolean] :redraft # @option [Boolean] ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe RemoveStatusService, type: :service do subject { described_class.new } let!(:alice) { Fabricate(:account) } let!(:bob) { Fabricate(:account, username: 'bob', domain: 'example.com') } let!(:jeff) { Fabricate(:account) } let!(:hank) ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class BulkImportRowService def call(row) @account = row.bulk_import.account @data = row.data @type = row.bulk_import.type.to_sym case @type when :following, :blocking, :muting, :lists target_acct ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe BulkImportRowService do subject { described_class.new } let(:account) { Fabricate(:account) } let(:import) { Fabricate(:bulk_import, account: account, type: import_type) } let(:import_row) { Fabricate(:bulk_import_row, bulk_import: im...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ActivityPub::FetchRemoteKeyService < BaseService include JsonLdHelper class Error < StandardError; end # Returns actor that owns the key def call(uri, id: true, prefetched_body: nil, suppress_errors: true) raise Er...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ActivityPub::FetchRemoteKeyService, type: :service do subject { described_class.new } let(:webfinger) { { subject: 'acct:alice@example.com', links: [{ rel: 'self', href: 'https://example.com/alice' }] } } let(:public_key_pem) do <<~TEXT ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ActivityPub::ProcessCollectionService < BaseService include JsonLdHelper def call(body, actor, **options) @account = actor @json = original_json = Oj.load(body, mode: :strict) @options = options return u...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ActivityPub::ProcessCollectionService, type: :service do subject { described_class.new } let(:actor) { Fabricate(:account, domain: 'example.com', uri: 'http://example.com/account') } let(:payload) do { '@context': 'https://www.w3.or...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ActivityPub::FetchRemoteActorService < BaseService include JsonLdHelper include DomainControlHelper include WebfingerHelper class Error < StandardError; end SUPPORTED_TYPES = %w(Application Group Organization Person ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ActivityPub::FetchRemoteActorService, type: :service do subject { described_class.new } let!(:actor) do { '@context': 'https://www.w3.org/ns/activitystreams', id: 'https://example.com/alice', type: 'Person', preferred...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ActivityPub::FetchFeaturedCollectionService < BaseService include JsonLdHelper def call(account, **options) return if account.featured_collection_url.blank? || account.suspended? || account.local? @account = accoun...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ActivityPub::FetchFeaturedCollectionService, type: :service do subject { described_class.new } let(:actor) { Fabricate(:account, domain: 'example.com', uri: 'https://example.com/account', featured_collection_url: 'https://example.com/account/pin...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ActivityPub::FetchRemoteAccountService < ActivityPub::FetchRemoteActorService # Does a WebFinger roundtrip on each call, unless `only_key` is true def call(uri, id: true, prefetched_body: nil, break_on_redirect: false, only_...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ActivityPub::FetchRemoteAccountService, type: :service do subject { described_class.new } let!(:actor) do { '@context': 'https://www.w3.org/ns/activitystreams', id: 'https://example.com/alice', type: 'Person', preferr...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ActivityPub::FetchFeaturedTagsCollectionService < BaseService include JsonLdHelper def call(account, url) return if url.blank? || account.suspended? || account.local? @account = account @json = fetch_resourc...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ActivityPub::FetchFeaturedTagsCollectionService, type: :service do subject { described_class.new } let(:collection_url) { 'https://example.com/account/tags' } let(:actor) { Fabricate(:account, domain: 'example.com', uri: 'https://example.com/a...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ActivityPub::FetchRemoteStatusService < BaseService include JsonLdHelper include DomainControlHelper include Redisable DISCOVERIES_PER_REQUEST = 1000 # Should be called when uri has already been checked for locality ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ActivityPub::FetchRemoteStatusService, type: :service do include ActionView::Helpers::TextHelper subject { described_class.new } let!(:sender) { Fabricate(:account, domain: 'foo.bar', uri: 'https://foo.bar') } let!(:recipient) { Fabricate(:...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ActivityPub::ProcessAccountService < BaseService include JsonLdHelper include DomainControlHelper include Redisable include Lockable SUBDOMAINS_RATELIMIT = 10 DISCOVERIES_PER_REQUEST = 400 # Should be called with...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ActivityPub::ProcessAccountService, type: :service do subject { described_class.new } context 'with property values' do let(:payload) do { id: 'https://foo.test', type: 'Actor', inbox: 'https://foo.test/inbox', ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ActivityPub::FetchRepliesService < BaseService include JsonLdHelper def call(parent_status, collection_or_uri, allow_synchronous_requests: true, request_id: nil) @account = parent_status.account @allow_synchronous_r...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ActivityPub::FetchRepliesService, type: :service do subject { described_class.new } let(:actor) { Fabricate(:account, domain: 'example.com', uri: 'http://example.com/account') } let(:status) { Fabricate(:status, account: actor...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ActivityPub::SynchronizeFollowersService < BaseService include JsonLdHelper include Payloadable def call(account, partial_collection_url) @account = account items = collection_items(partial_collection_url) re...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ActivityPub::SynchronizeFollowersService, type: :service do subject { described_class.new } let(:actor) { Fabricate(:account, domain: 'example.com', uri: 'http://example.com/account', inbox_url: 'http://example.com/inbox') } let(:alic...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ActivityPub::ProcessStatusUpdateService < BaseService include JsonLdHelper include Redisable include Lockable def call(status, activity_json, object_json, request_id: nil) raise ArgumentError, 'Status has unsaved ch...
# frozen_string_literal: true require 'rails_helper' def poll_option_json(name, votes) { type: 'Note', name: name, replies: { type: 'Collection', totalItems: votes } } end RSpec.describe ActivityPub::ProcessStatusUpdateService, type: :service do subject { described_class.new } let!(:status) { Fabricate(:statu...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UploadService # Temporarily introduced for upload API: https://gitlab.com/gitlab-org/gitlab/-/issues/325788 attr_accessor :override_max_attachment_size def initialize(model, file, uploader_class = FileUploader, **uploader...
# frozen_string_literal: true require 'spec_helper' RSpec.describe UploadService, feature_category: :shared do describe 'File service' do before do @user = create(:user) @project = create(:project, creator_id: @user.id, namespace: @user.namespace) end context 'for valid gif file' do b...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class NoteSummary attr_reader :note attr_reader :metadata def initialize(noteable, project, author, body, action: nil, commit_count: nil, created_at: nil) @note = { noteable: noteable, created_at: created_at |...
# frozen_string_literal: true require 'spec_helper' RSpec.describe NoteSummary, feature_category: :code_review_workflow do let(:project) { build(:project) } let(:noteable) { build(:issue) } let(:user) { build(:user) } def create_note_summary described_class.new(noteable, project, user, 'note', actio...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class AutoMergeService < BaseService include Gitlab::Utils::StrongMemoize STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS = 'merge_when_pipeline_succeeds' STRATEGIES = [STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS].freeze class << self d...
# frozen_string_literal: true require 'spec_helper' RSpec.describe AutoMergeService, feature_category: :code_review_workflow do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { create(:user) } let(:service) { described_class.new(project, user) } before_all do project.add_maintain...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # RepositoryArchiveCleanUpService removes cached repository archives # that are generated on-the-fly by Gitaly. These files are stored in the # following form (as defined in lib/gitlab/git/repository.rb) and served # by GitLab Workhor...
# frozen_string_literal: true require 'spec_helper' RSpec.describe RepositoryArchiveCleanUpService, feature_category: :source_code_management do subject(:service) { described_class.new } describe '#execute (new archive locations)' do let(:sha) { "0" * 40 } it 'removes outdated archives and directories i...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ImportExportCleanUpService LAST_MODIFIED_TIME_IN_MINUTES = 1440 DIR_DEPTH = 5 attr_reader :mmin, :path def initialize(mmin = LAST_MODIFIED_TIME_IN_MINUTES) @mmin = mmin @path = Gitlab::ImportExport.storage_path...
# frozen_string_literal: true require 'spec_helper' RSpec.describe ImportExportCleanUpService, feature_category: :importers do describe '#execute' do let(:service) { described_class.new } let(:tmp_import_export_folder) { 'tmp/gitlab_exports' } before do allow_next_instance_of(Gitlab::Import::Log...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Finds the correct checkbox in the passed in markdown/html and toggles it's state, # returning the updated markdown/html. # We don't care if the text has changed above or below the specific checkbox, as long # the checkbox still exis...
# frozen_string_literal: true require 'spec_helper' RSpec.describe TaskListToggleService, feature_category: :team_planning do let(:markdown) do <<-EOT.strip_heredoc * [ ] Task 1 * [x] Task 2 A paragraph 1. [X] Item 1 - [ ] Sub-item 1 - [ ] loose list with an em...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UpdateContainerRegistryInfoService def execute registry_config = Gitlab.config.registry return unless registry_config.enabled && registry_config.api_url.presence # registry_info will query the /v2 route of the reg...
# frozen_string_literal: true require 'spec_helper' RSpec.describe UpdateContainerRegistryInfoService, feature_category: :container_registry do let_it_be(:application_settings) { Gitlab::CurrentSettings } let_it_be(:api_url) { 'http://registry.gitlab' } describe '#execute' do before do stub_access_to...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Base class, scoped by container (project or group). # # New or existing services which only require a project or group container # should subclass BaseProjectService or BaseGroupService. # # If you require a different but specific, ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BaseContainerService, feature_category: :container_registry do let(:project) { Project.new } let(:user) { User.new } describe '#initialize' do it 'accepts container and current_user' do subject = described_class.new(container: project...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class GravatarService def execute(email, size = nil, scale = 2, username: nil) return if Gitlab::FIPS.enabled? return unless Gitlab::CurrentSettings.gravatar_enabled? identifier = email.presence || username.presence ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe GravatarService, feature_category: :user_profile do describe '#execute' do let(:url) { 'http://example.com/avatar?hash=%{hash}&size=%{size}&email=%{email}&username=%{username}' } before do allow(Gitlab.config.gravatar).to receive(:pla...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class AccessTokenValidationService # Results: VALID = :valid EXPIRED = :expired REVOKED = :revoked INSUFFICIENT_SCOPE = :insufficient_scope IMPERSONATION_DISABLED = :impersonation_disabled attr_reader :token, :request ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe AccessTokenValidationService, feature_category: :system_access do describe ".include_any_scope?" do let(:request) { double("request") } it "returns true if the required scope is present in the token's scopes" do token = double("token"...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class AuditEventService include AuditEventSaveType # Instantiates a new service # # @param [User, token String] author the entity who authors the change # @param [User, Project, Group] entity the scope which audit event bel...
# frozen_string_literal: true require 'spec_helper' RSpec.describe AuditEventService, :with_license, feature_category: :audit_events do let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user, :with_sign_ins) } let_it_be(:project_member) { create(:project_member, user: user) } let(:service) ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # SystemNoteService # # Used for creating system notes (e.g., when a user references a merge request # from an issue, an issue's assignee changes, an issue is closed, etc.) module SystemNoteService extend self # Called when commi...
# frozen_string_literal: true require 'spec_helper' RSpec.describe SystemNoteService, feature_category: :shared do include Gitlab::Routing include RepoHelpers include AssetsHelpers include DesignManagementTestHelpers let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, :reposit...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class BulkPushEventPayloadService def initialize(event, push_data) @event = event @push_data = push_data end def execute @event.build_push_event_payload( action: @push_data[:action], commit_count: 0, ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkPushEventPayloadService, feature_category: :source_code_management do let(:event) { create(:push_event) } let(:push_data) do { action: :created, ref_count: 4, ref_type: :branch } end subject { described_class.ne...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # TodoService class # # Used for creating/updating todos after certain user actions # # Ex. # TodoService.new.new_issue(issue, current_user) # class TodoService include Gitlab::Utils::UsageData # When create an issue we should:...
# frozen_string_literal: true require 'spec_helper' RSpec.describe TodoService, feature_category: :team_planning do include AfterNextHelpers let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, :repository) } let_it_be(:author) { create(:user) } let_it_be(:assignee) { create(:user) }...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Base class for services that count a single resource such as the number of # issues for a project. class BaseCountService def relation_for_count raise( NotImplementedError, '"relation_for_count" must be implemented...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BaseCountService, :use_clean_rails_memory_store_caching, feature_category: :shared do let(:service) { described_class.new } describe '#relation_for_count' do it 'raises NotImplementedError' do expect { service.relation_for_count }.to ra...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Service class for creating push event payloads as stored in the # "push_event_payloads" table. # # Example: # # data = Gitlab::DataBuilder::Push.build(...) # event = Event.create(...) # # PushEventPayloadService.new(even...
# frozen_string_literal: true require 'spec_helper' RSpec.describe PushEventPayloadService, feature_category: :source_code_management do let(:event) { create(:push_event) } describe '#execute' do let(:push_data) do { commits: [ { id: '1cf19a015df3523caf0a1f9d40c98a267d6a2f...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true require 'resolv' class VerifyPagesDomainService < BaseService # The maximum number of seconds to be spent on each DNS lookup RESOLVER_TIMEOUT_SECONDS = 15 # How long verification lasts for VERIFICATION_PERIOD = 7.days REMO...
# frozen_string_literal: true require 'spec_helper' RSpec.describe VerifyPagesDomainService, feature_category: :pages do using RSpec::Parameterized::TableSyntax include EmailHelpers let(:error_status) { { status: :error, message: "Couldn't verify #{domain.domain}" } } subject(:service) { described_class.new...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # This service passes Markdown content through our GFM rewriter classes # which rewrite references to GitLab objects and uploads within the content # based on their visibility by the `target_parent`. class MarkdownContentRewriterServi...
# frozen_string_literal: true require 'spec_helper' RSpec.describe MarkdownContentRewriterService, feature_category: :team_planning do let_it_be(:user) { create(:user) } let_it_be(:source_parent) { create(:project, :public) } let_it_be(:target_parent) { create(:project, :public) } let(:content) { 'My content...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class SearchService include Gitlab::Allowable include Gitlab::Utils::StrongMemoize DEFAULT_PER_PAGE = Gitlab::SearchResults::DEFAULT_PER_PAGE MAX_PER_PAGE = 200 attr_reader :params def initialize(current_user, params = ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe SearchService, feature_category: :global_search do let_it_be(:user) { create(:user) } let_it_be(:accessible_group) { create(:group, :private) } let_it_be(:inaccessible_group) { create(:group, :private) } let_it_be(:group_member) { create(:gro...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class SystemHooksService def execute_hooks_for(model, event) data = build_event_data(model, event) model.run_after_commit_or_now do SystemHooksService.new.execute_hooks(data) end end def execute_hooks(data, h...
# frozen_string_literal: true require 'spec_helper' RSpec.describe SystemHooksService, feature_category: :webhooks do describe '#execute_hooks_for' do let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project) } let_it_be(:group_member) { create(:g...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true require 'securerandom' # Compare 2 refs for one repo or between repositories # and return Compare object that responds to commits and diffs class CompareService attr_reader :start_project, :start_ref_name def initialize(new_star...
# frozen_string_literal: true require 'spec_helper' RSpec.describe CompareService, feature_category: :source_code_management do let(:project) { create(:project, :repository) } let(:user) { create(:user) } let(:service) { described_class.new(project, 'feature') } describe '#execute' do context 'compare wi...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UserAgentDetailService def initialize(spammable:, perform_spam_check:) @spammable = spammable @perform_spam_check = perform_spam_check end def create spam_params = Gitlab::RequestContext.instance.spam_params ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe UserAgentDetailService, feature_category: :instance_resiliency do describe '#create', :request_store do let_it_be(:spammable) { create(:issue) } using RSpec::Parameterized::TableSyntax where(:perform_spam_check, :spam_params_present, :...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class X509CertificateRevokeService def execute(certificate) return unless certificate.revoked? certificate.x509_commit_signatures.update_all(verification_status: :unverified) end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe X509CertificateRevokeService, feature_category: :system_access do describe '#execute' do let(:service) { described_class.new } let!(:x509_signature_1) { create(:x509_commit_signature, x509_certificate: x509_certificate, verification_status: ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # EventCreateService class # # Used for creating events feed on dashboard after certain user action # # Ex. # EventCreateService.new.new_issue(issue, current_user) # class EventCreateService IllegalActionError = Class.new(Standard...
# frozen_string_literal: true require 'spec_helper' RSpec.describe EventCreateService, :clean_gitlab_redis_cache, :clean_gitlab_redis_shared_state, feature_category: :service_ping do include SnowplowHelpers let(:service) { described_class.new } let(:dates) { { start_date: Date.today.beginning_of_week, end_date...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class WebHookService class InternalErrorResponse ERROR_MESSAGE = 'internal error' attr_reader :body, :headers, :code def success? false end def redirection? false end def internal_server_e...
# frozen_string_literal: true require 'spec_helper' RSpec.describe WebHookService, :request_store, :clean_gitlab_redis_shared_state, feature_category: :webhooks do include StubRequests let(:ellipsis) { '…' } let_it_be(:project) { create(:project) } let_it_be_with_reload(:project_hook) { create(:project_hook,...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class CohortsService MONTHS_INCLUDED = 12 def execute { months_included: MONTHS_INCLUDED, cohorts: cohorts } end # Get an array of hashes that looks like: # # [ # { # registratio...
# frozen_string_literal: true require 'spec_helper' RSpec.describe CohortsService, feature_category: :shared do describe '#execute' do def month_start(months_ago) months_ago.months.ago.beginning_of_month.to_date end # In the interests of speed and clarity, this example has minimal data. it 'r...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UserProjectAccessChangedService DELAY = 1.hour MEDIUM_DELAY = 10.minutes HIGH_PRIORITY = :high MEDIUM_PRIORITY = :medium LOW_PRIORITY = :low def initialize(user_ids) @user_ids = Array.wrap(user_ids) end de...
# frozen_string_literal: true require 'spec_helper' RSpec.describe UserProjectAccessChangedService, feature_category: :system_access do describe '#execute' do it 'permits high-priority operation' do expect(AuthorizedProjectsWorker).to receive(:bulk_perform_async) .with([[1], [2]]) described...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # rubocop:disable GitlabSecurity/PublicSend # NotificationService class # # Used for notifying users with emails about different events # # Ex. # NotificationService.new.new_issue(issue, current_user) # # When calculating the recip...
# frozen_string_literal: true require 'spec_helper' RSpec.describe NotificationService, :mailer, feature_category: :team_planning do include EmailSpec::Matchers include ExternalAuthorizationServiceHelpers include NotificationHelpers let_it_be_with_refind(:project, reload: true) { create(:project, :public) } ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ResetProjectCacheService < BaseService def execute @project.increment!(:jobs_cache_index) end end ```
# frozen_string_literal: true require 'spec_helper' RSpec.describe ResetProjectCacheService, feature_category: :groups_and_projects do let(:project) { create(:project) } let(:user) { create(:user) } subject { described_class.new(project, user).execute } context 'when project cache_index is nil' do befor...