INSTRUCTION
stringlengths
202
35.5k
RESPONSE
stringlengths
75
161k
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Topics class MergeService attr_accessor :source_topic, :target_topic def initialize(source_topic, target_topic) @source_topic = source_topic @target_topic = target_topic end def execute val...
# frozen_string_literal: true require 'spec_helper' RSpec.describe Topics::MergeService, feature_category: :shared do let_it_be(:source_topic) { create(:topic, name: 'source_topic') } let_it_be(:target_topic) { create(:topic, name: 'target_topic') } let_it_be(:project_1) { create(:project, :public, topic_list: ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Analytics module CycleAnalytics module Stages class ListService < Analytics::CycleAnalytics::Stages::BaseService def execute return forbidden unless allowed? success(build_default_stages...
# frozen_string_literal: true require 'spec_helper' RSpec.describe Analytics::CycleAnalytics::Stages::ListService, feature_category: :value_stream_management do let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } let_it_be(:project_namespace) { project.project_namespace.reload } let(:...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Deployments # Service class for linking merge requests to deployments. class LinkMergeRequestsService attr_reader :deployment # The number of commits per query for which to find merge requests. COMMITS_PER_QUER...
# frozen_string_literal: true require 'spec_helper' RSpec.describe Deployments::LinkMergeRequestsService, feature_category: :continuous_delivery do let(:project) { create(:project, :repository) } # * ddd0f15 Merge branch 'po-fix-test-env-path' into 'master' # |\ # | * 2d1db52 Correct test_env.rb path for a...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Deployments # This service archives old deploymets and deletes deployment refs for # keeping the project repository performant. class ArchiveInProjectService < ::BaseService BATCH_SIZE = 100 def execute dep...
# frozen_string_literal: true require 'spec_helper' RSpec.describe Deployments::ArchiveInProjectService, feature_category: :continuous_delivery do let_it_be(:project) { create(:project, :repository) } let(:service) { described_class.new(project, nil) } describe '#execute' do subject { service.execute } ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Deployments # This class creates a deployment record for a pipeline job. class CreateForJobService DeploymentCreationError = Class.new(StandardError) def execute(job) return unless job.is_a?(::Ci::Processable...
# frozen_string_literal: true require 'spec_helper' RSpec.describe Deployments::CreateForJobService, feature_category: :continuous_delivery do let_it_be(:project) { create(:project, :repository) } let_it_be(:user) { create(:user) } let(:service) { described_class.new } it_behaves_like 'create deployment for...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Deployments class UpdateEnvironmentService attr_reader :deployment attr_reader :deployable delegate :environment, to: :deployment delegate :variables, to: :deployable delegate :options, to: :deployable, a...
# frozen_string_literal: true require 'spec_helper' RSpec.describe Deployments::UpdateEnvironmentService, feature_category: :continuous_delivery do let(:user) { create(:user) } let(:project) { create(:project, :repository) } let(:options) { { name: environment_name } } let(:pipeline) do create( :ci_...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Deployments class UpdateService attr_reader :deployment, :params def initialize(deployment, params) @deployment = deployment @params = params end def execute deployment.update_status(params...
# frozen_string_literal: true require 'spec_helper' RSpec.describe Deployments::UpdateService, feature_category: :continuous_delivery do let(:deploy) { create(:deployment) } describe '#execute' do it 'can update the status to running' do expect(described_class.new(deploy, status: 'running').execute) ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Deployments class CreateService attr_reader :environment, :current_user, :params def initialize(environment, current_user, params) @environment = environment @current_user = current_user @params = p...
# frozen_string_literal: true require 'spec_helper' RSpec.describe Deployments::CreateService, feature_category: :continuous_delivery do let(:user) { create(:user) } describe '#execute' do let(:project) { create(:project, :repository) } let(:environment) { create(:environment, project: project) } it...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module BulkImports class UploadsExportService include Gitlab::ImportExport::CommandLineUtil BATCH_SIZE = 100 AVATAR_PATH = 'avatar' attr_reader :exported_objects_count def initialize(portable, export_path) ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::UploadsExportService, feature_category: :importers do let(:export_path) { Dir.mktmpdir } let(:project) { create(:project, avatar: fixture_file_upload('spec/fixtures/rails_sample.png', 'image/png')) } let!(:upload) { create(:upload, ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module BulkImports class LfsObjectsExportService include Gitlab::ImportExport::CommandLineUtil BATCH_SIZE = 100 attr_reader :exported_objects_count def initialize(portable, export_path) @portable = portable ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::LfsObjectsExportService, feature_category: :importers do let_it_be(:project) { create(:project) } let_it_be(:lfs_json_filename) { "#{BulkImports::FileTransfer::ProjectConfig::LFS_OBJECTS_RELATION}.json" } let_it_be(:remote_url) { 'h...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # File Download Service allows remote file download into tmp directory. # # @param configuration [BulkImports::Configuration] Config object containing url and access token # @param relative_url [String] Relative URL to download the fi...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::FileDownloadService, feature_category: :importers do describe '#execute' do let_it_be(:allowed_content_types) { %w[application/gzip application/octet-stream] } let_it_be(:file_size_limit) { 5.gigabytes } let_it_be(:config) {...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module BulkImports class BatchedRelationExportService include Gitlab::Utils::StrongMemoize BATCH_SIZE = 1000 BATCH_CACHE_KEY = 'bulk_imports/batched_relation_export/%{export_id}/%{batch_id}' CACHE_DURATION = 4.hours...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::BatchedRelationExportService, feature_category: :importers do let_it_be(:user) { create(:user) } let_it_be(:portable) { create(:group) } let(:relation) { 'labels' } let(:jid) { '123' } subject(:service) { described_class.new(u...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module BulkImports class RepositoryBundleExportService def initialize(repository, export_path, export_filename) @repository = repository @export_path = export_path @export_filename = export_filename end ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::RepositoryBundleExportService, feature_category: :importers do let(:project) { create(:project) } let(:export_path) { Dir.mktmpdir } subject(:service) { described_class.new(repository, export_path, export_filename) } after do ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module BulkImports class ExportService # @param portable [Project|Group] A project or a group to export. # @param user [User] A user performing the export. # @param batched [Boolean] Whether to export the data in batches...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::ExportService, feature_category: :importers do let_it_be(:group) { create(:group) } let_it_be(:user) { create(:user) } before do group.add_owner(user) end subject { described_class.new(portable: group, user: user) } des...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module BulkImports class ProcessService PERFORM_DELAY = 5.seconds DEFAULT_BATCH_SIZE = 5 attr_reader :bulk_import def initialize(bulk_import) @bulk_import = bulk_import end def execute return u...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::ProcessService, feature_category: :importers do describe '#execute' do let_it_be_with_reload(:bulk_import) { create(:bulk_import) } subject { described_class.new(bulk_import) } context 'when no bulk import is found' do ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module BulkImports class RelationBatchExportService include Gitlab::ImportExport::CommandLineUtil def initialize(user, batch) @user = user @batch = batch @config = FileTransfer.config_for(portable) end...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::RelationBatchExportService, feature_category: :importers do let_it_be(:project) { create(:project) } let_it_be(:label) { create(:label, project: project) } let_it_be(:user) { create(:user) } let_it_be(:export) { create(:bulk_impor...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Archive Extraction Service allows extraction of contents # from `tar` archives with an additional handling (removal) # of file symlinks. # # @param tmpdir [String] A path where archive is located # and where its contents are extract...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::ArchiveExtractionService, feature_category: :importers do let_it_be(:tmpdir) { Dir.mktmpdir } let_it_be(:filename) { 'symlink_export.tar' } let_it_be(:filepath) { File.join(tmpdir, filename) } before do FileUtils.copy_file(Fi...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module BulkImports class FileExportService include Gitlab::ImportExport::CommandLineUtil SINGLE_OBJECT_RELATIONS = [ FileTransfer::ProjectConfig::REPOSITORY_BUNDLE_RELATION, FileTransfer::ProjectConfig::DESIGN_B...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::FileExportService, feature_category: :importers do let_it_be(:project) { create(:project) } let(:relations) do { 'uploads' => BulkImports::UploadsExportService, 'lfs_objects' => BulkImports::LfsObjectsExportService, ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Entry point of the BulkImport/Direct Transfer feature. # This service receives a Gitlab Instance connection params # and a list of groups or projects to be imported. # # Process topography: # # sync | async # ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::CreateService, feature_category: :importers do let(:user) { create(:user) } let(:credentials) { { url: 'http://gitlab.example', access_token: 'token' } } let(:destination_group) { create(:group, path: 'destination1') } let(:migrat...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module BulkImports class RelationExportService include Gitlab::ImportExport::CommandLineUtil EXISTING_EXPORT_TTL = 3.minutes def initialize(user, portable, relation, jid) @user = user @portable = portable ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::RelationExportService, feature_category: :importers do let_it_be(:jid) { 'jid' } let_it_be(:relation) { 'labels' } let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project) } ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module BulkImports class GetImportableDataService def initialize(params, query_params, credentials) @params = params @query_params = query_params @credentials = credentials end def execute { ...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::GetImportableDataService, feature_category: :importers do describe '#execute' do include_context 'bulk imports requests context', 'https://gitlab.example.com' let_it_be(:params) { { per_page: 20, page: 1 } } let_it_be(:quer...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # File Decompression Service allows gzipped files decompression into tmp directory. # # @param tmpdir [String] Temp directory to store downloaded file to. Must be located under `Dir.tmpdir`. # @param filename [String] Name of the file...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::FileDecompressionService, feature_category: :importers do using RSpec::Parameterized::TableSyntax let_it_be(:tmpdir) { Dir.mktmpdir } let_it_be(:ndjson_filename) { 'labels.ndjson' } let_it_be(:ndjson_filepath) { File.join(tmpdir,...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module BulkImports class TreeExportService include Gitlab::Utils::StrongMemoize delegate :exported_objects_count, to: :serializer def initialize(portable, export_path, relation, user) @portable = portable @...
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::TreeExportService, feature_category: :importers do let_it_be(:project) { create(:project) } let_it_be(:export_path) { Dir.mktmpdir } let(:relation) { 'issues' } subject(:service) { described_class.new(project, export_path, relat...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true TopicStatusUpdater = Struct.new(:topic, :user) do def update!(status, enabled, opts = {}) status = Status.new(status, enabled) @topic_timer = topic.public_topic_timer updated = nil Topic.transaction do ...
# encoding: UTF-8 # frozen_string_literal: true # TODO - test pinning, create_moderator_post RSpec.describe TopicStatusUpdater do fab!(:user) fab!(:admin) it "avoids notifying on automatically closed topics" do # TODO: TopicStatusUpdater should suppress message bus updates from the users it "pretends to re...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class NotificationEmailer class EmailUser attr_reader :notification, :no_delay def initialize(notification, no_delay: false) @notification = notification @no_delay = no_delay end def group_mentioned ...
# frozen_string_literal: true RSpec.describe NotificationEmailer do before do freeze_time NotificationEmailer.enable end fab!(:topic) fab!(:post) { Fabricate(:post, topic: topic) } # something is off with fabricator def create_notification(type, user = nil) user ||= Fabricate(:user) Notif...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class WordWatcher REPLACEMENT_LETTER ||= CGI.unescape_html("&#9632;") CACHE_VERSION ||= 3 def initialize(raw) @raw = raw end @cache_enabled = true def self.disable_cache @cache_enabled = false end def self....
# frozen_string_literal: true RSpec.describe WordWatcher do let(:raw) { <<~RAW.strip } Do you like liquorice? I really like them. One could even say that I am *addicted* to liquorice. And if you can mix it up with some anise, then I'm in heaven ;) RAW after { Discourse.redis.flushdb } d...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UsernameCheckerService def initialize(allow_reserved_username: false) @allow_reserved_username = allow_reserved_username end def check_username(username, email) if username && username.length > 0 validator =...
# frozen_string_literal: true RSpec.describe UsernameCheckerService do describe "#check_username" do before do @service = UsernameCheckerService.new @nil_email = nil @email = "vincentvega@example.com" end context "when username is invalid" do it "rejects too short usernames" do ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class HashtagAutocompleteService HASHTAGS_PER_REQUEST = 20 SEARCH_MAX_LIMIT = 50 DEFAULT_DATA_SOURCES = [CategoryHashtagDataSource, TagHashtagDataSource] DEFAULT_CONTEXTUAL_TYPE_PRIORITIES = [ { type: "category", context: ...
# frozen_string_literal: true RSpec.describe HashtagAutocompleteService do subject(:service) { described_class.new(guardian) } fab!(:user) fab!(:category1) { Fabricate(:category, name: "The Book Club", slug: "the-book-club") } fab!(:tag1) do Fabricate(:tag, name: "great-books", staff_topic_count: 22, publ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class HeatSettingsUpdater def self.update return unless SiteSetting.automatic_topic_heat_values views_by_percentile = views_thresholds update_setting(:topic_views_heat_high, views_by_percentile[10]) update_setting(:...
# frozen_string_literal: true RSpec.describe HeatSettingsUpdater do describe ".update" do subject(:update_settings) { described_class.update } def expect_default_values %i[topic_views_heat topic_post_like_heat].each do |prefix| %i[low medium high].each do |level| setting_name = "#{pr...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UsernameChanger def initialize(user, new_username, actor = nil) @user = user @old_username = user.username @new_username = new_username @actor = actor end def self.change(user, new_username, actor = nil) ...
# frozen_string_literal: true RSpec.describe UsernameChanger do before { Jobs.run_immediately! } describe "#change" do let(:user) { Fabricate(:user) } context "when everything goes well" do let!(:old_username) { user.username } it "should change the username" do new_username = "#{use...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class GroupActionLogger def initialize(acting_user, group) @acting_user = acting_user @group = group end def log_make_user_group_owner(target_user) GroupHistory.create!( default_params.merge( action: G...
# frozen_string_literal: true RSpec.describe GroupActionLogger do subject(:logger) { described_class.new(group_owner, group) } fab!(:group_owner) { Fabricate(:user) } fab!(:group) fab!(:user) before { group.add_owner(group_owner) } describe "#log_make_user_group_owner" do it "should create the right...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class GroupMentionsUpdater def self.update(current_name, previous_name) Post .where( "cooked LIKE '%class=\"mention-group%' AND raw LIKE :previous_name", previous_name: "%@#{previous_name}%", ) ...
# frozen_string_literal: true RSpec.describe GroupMentionsUpdater do fab!(:post) before { Jobs.run_immediately! } describe ".update" do it "should update valid group mentions" do new_group_name = "awesome_team" old_group_name = "team" [ ["@#{old_group_name} is awesome!", "@#{new_...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class PostActionNotifier def self.disable @disabled = true end def self.enable @disabled = false end # For testing purposes def self.reset! @custom_post_revision_notifier_recipients = nil end def self.al...
# frozen_string_literal: true RSpec.describe PostActionNotifier do before do PostActionNotifier.enable Jobs.run_immediately! end fab!(:evil_trout) fab!(:post) context "when editing a post" do it "notifies a user of the revision" do expect { post.revise(evil_trout, raw: "world is the new b...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ColorSchemeRevisor def initialize(color_scheme, params = {}) @color_scheme = color_scheme @params = params end def self.revise(color_scheme, params) self.new(color_scheme, params).revise end def revise ...
# frozen_string_literal: true RSpec.describe ColorSchemeRevisor do let(:color) { Fabricate.build(:color_scheme_color, hex: "FFFFFF", color_scheme: nil) } let(:color_scheme) do Fabricate( :color_scheme, created_at: 1.day.ago, updated_at: 1.day.ago, color_scheme_colors: [color], ) e...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UserUpdater CATEGORY_IDS = { watched_first_post_category_ids: :watching_first_post, watched_category_ids: :watching, tracked_category_ids: :tracking, regular_category_ids: :regular, muted_category_ids: :mut...
# frozen_string_literal: true RSpec.describe UserUpdater do fab!(:user) fab!(:u1) { Fabricate(:user) } fab!(:u2) { Fabricate(:user) } fab!(:u3) { Fabricate(:user) } let(:acting_user) { Fabricate.build(:user) } describe "#update_muted_users" do it "has no cross talk" do updater = UserUpdater.new...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class RandomTopicSelector BACKFILL_SIZE = 3000 BACKFILL_LOW_WATER_MARK = 500 def self.backfill(category = nil) exclude = category&.topic_id options = { per_page: category ? category.num_featured_topics : 3, ...
# frozen_string_literal: true RSpec.describe RandomTopicSelector do it "can correctly use cache" do key = RandomTopicSelector.cache_key Discourse.redis.del key 4.times { |t| Discourse.redis.rpush key, t } expect(RandomTopicSelector.next(0)).to eq([]) expect(RandomTopicSelector.next(2)).to eq([...
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, @u...
# 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_t...
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) # Exi...
# 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 "include...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Responsible for logging the actions of admins and moderators. class StaffActionLogger def self.base_attrs %i[topic_id post_id context subject ip_address previous_value new_value] end def initialize(admin) @admin = adm...
# frozen_string_literal: true RSpec.describe StaffActionLogger do fab!(:admin) let(:logger) { described_class.new(admin) } describe "new" do it "raises an error when user is nil" do expect { described_class.new(nil) }.to raise_error(Discourse::InvalidParameters) end it "raises an error when u...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true require "net/imap" require "net/smtp" require "net/pop" # Usage: # # begin # EmailSettingsValidator.validate_imap(host: "imap.test.com", port: 999, username: "test@test.com", password: "password") # # # or for specific host prese...
# frozen_string_literal: true RSpec.describe EmailSettingsValidator do let(:username) { "kwest@gmail.com" } let(:password) { "mbdtf" } describe "#validate_imap" do let(:host) { "imap.gmail.com" } let(:port) { 993 } let(:net_imap_stub) do obj = mock() obj.stubs(:login).returns(true) ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UserStatCountUpdater class << self def increment!(post, user_stat: nil) update_using_operator!(post, user_stat: user_stat, action: :increment!) end def decrement!(post, user_stat: nil) update_using_ope...
# frozen_string_literal: true RSpec.describe UserStatCountUpdater do fab!(:user) fab!(:user_stat) { user.user_stat } fab!(:post) fab!(:post_2) { Fabricate(:post, topic: post.topic) } before do @orig_logger = Rails.logger Rails.logger = @fake_logger = FakeLogger.new SiteSetting.verbose_user_stat_...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UserAuthenticator def initialize( user, session, authenticator_finder: Users::OmniauthCallbacksController, require_password: true ) @user = user @session = session if session&.dig(:authentication)...
# frozen_string_literal: true RSpec.describe UserAuthenticator do def github_auth(email_valid) { email: "user53@discourse.org", username: "joedoe546", email_valid: email_valid, omit_username: nil, name: "Joe Doe 546", authenticator_name: "github", extra_data: { p...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Used as a data source via HashtagAutocompleteService to provide tag # results when looking up a tag slug via markdown or searching for # tags via the # autocomplete character. class TagHashtagDataSource def self.enabled? SiteS...
# frozen_string_literal: true RSpec.describe TagHashtagDataSource do fab!(:tag1) { Fabricate(:tag, name: "fact", public_topic_count: 0) } fab!(:tag2) { Fabricate(:tag, name: "factor", public_topic_count: 5) } fab!(:tag3) { Fabricate(:tag, name: "factory", public_topic_count: 4) } fab!(:tag4) { Fabricate(:tag, ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # A service class that backfills the changes to the default sidebar categories and tags site settings. # # When a category/tag is removed from the site settings, the `SidebarSectionLink` records associated with the category/tag # are ...
# frozen_string_literal: true RSpec.describe SidebarSiteSettingsBackfiller do fab!(:user) fab!(:user2) { Fabricate(:user) } fab!(:user3) { Fabricate(:user) } fab!(:staged_user) { Fabricate(:user, staged: true) } fab!(:category) fab!(:category2) { Fabricate(:category) } fab!(:category3) { Fabricate(:categ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class DestroyTask def initialize(io = STDOUT) @io = io end def destroy_topics(category, parent_category = nil, delete_system_topics = false) c = Category.find_by_slug(category, parent_category) descriptive_slug = pa...
# frozen_string_literal: true RSpec.describe DestroyTask do describe "destroy topics" do fab!(:c) { Fabricate(:category_with_definition) } fab!(:t) { Fabricate(:topic, category: c) } let!(:p) { Fabricate(:post, topic: t) } fab!(:c2) { Fabricate(:category_with_definition) } fab!(:t2) { Fabricate(:...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true require "net/imap" require "net/smtp" require "net/pop" class EmailSettingsExceptionHandler EXPECTED_EXCEPTIONS = [ Net::POPAuthenticationError, Net::IMAP::NoResponseError, Net::IMAP::Error, Net::SMTPAuthenticationE...
# frozen_string_literal: true RSpec.describe EmailSettingsExceptionHandler do describe "#friendly_exception_message" do it "formats a Net::POPAuthenticationError" do exception = Net::POPAuthenticationError.new("invalid credentials") expect(described_class.friendly_exception_message(exception, "pop.te...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class PostOwnerChanger def initialize(params) @post_ids = params[:post_ids] @topic = Topic.with_deleted.find_by(id: params[:topic_id].to_i) @new_owner = params[:new_owner] @acting_user = params[:acting_user] @ski...
# frozen_string_literal: true RSpec.describe PostOwnerChanger do describe "#change_owner!" do fab!(:editor) { Fabricate(:admin) } fab!(:user_a) { Fabricate(:user) } let(:p1) { create_post(post_number: 1) } let(:topic) { p1.topic } let(:p2) { create_post(topic: topic, post_number: 2) } let(:p3...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class TopicTimestampChanger class InvalidTimestampError < StandardError end def initialize(timestamp:, topic: nil, topic_id: nil) @topic = topic || Topic.with_deleted.find(topic_id) @posts = @topic.posts @current_ti...
# frozen_string_literal: true RSpec.describe TopicTimestampChanger do describe "#change!" do let(:old_timestamp) { Time.zone.now } let(:topic) { Fabricate(:topic, created_at: old_timestamp) } let!(:p1) { Fabricate(:post, topic: topic, created_at: old_timestamp) } let!(:p2) { Fabricate(:post, topic: t...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class TrustLevelGranter def initialize(trust_level, user) @trust_level, @user = trust_level, user end def self.grant(trust_level, user) TrustLevelGranter.new(trust_level, user).grant end def grant if @user.trus...
# frozen_string_literal: true RSpec.describe TrustLevelGranter do describe "grant" do it "grants trust level" do user = Fabricate(:user, email: "foo@bar.com", trust_level: 0) TrustLevelGranter.grant(3, user) user.reload expect(user.trust_level).to eq(3) end end end
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ThemeSettingsMigrationsRunner Migration = Struct.new(:version, :name, :original_name, :code, :theme_field_id) MIGRATION_ENTRY_POINT_JS = <<~JS const migrate = require("discourse/theme/migration")?.default; function ...
# frozen_string_literal: true describe ThemeSettingsMigrationsRunner do fab!(:theme) fab!(:migration_field) { Fabricate(:migration_theme_field, version: 1, theme: theme) } fab!(:settings_field) { Fabricate(:settings_theme_field, theme: theme, value: <<~YAML) } integer_setting: 1 boolean_setting: true...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Responsible for destroying a User record class UserDestroyer class PostsExistError < RuntimeError end def initialize(actor) @actor = actor raise Discourse::InvalidParameters.new("acting user is nil") unless @actor && ...
# frozen_string_literal: true RSpec.describe UserDestroyer do fab!(:user) { Fabricate(:user_with_secondary_email) } fab!(:admin) describe ".new" do it "raises an error when user is nil" do expect { UserDestroyer.new(nil) }.to raise_error(Discourse::InvalidParameters) end it "raises an error w...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module WildcardDomainChecker def self.check_domain(domain, external_domain) escaped_domain = domain[0] == "*" ? Regexp.escape(domain).sub("\\*", '\S*') : Regexp.escape(domain) domain_regex = Regexp.new("\\A#{escaped_do...
# frozen_string_literal: true RSpec.describe WildcardDomainChecker do describe ".check_domain" do context "when domain is valid" do it "returns correct domain" do result1 = WildcardDomainChecker.check_domain( "*.discourse.org", "anything.is.possible.discourse.org",...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # GroupMessage sends a private message to a group. # It will also avoid sending the same message repeatedly, which can happen with # notifications to moderators when spam is detected. # # Options: # # user: (User) If the message is ...
# frozen_string_literal: true RSpec.describe GroupMessage do subject(:send_group_message) do GroupMessage.create(moderators_group, :user_automatically_silenced, user: user) end let(:moderators_group) { Group[:moderators].name } let!(:admin) { Fabricate.build(:admin, id: 999) } let!(:user) { Fabricate.b...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UserMerger def initialize(source_user, target_user, acting_user = nil) @source_user = source_user @target_user = target_user @acting_user = acting_user @user_id = source_user.id @source_primary_email = sour...
# frozen_string_literal: true RSpec.describe UserMerger do fab!(:target_user) { Fabricate(:user, username: "alice", email: "alice@example.com") } fab!(:source_user) { Fabricate(:user, username: "alice1", email: "alice@work.com") } fab!(:walter) { Fabricate(:walter_white) } fab!(:coding_horror) fab!(:p1) { F...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class PostAlerter USER_BATCH_SIZE = 100 def self.post_created(post, opts = {}) PostAlerter.new(opts).after_save_post(post, true) post end def self.post_edited(post, opts = {}) PostAlerter.new(opts).after_save_pos...
# frozen_string_literal: true RSpec::Matchers.define :add_notification do |user, notification_type| match(notify_expectation_failures: true) do |actual| notifications = user.notifications before = notifications.count actual.call expect(notifications.count).to eq(before + 1), "expected 1 new not...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class ExternalUploadManager DOWNLOAD_LIMIT = 100.megabytes SIZE_MISMATCH_BAN_MINUTES = 5 BAN_USER_REDIS_PREFIX = "ban_user_from_external_uploads_" UPLOAD_TYPES_EXCLUDED_FROM_UPLOAD_PROMOTION = ["backup"].freeze class Check...
# frozen_string_literal: true RSpec.describe ExternalUploadManager do subject(:manager) { ExternalUploadManager.new(external_upload_stub) } fab!(:user) let!(:logo_file) { file_from_fixtures("logo.png") } let!(:pdf_file) { file_from_fixtures("large.pdf", "pdf") } let(:object_size) { 1.megabyte } let(:etag...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true ## # Anything that we want to be able to bookmark must be registered as a # bookmarkable type using Plugin::Instance#register_bookmarkable(bookmarkable_klass), # where the bookmarkable_klass is a class that implements this BaseBookmar...
# frozen_string_literal: true RSpec.describe BaseBookmarkable do fab!(:bookmark) { Fabricate(:bookmark, bookmarkable: Fabricate(:post)) } describe "#send_reminder_notification" do it "raises an error if the data, data.bookmarkable_url, or data.title values are missing from notification_data" do expect {...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Used as a data source via HashtagAutocompleteService to provide category # results when looking up a category slug via markdown or searching for # categories via the # autocomplete character. class CategoryHashtagDataSource def se...
# frozen_string_literal: true RSpec.describe CategoryHashtagDataSource do fab!(:parent_category) { Fabricate(:category, slug: "fun", topic_count: 2) } fab!(:category1) do Fabricate(:category, slug: "random", topic_count: 12, parent_category: parent_category) end fab!(:category2) { Fabricate(:category, name...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UserAnonymizer attr_reader :user_history EMAIL_SUFFIX = "@anonymized.invalid" # opts: # anonymize_ip - an optional new IP to update their logs with def initialize(user, actor = nil, opts = nil) @user = user ...
# frozen_string_literal: true RSpec.describe UserAnonymizer do let(:admin) { Fabricate(:admin) } describe "event" do subject(:make_anonymous) do described_class.make_anonymous(user, admin, anonymize_ip: "2.2.2.2") end let(:user) { Fabricate(:user, username: "edward") } it "triggers the eve...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UserActivator attr_reader :user, :request, :session, :cookies, :message def initialize(user, request, session, cookies) @user = user @session = session @cookies = cookies @request = request @message = ni...
# frozen_string_literal: true RSpec.describe UserActivator do fab!(:user) let!(:email_token) { Fabricate(:email_token, user: user) } describe "email_activator" do let(:activator) { EmailActivator.new(user, nil, nil, nil) } it "create email token and enqueues user email" do now = freeze_time ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class PushNotificationPusher TOKEN_VALID_FOR_SECONDS ||= 5 * 60 CONNECTION_TIMEOUT_SECONDS = 5 def self.push(user, payload) message = nil I18n.with_locale(user.effective_locale) do notification_icon_name = Notific...
# frozen_string_literal: true RSpec.describe PushNotificationPusher do it "returns badges url by default" do expect(PushNotificationPusher.get_badge).to eq("/assets/push-notifications/discourse.png") end it "returns custom badges url" do upload = Fabricate(:upload) SiteSetting.push_notifications_ico...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class AnonymousShadowCreator attr_reader :user def self.get_master(user) new(user).get_master end def self.get(user) new(user).get end def initialize(user) @user = user end def get_master return unl...
# frozen_string_literal: true RSpec.describe AnonymousShadowCreator do it "returns no shadow by default" do expect(AnonymousShadowCreator.get(Fabricate.build(:user))).to eq(nil) end context "when anonymous posting is enabled" do fab!(:user) { Fabricate(:user, trust_level: 3) } before do SiteS...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class InlineUploads PLACEHOLDER = "__replace__" PATH_PLACEHOLDER = "__replace_path__" UPLOAD_REGEXP_PATTERN = "/original/(\\dX/(?:\\h/)*\\h{40}[a-zA-Z0-9.]*)(\\?v=\\d+)?" private_constant :UPLOAD_REGEXP_PATTERN def self.pr...
# frozen_string_literal: true RSpec.describe InlineUploads do before { set_cdn_url "https://awesome.com" } describe ".process" do context "with local uploads" do fab!(:upload) fab!(:upload2) { Fabricate(:upload) } fab!(:upload3) { Fabricate(:upload) } it "should not correct existing in...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UserSilencer attr_reader :user_history def initialize(user, by_user = nil, opts = {}) @user, @by_user, @opts = user, by_user, opts end def self.silence(user, by_user = nil, opts = {}) UserSilencer.new(user, by_...
# frozen_string_literal: true RSpec.describe UserSilencer do fab!(:user) { Fabricate(:user, trust_level: 0) } fab!(:post) { Fabricate(:post, user: user) } fab!(:admin) describe "silence" do subject(:silence_user) { silencer.silence } let(:silencer) { UserSilencer.new(user) } it "silences the use...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class TopicBookmarkable < BaseBookmarkable include TopicPostBookmarkableHelper def self.model Topic end def self.serializer UserTopicBookmarkSerializer end def self.preload_associations [:category, :tags, { ...
# frozen_string_literal: true require "rails_helper" RSpec.describe TopicBookmarkable do subject(:registered_bookmarkable) { RegisteredBookmarkable.new(TopicBookmarkable) } fab!(:user) fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) } let(:guardian) { Guardian.new(user) } ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class PostBookmarkable < BaseBookmarkable include TopicPostBookmarkableHelper def self.model Post end def self.serializer UserPostBookmarkSerializer end def self.preload_associations [{ topic: %i[tags catego...
# frozen_string_literal: true require "rails_helper" RSpec.describe PostBookmarkable do subject(:registered_bookmarkable) { RegisteredBookmarkable.new(PostBookmarkable) } fab!(:user) fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) } let(:guardian) { Guardian.new(user) } l...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module WildcardUrlChecker def self.check_url(url, url_to_check) return false if !valid_url?(url_to_check) escaped_url = Regexp.escape(url).sub("\\*", '\S*') url_regex = Regexp.new("\\A#{escaped_url}\\z", "i") url_t...
# frozen_string_literal: true RSpec.describe WildcardUrlChecker do describe ".check_url" do context "when url is valid" do it "returns true" do result1 = described_class.check_url( "https://*.discourse.org", "https://anything.is.possible.discourse.org", )...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class EmailStyleUpdater attr_reader :errors def initialize(user) @user = user @errors = [] end def update(attrs) if attrs.has_key?(:html) && !attrs[:html].include?("%{email_content}") @errors << I18n.t("ema...
# frozen_string_literal: true RSpec.describe EmailStyleUpdater do fab!(:admin) let(:default_html) { File.read("#{Rails.root}/app/views/email/default_template.html") } let(:updater) { EmailStyleUpdater.new(admin) } def expect_settings_to_be_unset expect(SiteSetting.email_custom_template).to_not be_present ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class SearchIndexer MIN_POST_BLURB_INDEX_VERSION = 4 POST_INDEX_VERSION = 5 TOPIC_INDEX_VERSION = 4 CATEGORY_INDEX_VERSION = 3 USER_INDEX_VERSION = 3 TAG_INDEX_VERSION = 3 # version to apply when issuing a background r...
# frozen_string_literal: true RSpec.describe SearchIndexer do let(:post_id) { 99 } before { SearchIndexer.enable } after { SearchIndexer.disable } it "correctly indexes chinese" do SiteSetting.default_locale = "zh_CN" data = "你好世界" SearchIndexer.update_posts_index( post_id: post_id, ...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true class UserNotificationScheduleProcessor attr_accessor :schedule, :user, :timezone_name def initialize(schedule) @schedule = schedule @user = schedule.user @timezone_name = user.user_option.timezone end def create...
# frozen_string_literal: true RSpec.describe UserNotificationScheduleProcessor do include ActiveSupport::Testing::TimeHelpers fab!(:user) let(:standard_schedule) do schedule = UserNotificationSchedule.create({ user: user }.merge(UserNotificationSchedule::DEFAULT)) schedule.enabled = true sched...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true # Consolidate notifications based on a threshold and a time window. # # If a consolidated notification already exists, we'll update it instead. # If it doesn't and creating a new one would match the threshold, we delete existing ones ...
# frozen_string_literal: true RSpec.describe Notifications::ConsolidateNotifications do describe "#before_consolidation_callbacks" do fab!(:user) let(:rule) do described_class.new( from: Notification.types[:liked], to: Notification.types[:liked], consolidation_window: 10.minutes...
Write RSpec test file for following ruby class ```ruby # frozen_string_literal: true module Notifications class ConsolidationPlanner def consolidate_or_save!(notification) plan = plan_for(notification) return :no_plan if plan.nil? plan.consolidate_or_save!(notification) end private ...
# frozen_string_literal: true RSpec.describe Notifications::ConsolidationPlanner do subject(:planner) { described_class.new } describe "#consolidate_or_save!" do let(:threshold) { 1 } fab!(:user) let(:like_user) { "user1" } before { SiteSetting.notification_consolidation_threshold = threshold } ...
Write RSpec test file for following ruby class ```ruby class SearchService pattr_initialize [:current_user!, :current_account!, :params!, :search_type!] def perform case search_type when 'Message' { messages: filter_messages } when 'Conversation' { conversations: filter_conversations } ...
require 'rails_helper' describe SearchService do subject(:search) { described_class.new(current_user: user, current_account: account, params: params, search_type: search_type) } let(:search_type) { 'all' } let!(:account) { create(:account) } let!(:user) { create(:user, account: account) } let!(:inbox) { cre...
Write RSpec test file for following ruby class ```ruby class ActionService include EmailHelper def initialize(conversation) @conversation = conversation.reload end def mute_conversation(_params) @conversation.mute! end def snooze_conversation(_params) @conversation.snoozed! end def resol...
require 'rails_helper' describe ActionService do let(:account) { create(:account) } describe '#resolve_conversation' do let(:conversation) { create(:conversation) } let(:action_service) { described_class.new(conversation) } it 'resolves the conversation' do expect(conversation.status).to eq('op...
Write RSpec test file for following ruby class ```ruby class Twitter::WebhookSubscribeService include Rails.application.routes.url_helpers pattr_initialize [:inbox_id] def perform ensure_webhook unless subscription? subscribe_response = twitter_client.create_subscription raise StandardError,...
require 'rails_helper' describe Twitter::WebhookSubscribeService do subject(:webhook_subscribe_service) { described_class.new(inbox_id: twitter_inbox.id) } let(:twitter_client) { instance_double(Twitty::Facade) } let(:twitter_success_response) { instance_double(Twitty::Response, status: '200', body: { message: ...
Write RSpec test file for following ruby class ```ruby class Twitter::SendOnTwitterService < Base::SendOnChannelService pattr_initialize [:message!] private delegate :additional_attributes, to: :contact def channel_class Channel::TwitterProfile end def perform_reply conversation_type == 'tweet' ...
require 'rails_helper' describe Twitter::SendOnTwitterService do subject(:send_reply_service) { described_class.new(message: message) } let(:twitter_client) { instance_double(Twitty::Facade) } let(:twitter_response) { instance_double(Twitty::Response) } let(:account) { create(:account) } let(:widget_inbox) ...
Write RSpec test file for following ruby class ```ruby class AutoAssignment::InboxRoundRobinService pattr_initialize [:inbox!] # called on inbox delete def clear_queue ::Redis::Alfred.delete(round_robin_key) end # called on inbox member create def add_agent_to_queue(user_id) ::Redis::Alfred.lpush(...
require 'rails_helper' describe AutoAssignment::InboxRoundRobinService do subject(:inbox_round_robin_service) { described_class.new(inbox: inbox) } let!(:account) { create(:account) } let!(:inbox) { create(:inbox, account: account) } let!(:inbox_members) { create_list(:inbox_member, 5, inbox: inbox) } desc...
Write RSpec test file for following ruby class ```ruby class AutoAssignment::AgentAssignmentService # Allowed agent ids: array # This is the list of agents from which an agent can be assigned to this conversation # examples: Agents with assignment capacity, Agents who are members of a team etc pattr_initialize ...
require 'rails_helper' RSpec.describe AutoAssignment::AgentAssignmentService do let!(:account) { create(:account) } let!(:inbox) { create(:inbox, account: account, enable_auto_assignment: false) } let!(:inbox_members) { create_list(:inbox_member, 5, inbox: inbox) } let!(:conversation) { create(:conversation, i...
Write RSpec test file for following ruby class ```ruby class Messages::MentionService pattr_initialize [:message!] def perform return unless valid_mention_message?(message) validated_mentioned_ids = filter_mentioned_ids_by_inbox return if validated_mentioned_ids.blank? Conversations::UserMentionJ...
require 'rails_helper' describe Messages::MentionService do let!(:account) { create(:account) } let!(:user) { create(:user, account: account) } let!(:first_agent) { create(:user, account: account) } let!(:second_agent) { create(:user, account: account) } let!(:inbox) { create(:inbox, account: account) } le...
Write RSpec test file for following ruby class ```ruby class Messages::NewMessageNotificationService pattr_initialize [:message!] def perform return unless message.notifiable? notify_participating_users notify_conversation_assignee end private delegate :conversation, :sender, :account, to: :me...
require 'rails_helper' describe Messages::NewMessageNotificationService do context 'when message is not notifiable' do it 'will not create any notifications' do message = build(:message, message_type: :activity) expect(NotificationBuilder).not_to receive(:new) described_class.new(message: messa...
Write RSpec test file for following ruby class ```ruby class Sms::DeliveryStatusService pattr_initialize [:inbox!, :params!] def perform return unless supported_status? process_status if message.present? end private def process_status @message.status = status @message.external_error = exte...
require 'rails_helper' describe Sms::DeliveryStatusService do describe '#perform' do let!(:account) { create(:account) } let!(:sms_channel) { create(:channel_sms) } let!(:contact) { create(:contact, account: account, phone_number: '+12345') } let(:contact_inbox) { create(:contact_inbox, source_id: '+...
Write RSpec test file for following ruby class ```ruby class Sms::IncomingMessageService include ::FileTypeHelper pattr_initialize [:inbox!, :params!] def perform set_contact set_conversation @message = @conversation.messages.create!( content: params[:text], account_id: @inbox.account_id...
require 'rails_helper' describe Sms::IncomingMessageService do describe '#perform' do let!(:sms_channel) { create(:channel_sms) } let(:params) do { 'id': '3232420-2323-234324', 'owner': sms_channel.phone_number, 'applicationId': '2342349-324234d-32432432', 'time': '2022...
Write RSpec test file for following ruby class ```ruby class Sms::SendOnSmsService < Base::SendOnChannelService private def channel_class Channel::Sms end def perform_reply send_on_sms end def send_on_sms message_id = channel.send_message(message.conversation.contact_inbox.source_id, message)...
require 'rails_helper' describe Sms::SendOnSmsService do describe '#perform' do context 'when a valid message' do let(:sms_request) { double } let!(:sms_channel) { create(:channel_sms) } let!(:contact_inbox) { create(:contact_inbox, inbox: sms_channel.inbox, source_id: '+123456789') } let...
Write RSpec test file for following ruby class ```ruby class Sms::OneoffSmsCampaignService pattr_initialize [:campaign!] def perform raise "Invalid campaign #{campaign.id}" if campaign.inbox.inbox_type != 'Sms' || !campaign.one_off? raise 'Completed Campaign' if campaign.completed? # marks campaign co...
require 'rails_helper' describe Sms::OneoffSmsCampaignService do subject(:sms_campaign_service) { described_class.new(campaign: campaign) } let(:account) { create(:account) } let!(:sms_channel) { create(:channel_sms) } let!(:sms_inbox) { create(:inbox, channel: sms_channel) } let(:label1) { create(:label, a...
Write RSpec test file for following ruby class ```ruby class Notification::PushNotificationService include Rails.application.routes.url_helpers pattr_initialize [:notification!] def perform return unless user_subscribed_to_notification? notification_subscriptions.each do |subscription| send_brows...
require 'rails_helper' describe Notification::PushNotificationService do let!(:account) { create(:account) } let!(:user) { create(:user, account: account) } let!(:notification) { create(:notification, user: user, account: user.accounts.first) } let(:fcm_double) { double } before do allow(WebPush).to rec...
Write RSpec test file for following ruby class ```ruby # refer: https://gitlab.com/gitlab-org/ruby/gems/gitlab-mail_room/-/blob/master/lib/mail_room/microsoft_graph/connection.rb # refer: https://github.com/microsoftgraph/msgraph-sample-rubyrailsapp/tree/b4a6869fe4a438cde42b161196484a929f1bee46 # https://learn.microsof...
require 'rails_helper' RSpec.describe Microsoft::RefreshOauthTokenService do let(:access_token) { SecureRandom.hex } let(:refresh_token) { SecureRandom.hex } let(:expires_on) { Time.zone.now + 3600 } let!(:microsoft_email_channel) do create(:channel_email, provider_config: { access_token: access_token, re...
Write RSpec test file for following ruby class ```ruby class Contacts::ContactableInboxesService pattr_initialize [:contact!] def get account = contact.account account.inboxes.filter_map { |inbox| get_contactable_inbox(inbox) } end private def get_contactable_inbox(inbox) case inbox.channel_typ...
require 'rails_helper' describe Contacts::ContactableInboxesService do before do stub_request(:post, /graph.facebook.com/) end let(:account) { create(:account) } let(:contact) { create(:contact, account: account, email: 'contact@example.com', phone_number: '+2320000') } let!(:twilio_sms) { create(:chann...
Write RSpec test file for following ruby class ```ruby class Contacts::FilterService < FilterService ATTRIBUTE_MODEL = 'contact_attribute'.freeze def perform @contacts = contact_query_builder { contacts: @contacts, count: @contacts.count } end def contact_query_builder contact_fil...
require 'rails_helper' describe Contacts::FilterService do subject(:filter_service) { described_class } let!(:account) { create(:account) } let!(:first_user) { create(:user, account: account) } let!(:second_user) { create(:user, account: account) } let!(:inbox) { create(:inbox, account: account, enable_auto...
Write RSpec test file for following ruby class ```ruby class Labels::UpdateService pattr_initialize [:new_label_title!, :old_label_title!, :account_id!] def perform tagged_conversations.find_in_batches do |conversation_batch| conversation_batch.each do |conversation| conversation.label_list.remov...
require 'rails_helper' describe Labels::UpdateService do let(:account) { create(:account) } let(:conversation) { create(:conversation, account: account) } let(:label) { create(:label, account: account) } let(:contact) { conversation.contact } before do conversation.label_list.add(label.title) conver...
Write RSpec test file for following ruby class ```ruby class Internal::RemoveStaleContactInboxesService def perform return unless remove_stale_contact_inbox_job_enabled? time_period = 90.days.ago contact_inboxes_to_delete = stale_contact_inboxes(time_period) log_stale_contact_inboxes_deletion(contac...
# spec/services/remove_stale_contact_inboxes_service_spec.rb require 'rails_helper' RSpec.describe Internal::RemoveStaleContactInboxesService do describe '#perform' do it 'does not delete stale contact inboxes if REMOVE_STALE_CONTACT_INBOX_JOB_STATUS is false' do # default value of REMOVE_STALE_CONTACT_IN...
Write RSpec test file for following ruby class ```ruby class AgentBots::ValidateBotService pattr_initialize [:agent_bot] def perform return true unless agent_bot.bot_type == 'csml' validate_csml_bot end private def csml_client @csml_client ||= CsmlEngine.new end def csml_bot_payload { ...
require 'rails_helper' describe AgentBots::ValidateBotService do describe '#perform' do it 'returns true if bot_type is not csml' do agent_bot = create(:agent_bot) valid = described_class.new(agent_bot: agent_bot).perform expect(valid).to be true end it 'returns true if validate csml r...
Write RSpec test file for following ruby class ```ruby class Macros::ExecutionService < ActionService def initialize(macro, conversation, user) super(conversation) @macro = macro @account = macro.account @user = user Current.user = user end def perform @macro.actions.each do |action| ...
require 'rails_helper' RSpec.describe Macros::ExecutionService, type: :service do let(:account) { create(:account) } let(:conversation) { create(:conversation, account: account) } let(:user) { create(:user, account: account) } let(:macro) { create(:macro, account: account) } let(:service) { described_class.n...
Write RSpec test file for following ruby class ```ruby class Facebook::SendOnFacebookService < Base::SendOnChannelService private def channel_class Channel::FacebookPage end def perform_reply send_message_to_facebook fb_text_message_params if message.content.present? send_message_to_facebook fb_at...
require 'rails_helper' describe Facebook::SendOnFacebookService do subject(:send_reply_service) { described_class.new(message: message) } before do allow(Facebook::Messenger::Subscriptions).to receive(:subscribe).and_return(true) allow(bot).to receive(:deliver).and_return({ recipient_id: '1008372609250235...
Write RSpec test file for following ruby class ```ruby # ref : https://developers.line.biz/en/docs/messaging-api/receiving-messages/#webhook-event-types # https://developers.line.biz/en/reference/messaging-api/#message-event class Line::IncomingMessageService include ::FileTypeHelper pattr_initialize [:inbox!, :pa...
require 'rails_helper' describe Line::IncomingMessageService do let!(:line_channel) { create(:channel_line) } let(:params) do { 'destination': '2342234234', 'events': [ { 'replyToken': '0f3779fba3b349968c5d07db31eab56f', 'type': 'message', 'mode': 'active', ...
Write RSpec test file for following ruby class ```ruby class Line::SendOnLineService < Base::SendOnChannelService private def channel_class Channel::Line end def perform_reply response = channel.client.push_message(message.conversation.contact_inbox.source_id, build_payload) return if response.bl...
require 'rails_helper' describe Line::SendOnLineService do describe '#perform' do let(:line_client) { double } let(:line_channel) { create(:channel_line) } let(:message) do create(:message, message_type: :outgoing, content: 'test', conversation: create(:conversation, inbox: l...
Write RSpec test file for following ruby class ```ruby class Conversations::FilterService < FilterService ATTRIBUTE_MODEL = 'conversation_attribute'.freeze def initialize(params, user, filter_account = nil) @account = filter_account || Current.account super(params, user) end def perform @conversat...
require 'rails_helper' describe Conversations::FilterService do subject(:filter_service) { described_class } let!(:account) { create(:account) } let!(:user_1) { create(:user, account: account) } let!(:user_2) { create(:user, account: account) } let!(:campaign_1) { create(:campaign, title: 'Test Campaign', a...
Write RSpec test file for following ruby class ```ruby class AutomationRules::ActionService < ActionService def initialize(rule, account, conversation) super(conversation) @rule = rule @account = account Current.executed_by = rule end def perform @rule.actions.each do |action| @conversa...
require 'rails_helper' RSpec.describe AutomationRules::ActionService do let(:account) { create(:account) } let(:agent) { create(:user, account: account) } let(:conversation) { create(:conversation, account: account) } let!(:rule) do create(:automation_rule, account: account, ac...
Write RSpec test file for following ruby class ```ruby require 'json' class AutomationRules::ConditionsFilterService < FilterService ATTRIBUTE_MODEL = 'contact_attribute'.freeze def initialize(rule, conversation = nil, options = {}) super([], nil) @rule = rule @conversation = conversation @account...
require 'rails_helper' RSpec.describe AutomationRules::ConditionsFilterService do let(:account) { create(:account) } let(:conversation) { create(:conversation, account: account) } let(:email_channel) { create(:channel_email, account: account) } let(:email_inbox) { create(:inbox, channel: email_channel, account...
Write RSpec test file for following ruby class ```ruby # Find the various telegram payload samples here: https://core.telegram.org/bots/webhooks#testing-your-bot-with-updates # https://core.telegram.org/bots/api#available-types class Telegram::UpdateMessageService pattr_initialize [:inbox!, :params!] def perform ...
require 'rails_helper' describe Telegram::UpdateMessageService do let!(:telegram_channel) { create(:channel_telegram) } let!(:update_params) do { 'update_id': 2_323_484, 'edited_message': { 'message_id': 48, 'from': { 'id': 512_313_123_171_248, 'is_bot': false, ...
Write RSpec test file for following ruby class ```ruby # Find the various telegram payload samples here: https://core.telegram.org/bots/webhooks#testing-your-bot-with-updates # https://core.telegram.org/bots/api#available-types class Telegram::IncomingMessageService include ::FileTypeHelper include ::Telegram::Par...
require 'rails_helper' describe Telegram::IncomingMessageService do before do stub_request(:any, /api.telegram.org/).to_return(headers: { content_type: 'application/json' }, body: {}.to_json, status: 200) stub_request(:get, 'https://chatwoot-assets.local/sample.png').to_return( status: 200, body:...