{"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass TagFollowingService\n def initialize(user=nil)\n @user = user\n end\n\n def create(name)\n name_normalized = ActsAsTaggableOn::Tag.normalize(name)\n raise ArgumentError, \"Name field null or empty\" if name_normalized.blank?\n\n tag = ActsAsTaggableOn::Tag.find_or_create_by(name: name_normalized)\n raise DuplicateTag if @user.tag_followings.exists?(tag_id: tag.id)\n\n tag_following = @user.tag_followings.new(tag_id: tag.id)\n raise \"Can't process tag entity\" unless tag_following.save\n\n tag\n end\n\n def find(name)\n name_normalized = ActsAsTaggableOn::Tag.normalize(name)\n ActsAsTaggableOn::Tag.find_or_create_by(name: name_normalized)\n end\n\n def destroy(id)\n tag_following = @user.tag_followings.find_by!(tag_id: id)\n tag_following.destroy\n end\n\n def destroy_by_name(name)\n name_normalized = ActsAsTaggableOn::Tag.normalize(name)\n followed_tag = @user.followed_tags.find_by!(name: name_normalized)\n destroy(followed_tag.id)\n end\n\n def index\n @user.followed_tags\n end\n\n class DuplicateTag < RuntimeError; end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe TagFollowingService do\n before do\n add_tag(\"tag1\", alice)\n add_tag(\"tag2\", alice)\n end\n\n describe \"#create\" do\n it \"Creates new tag with valid name\" do\n name = SecureRandom.uuid\n expect(alice.followed_tags.find_by(name: name)).to be_nil\n tag_data = tag_following_service(alice).create(name)\n expect(alice.followed_tags.find_by(name: name).name).to eq(name)\n expect(tag_data[\"name\"]).to eq(name)\n expect(tag_data[\"id\"]).to be_truthy\n expect(tag_data[\"taggings_count\"]).to eq(0)\n end\n\n it \"Throws error with empty tag\" do\n expect { tag_following_service(alice).create(nil) }.to raise_error(ArgumentError)\n expect { tag_following_service(alice).create(\"\") }.to raise_error(ArgumentError)\n expect { tag_following_service(alice).create(\"#\") }.to raise_error(ArgumentError)\n expect { tag_following_service(alice).create(\" \") }.to raise_error(ArgumentError)\n end\n\n it \"throws an error when trying to follow an already followed tag\" do\n name = SecureRandom.uuid\n tag_following_service.create(name)\n expect {\n tag_following_service.create(name)\n }.to raise_error TagFollowingService::DuplicateTag\n end\n end\n\n describe \"#destroy\" do\n it \"Deletes tag with valid name\" do\n name = SecureRandom.uuid\n add_tag(name, alice)\n expect(alice.followed_tags.find_by(name: name).name).to eq(name)\n expect(tag_following_service(alice).destroy_by_name(name)).to be_truthy\n expect(alice.followed_tags.find_by(name: name)).to be_nil\n end\n\n it \"Deletes tag with id\" do\n name = SecureRandom.uuid\n new_tag = add_tag(name, alice)\n expect(alice.followed_tags.find_by(name: name).name).to eq(name)\n expect(tag_following_service(alice).destroy(new_tag.tag_id)).to be_truthy\n expect(alice.followed_tags.find_by(name: name)).to be_nil\n end\n\n it \"Does nothing with tag that isn't already followed\" do\n original_length = alice.followed_tags.length\n expect {\n tag_following_service(alice).destroy_by_name(SecureRandom.uuid)\n }.to raise_error ActiveRecord::RecordNotFound\n expect {\n tag_following_service(alice).destroy(-1)\n }.to raise_error ActiveRecord::RecordNotFound\n expect(alice.followed_tags.length).to eq(original_length)\n end\n\n it \"Does nothing with empty tag name\" do\n original_length = alice.followed_tags.length\n expect {\n tag_following_service(alice).destroy_by_name(\"\")\n }.to raise_error ActiveRecord::RecordNotFound\n expect(alice.followed_tags.length).to eq(original_length)\n end\n end\n\n describe \"#index\" do\n it \"Returns user's list of tags\" do\n tags = tag_following_service(alice).index\n expect(tags.length).to eq(alice.followed_tags.length)\n end\n end\n\n private\n\n def tag_following_service(user=alice)\n TagFollowingService.new(user)\n end\n\n def add_tag(name, user)\n tag = ActsAsTaggableOn::Tag.find_or_create_by(name: name)\n tag_following = user.tag_followings.new(tag_id: tag.id)\n tag_following.save\n tag_following\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass AspectsMembershipService\n def initialize(user=nil)\n @user = user\n end\n\n def create(aspect_id, person_id)\n person = Person.find(person_id)\n aspect = @user.aspects.where(id: aspect_id).first\n raise ActiveRecord::RecordNotFound unless person.present? && aspect.present?\n\n contact = @user.share_with(person, aspect)\n raise I18n.t(\"aspects.add_to_aspect.failure\") if contact.blank?\n\n AspectMembership.where(contact_id: contact.id, aspect_id: aspect.id).first\n end\n\n def destroy_by_ids(aspect_id, contact_id)\n aspect = @user.aspects.where(id: aspect_id).first\n contact = @user.contacts.where(person_id: contact_id).first\n destroy(aspect, contact)\n end\n\n def destroy_by_membership_id(membership_id)\n aspect = @user.aspects.joins(:aspect_memberships).where(aspect_memberships: {id: membership_id}).first\n contact = @user.contacts.joins(:aspect_memberships).where(aspect_memberships: {id: membership_id}).first\n destroy(aspect, contact)\n end\n\n def contacts_in_aspect(aspect_id)\n order = [Arel.sql(\"contact_id IS NOT NULL DESC\"), \"profiles.first_name ASC\", \"profiles.last_name ASC\",\n \"profiles.diaspora_handle ASC\"]\n @user.aspects.find(aspect_id) # to provide better error code if aspect isn't correct\n contacts = @user.contacts.arel_table\n aspect_memberships = AspectMembership.arel_table\n @user.contacts.joins(\n contacts.join(aspect_memberships).on(\n aspect_memberships[:aspect_id].eq(aspect_id).and(\n aspect_memberships[:contact_id].eq(contacts[:id])\n )\n ).join_sources\n ).includes(person: :profile).order(order)\n end\n\n def all_contacts\n order = [\"profiles.first_name ASC\", \"profiles.last_name ASC\",\n \"profiles.diaspora_handle ASC\"]\n @user.contacts.includes(person: :profile).order(order)\n end\n\n private\n\n def destroy(aspect, contact)\n raise ActiveRecord::RecordNotFound unless aspect.present? && contact.present?\n\n raise Diaspora::NotMine unless @user.mine?(aspect) && @user.mine?(contact)\n\n membership = contact.aspect_memberships.where(aspect_id: aspect.id).first\n raise ActiveRecord::RecordNotFound if membership.blank?\n\n success = membership.destroy\n\n {success: success, membership: membership}\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe AspectsMembershipService do\n before do\n @alice_aspect1 = alice.aspects.first\n @alice_aspect2 = alice.aspects.create(name: \"another aspect\")\n @bob_aspect1 = bob.aspects.first\n end\n\n describe \"#create\" do\n context \"with valid IDs\" do\n it \"succeeds\" do\n membership = aspects_membership_service.create(@alice_aspect2.id, bob.person.id)\n expect(membership[:aspect_id]).to eq(@alice_aspect2.id)\n expect(@alice_aspect2.contacts.find_by(person_id: bob.person.id)).not_to be_nil\n end\n\n it \"fails if already in aspect\" do\n aspects_membership_service.create(@alice_aspect2.id, bob.person.id)\n expect {\n aspects_membership_service.create(@alice_aspect2.id, bob.person.id)\n }.to raise_error ActiveRecord::RecordNotUnique\n end\n end\n\n context \"with invalid IDs\" do\n it \"fails with invalid User ID\" do\n expect {\n aspects_membership_service.create(@alice_aspect2.id, -1)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"fails with invalid Aspect ID\" do\n expect {\n aspects_membership_service.create(-1, bob.person.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"fails with aspect ID that isn't user's\" do\n expect {\n aspects_membership_service.create(@bob_aspect1.id, eve.person.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n end\n\n describe \"#destroy\" do\n before do\n @membership = aspects_membership_service.create(@alice_aspect2.id, bob.person.id)\n end\n\n context \"with aspect\/user valid IDs\" do\n it \"succeeds if in aspect\" do\n aspects_membership_service.destroy_by_ids(@alice_aspect2.id, bob.person.id)\n expect(@alice_aspect2.contacts.find_by(person_id: bob.person.id)).to be_nil\n end\n\n it \"fails if not in aspect\" do\n expect {\n aspects_membership_service.destroy_by_ids(@alice_aspect2.id, eve.person.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n\n context \"with a membership ID\" do\n it \"succeeds if their membership\" do\n aspects_membership_service.destroy_by_membership_id(@membership.id)\n expect(@alice_aspect2.contacts.find_by(person_id: bob.person.id)).to be_nil\n end\n\n it \"fails if not their membership\" do\n expect {\n aspects_membership_service(eve).destroy_by_membership_id(@membership.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"fails if invalid membership ID\" do\n expect {\n aspects_membership_service(eve).destroy_by_membership_id(-1)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n\n context \"with invalid IDs\" do\n it \"fails with invalid User ID\" do\n expect {\n aspects_membership_service.destroy_by_ids(@alice_aspect2.id, -1)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"fails with invalid Aspect ID\" do\n expect {\n aspects_membership_service.destroy_by_ids(-1, eve.person.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"fails with aspect ID that isn't user's\" do\n expect {\n aspects_membership_service(eve).destroy_by_ids(@alice_aspect2.id, bob.person.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n end\n\n describe \"#list\" do\n before do\n aspects_membership_service.create(@alice_aspect2.id, bob.person.id)\n aspects_membership_service.create(@alice_aspect2.id, eve.person.id)\n @alice_aspect3 = alice.aspects.create(name: \"empty aspect\")\n end\n\n context \"with valid aspect ID\" do\n it \"returns users in full aspect\" do\n contacts = aspects_membership_service.contacts_in_aspect(@alice_aspect2.id)\n expect(contacts.length).to eq(2)\n expect(contacts.map {|c| c.person.guid }.sort).to eq([bob.person.guid, eve.person.guid].sort)\n end\n\n it \"returns empty array in empty aspect\" do\n contacts = aspects_membership_service.contacts_in_aspect(@alice_aspect3.id)\n expect(contacts.length).to eq(0)\n end\n end\n\n context \"with invalid aspect ID\" do\n it \"fails\" do\n expect {\n aspects_membership_service.contacts_in_aspect(-1)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n end\n\n describe \"#all_contacts\" do\n before do\n aspects_membership_service.create(@alice_aspect2.id, bob.person.id)\n aspects_membership_service.create(@alice_aspect2.id, eve.person.id)\n @alice_aspect3 = alice.aspects.create(name: \"empty aspect\")\n end\n\n it \"returns all user's contacts\" do\n contacts = aspects_membership_service.all_contacts\n expect(contacts.length).to eq(2)\n end\n end\n\n def aspects_membership_service(user=alice)\n AspectsMembershipService.new(user)\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass LikeService\n def initialize(user=nil)\n @user = user\n end\n\n def create_for_post(post_id)\n post = post_service.find!(post_id)\n user.like!(post)\n end\n\n def create_for_comment(comment_id)\n comment = comment_service.find!(comment_id)\n post_service.find!(comment.commentable_id) # checks implicit for visible posts\n user.like_comment!(comment)\n end\n\n def destroy(like_id)\n like = Like.find(like_id)\n if user.owns?(like)\n user.retract(like)\n true\n else\n false\n end\n end\n\n def find_for_post(post_id)\n likes = post_service.find!(post_id).likes\n user ? likes.order(Arel.sql(\"author_id = #{user.person.id} DESC\")) : likes\n end\n\n def find_for_comment(comment_id)\n comment = comment_service.find!(comment_id)\n post_service.find!(comment.post.id) # checks implicit for visible posts\n likes = comment.likes\n user ? likes.order(Arel.sql(\"author_id = #{user.person.id} DESC\")) : likes\n end\n\n def unlike_post(post_id)\n likes = post_service.find!(post_id).likes\n likes = likes.order(Arel.sql(\"author_id = #{user.person.id} DESC\"))\n if !likes.empty? && user.owns?(likes[0])\n user.retract(likes[0])\n true\n else\n false\n end\n end\n\n def unlike_comment(comment_id)\n likes = comment_service.find!(comment_id).likes\n likes = likes.order(Arel.sql(\"author_id = #{user.person.id} DESC\"))\n if !likes.empty? && user.owns?(likes[0])\n user.retract(likes[0])\n true\n else\n false\n end\n end\n\n private\n\n attr_reader :user\n\n def post_service\n @post_service ||= PostService.new(user)\n end\n\n def comment_service\n @comment_service ||= CommentService.new(user)\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe LikeService do\n let(:post) { alice.post(:status_message, text: \"hello\", to: alice.aspects.first) }\n let(:alice_comment) { CommentService.new(alice).create(post.id, \"This is a wonderful post\") }\n let(:bobs_comment) { CommentService.new(bob).create(post.id, \"My post was better than yours\") }\n\n describe \"#create_for_post\" do\n it \"creates a like on my own post\" do\n expect {\n LikeService.new(alice).create_for_post(post.id)\n }.not_to raise_error\n end\n\n it \"creates a like on a post of a contact\" do\n expect {\n LikeService.new(bob).create_for_post(post.id)\n }.not_to raise_error\n end\n\n it \"attaches the like to the post\" do\n like = LikeService.new(alice).create_for_post(post.id)\n expect(post.likes.first.id).to eq(like.id)\n end\n\n it \"fails if the post does not exist\" do\n expect {\n LikeService.new(bob).create_for_post(\"unknown id\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"fails if the user can't see the post\" do\n expect {\n LikeService.new(eve).create_for_post(post.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"fails if the user already liked the post\" do\n LikeService.new(alice).create_for_post(post.id)\n expect {\n LikeService.new(alice).create_for_post(post.id)\n }.to raise_error ActiveRecord::RecordInvalid\n end\n end\n\n describe \"#create_for_comment\" do\n it \"creates a like on a posts comment\" do\n expect {\n LikeService.new(alice).create_for_comment(alice_comment.id)\n }.not_to raise_error\n end\n\n it \"creates a like on someone else comment\" do\n expect {\n LikeService.new(alice).create_for_comment(bobs_comment.id)\n }.not_to raise_error\n end\n\n it \"attaches the like to the comment\" do\n like = LikeService.new(alice).create_for_comment(bobs_comment.id)\n expect(bobs_comment.likes.first.id).to eq(like.id)\n end\n\n it \"fails if comment does not exist\" do\n expect {\n LikeService.new(alice).create_for_comment(\"unknown_id\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"fails if user cant see post and its comments\" do\n expect {\n LikeService.new(eve).create_for_comment(bobs_comment.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"fails if user already liked the comment\" do\n LikeService.new(alice).create_for_comment(bobs_comment.id)\n expect {\n LikeService.new(alice).create_for_comment(bobs_comment.id)\n }.to raise_error ActiveRecord::RecordInvalid\n end\n end\n\n describe \"#destroy\" do\n context \"for post like\" do\n let(:like) { LikeService.new(bob).create_for_post(post.id) }\n\n it \"lets the user destroy their own like\" do\n result = LikeService.new(bob).destroy(like.id)\n expect(result).to be_truthy\n end\n\n it \"doesn't let the parent author destroy others likes\" do\n result = LikeService.new(alice).destroy(like.id)\n expect(result).to be_falsey\n end\n\n it \"doesn't let someone destroy others likes\" do\n result = LikeService.new(eve).destroy(like.id)\n expect(result).to be_falsey\n end\n\n it \"fails if the like doesn't exist\" do\n expect {\n LikeService.new(bob).destroy(\"unknown id\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n\n context \"for comment like\" do\n let(:like) { LikeService.new(bob).create_for_comment(alice_comment.id) }\n\n it \"let the user destroy its own comment like\" do\n result = LikeService.new(bob).destroy(like.id)\n expect(result).to be_truthy\n end\n\n it \"doesn't let the parent author destroy other comment likes\" do\n result = LikeService.new(alice).destroy(like.id)\n expect(result).to be_falsey\n end\n\n it \"fails if the like doesn't exist\" do\n expect {\n LikeService.new(alice).destroy(\"unknown id\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n end\n\n describe \"#find_for_post\" do\n context \"with user\" do\n it \"returns likes for a public post\" do\n post = alice.post(:status_message, text: \"hello\", public: true)\n like = LikeService.new(alice).create_for_post(post.id)\n expect(LikeService.new(eve).find_for_post(post.id)).to include(like)\n end\n\n it \"returns likes for a visible private post\" do\n like = LikeService.new(alice).create_for_post(post.id)\n expect(LikeService.new(bob).find_for_post(post.id)).to include(like)\n end\n\n it \"doesn't return likes for a private post the user can not see\" do\n LikeService.new(alice).create_for_post(post.id)\n expect {\n LikeService.new(eve).find_for_post(post.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"returns the user's like first\" do\n post = alice.post(:status_message, text: \"hello\", public: true)\n [alice, bob, eve].map {|user| LikeService.new(user).create_for_post(post.id) }\n\n [alice, bob, eve].each do |user|\n expect(\n LikeService.new(user).find_for_post(post.id).first.author.id\n ).to be user.person.id\n end\n end\n end\n\n context \"without user\" do\n it \"returns likes for a public post\" do\n post = alice.post(:status_message, text: \"hello\", public: true)\n like = LikeService.new(alice).create_for_post(post.id)\n expect(LikeService.new.find_for_post(post.id)).to include(like)\n end\n\n it \"doesn't return likes a for private post\" do\n LikeService.new(alice).create_for_post(post.id)\n expect {\n LikeService.new.find_for_post(post.id)\n }.to raise_error Diaspora::NonPublic\n end\n end\n\n it \"returns all likes of a post\" do\n post = alice.post(:status_message, text: \"hello\", public: true)\n likes = [alice, bob, eve].map {|user| LikeService.new(user).create_for_post(post.id) }\n\n expect(LikeService.new.find_for_post(post.id)).to match_array(likes)\n end\n end\n\n describe \"#find_for_comment\" do\n context \"with user\" do\n it \"returns likes for a public post comment\" do\n post = alice.post(:status_message, text: \"hello\", public: true)\n comment = CommentService.new(bob).create(post.id, \"Hello comment\")\n like = LikeService.new(alice).create_for_comment(comment.id)\n expect(LikeService.new(eve).find_for_comment(comment.id)).to include(like)\n end\n\n it \"returns likes for visible private post comments\" do\n comment = CommentService.new(bob).create(post.id, \"Hello comment\")\n like = LikeService.new(alice).create_for_comment(comment.id)\n expect(LikeService.new(bob).find_for_comment(comment.id)).to include(like)\n end\n\n it \"doesn't return likes for a posts comment the user can not see\" do\n expect {\n LikeService.new(eve).find_for_comment(alice_comment.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"returns the user's like first\" do\n post = alice.post(:status_message, text: \"hello\", public: true)\n comment = CommentService.new(alice).create(post.id, \"I like my own post\")\n\n [alice, bob, eve].map {|user| LikeService.new(user).create_for_comment(comment.id) }\n [alice, bob, eve].each do |user|\n expect(\n LikeService.new(user).find_for_comment(comment.id).first.author.id\n ).to be user.person.id\n end\n end\n end\n\n context \"without user\" do\n it \"returns likes for a comment on a public post\" do\n post = alice.post(:status_message, text: \"hello\", public: true)\n comment = CommentService.new(bob).create(post.id, \"I like my own post\")\n like = LikeService.new(alice).create_for_comment(comment.id)\n expect(\n LikeService.new.find_for_comment(comment.id)\n ).to include(like)\n end\n\n it \"doesn't return likes for a private post comment\" do\n LikeService.new(alice).create_for_comment(alice_comment.id)\n expect {\n LikeService.new.find_for_comment(alice_comment.id)\n }.to raise_error Diaspora::NonPublic\n end\n end\n end\n\n describe \"#unlike_post\" do\n before do\n LikeService.new(alice).create_for_post(post.id)\n end\n\n it \"removes the like to the post\" do\n LikeService.new(alice).unlike_post(post.id)\n expect(post.likes.length).to eq(0)\n end\n end\n\n describe \"#unlike_comment\" do\n it \"removes the like for a comment\" do\n comment = CommentService.new(alice).create(post.id, \"I like my own post\")\n LikeService.new(alice).create_for_comment(comment.id)\n expect(comment.likes.length).to eq(1)\n\n LikeService.new(alice).unlike_comment(comment.id)\n comment = CommentService.new(alice).find!(comment.id)\n expect(comment.likes.length).to eq(0)\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass StatusMessageCreationService\n include Rails.application.routes.url_helpers\n\n def initialize(user)\n @user = user\n end\n\n def create(params)\n validate_content(params)\n\n build_status_message(params).tap do |status_message|\n load_aspects(params[:aspect_ids]) unless status_message.public?\n add_attachments(status_message, params)\n status_message.save\n process(status_message, params[:services])\n end\n end\n\n private\n\n attr_reader :user, :aspects\n\n def validate_content(params)\n raise MissingContent unless params[:status_message][:text].present? || params[:photos].present?\n end\n\n def build_status_message(params)\n public = params[:public] || false\n user.build_post(:status_message, params[:status_message].merge(public: public))\n end\n\n def add_attachments(status_message, params)\n add_location(status_message, params[:location_address], params[:location_coords])\n add_poll(status_message, params)\n add_photos(status_message, params[:photos])\n end\n\n def add_location(status_message, address, coordinates)\n status_message.build_location(address: address, coordinates: coordinates) if address.present?\n end\n\n def add_poll(status_message, params)\n if params[:poll_question].present?\n status_message.build_poll(question: params[:poll_question])\n [*params[:poll_answers]].each do |poll_answer|\n answer = status_message.poll.poll_answers.build(answer: poll_answer)\n answer.poll = status_message.poll\n end\n end\n end\n\n def add_photos(status_message, photos)\n if photos.present?\n status_message.photos << Photo.where(id: photos, author_id: status_message.author_id)\n status_message.photos.each do |photo|\n photo.public = status_message.public\n photo.pending = false\n end\n end\n end\n\n def load_aspects(aspect_ids)\n @aspects = user.aspects_from_ids(aspect_ids)\n raise BadAspectsIDs if aspects.empty?\n end\n\n def process(status_message, services)\n add_to_streams(status_message) unless status_message.public?\n dispatch(status_message, services)\n end\n\n def add_to_streams(status_message)\n user.add_to_streams(status_message, aspects)\n status_message.photos.each {|photo| user.add_to_streams(photo, aspects) }\n end\n\n def dispatch(status_message, services)\n receiving_services = services ? Service.titles(services) : []\n status_message.filter_mentions # this is only required until changes from #6818 are deployed on every pod\n user.dispatch_post(status_message,\n url: short_post_url(status_message.guid, host: AppConfig.environment.url),\n service_types: receiving_services)\n end\n\n class BadAspectsIDs < RuntimeError\n end\n\n class MissingContent < RuntimeError\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe StatusMessageCreationService do\n describe \"#create\" do\n let(:aspect) { alice.aspects.first }\n let(:text) { \"I'm writing tests\" }\n let(:params) {\n {\n status_message: {text: text},\n aspect_ids: [aspect.id.to_s]\n }\n }\n\n it \"returns the created StatusMessage\" do\n status_message = StatusMessageCreationService.new(alice).create(params)\n expect(status_message).to_not be_nil\n expect(status_message.text).to eq(text)\n end\n\n context \"with aspect_ids\" do\n it \"creates aspect_visibilities for the StatusMessages\" do\n alice.aspects.create(name: \"another aspect\")\n\n status_message = StatusMessageCreationService.new(alice).create(params)\n expect(status_message.aspect_visibilities.map(&:aspect)).to eq([aspect])\n end\n\n it \"does not create aspect_visibilities if the post is public\" do\n status_message = StatusMessageCreationService.new(alice).create(params.merge(public: true))\n expect(status_message.aspect_visibilities).to be_empty\n end\n\n it \"raises exception if aspects_ids don't contain any applicable aspect identifiers\" do\n bad_ids = [Aspect.ids.max.next, bob.aspects.first.id].map(&:to_s)\n expect {\n StatusMessageCreationService.new(alice).create(params.merge(aspect_ids: bad_ids))\n }.to remain(StatusMessage, :count).and raise_error(StatusMessageCreationService::BadAspectsIDs)\n end\n end\n\n context \"with public\" do\n it \"it creates a private StatusMessage by default\" do\n status_message = StatusMessageCreationService.new(alice).create(params)\n expect(status_message.public).to be_falsey\n end\n\n it \"it creates a private StatusMessage\" do\n status_message = StatusMessageCreationService.new(alice).create(params.merge(public: false))\n expect(status_message.public).to be_falsey\n end\n\n it \"it creates a public StatusMessage\" do\n status_message = StatusMessageCreationService.new(alice).create(params.merge(public: true))\n expect(status_message.public).to be_truthy\n end\n end\n\n context \"with location\" do\n it \"it creates a location\" do\n location_params = {location_address: \"somewhere\", location_coords: \"1,2\"}\n status_message = StatusMessageCreationService.new(alice).create(params.merge(location_params))\n location = status_message.location\n expect(location.address).to eq(\"somewhere\")\n expect(location.lat).to eq(\"1\")\n expect(location.lng).to eq(\"2\")\n end\n\n it \"does not add a location without location params\" do\n status_message = StatusMessageCreationService.new(alice).create(params)\n expect(status_message.location).to be_nil\n end\n end\n\n context \"with poll\" do\n it \"it creates a poll\" do\n poll_params = {poll_question: \"something?\", poll_answers: %w(yes no maybe)}\n status_message = StatusMessageCreationService.new(alice).create(params.merge(poll_params))\n poll = status_message.poll\n expect(poll.question).to eq(\"something?\")\n expect(poll.poll_answers.size).to eq(3)\n poll_answers = poll.poll_answers.map(&:answer)\n expect(poll_answers).to include(\"yes\")\n expect(poll_answers).to include(\"no\")\n expect(poll_answers).to include(\"maybe\")\n end\n\n it \"does not add a poll without poll params\" do\n status_message = StatusMessageCreationService.new(alice).create(params)\n expect(status_message.poll).to be_nil\n end\n end\n\n context \"with photos\" do\n let(:photo1) {\n alice.build_post(:photo, pending: true, user_file: File.open(photo_fixture_name), to: aspect.id).tap(&:save!)\n }\n let(:photo2) {\n alice.build_post(:photo, pending: true, user_file: File.open(photo_fixture_name), to: aspect.id).tap(&:save!)\n }\n let(:photo_ids) { [photo1.id.to_s, photo2.id.to_s] }\n\n it \"it attaches all photos\" do\n status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids))\n photos = status_message.photos\n expect(photos.size).to eq(2)\n expect(photos.map(&:id).map(&:to_s)).to match_array(photo_ids)\n end\n\n it \"does not attach photos without photos param\" do\n status_message = StatusMessageCreationService.new(alice).create(params)\n expect(status_message.photos).to be_empty\n end\n\n context \"with aspect_ids\" do\n it \"it marks the photos as non-public if the post is non-public\" do\n status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids))\n status_message.photos.each do |photo|\n expect(photo.public).to be_falsey\n end\n end\n\n it \"creates aspect_visibilities for the Photo\" do\n alice.aspects.create(name: \"another aspect\")\n\n status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids))\n status_message.photos.each do |photo|\n expect(photo.aspect_visibilities.map(&:aspect)).to eq([aspect])\n end\n end\n\n it \"does not create aspect_visibilities if the post is public\" do\n status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids, public: true))\n status_message.photos.each do |photo|\n expect(photo.aspect_visibilities).to be_empty\n end\n end\n\n it \"sets pending to false on any attached photos\" do\n status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids))\n status_message.photos.each do |photo|\n expect(photo.reload.pending).to be_falsey\n end\n end\n end\n\n context \"with public\" do\n it \"it marks the photos as public if the post is public\" do\n status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids, public: true))\n status_message.photos.each do |photo|\n expect(photo.public).to be_truthy\n end\n end\n\n it \"sets pending to false on any attached photos\" do\n status_message = StatusMessageCreationService.new(alice).create(params.merge(photos: photo_ids, public: true))\n status_message.photos.each do |photo|\n expect(photo.reload.pending).to be_falsey\n end\n end\n end\n end\n\n context \"dispatch\" do\n it \"dispatches the StatusMessage\" do\n expect(alice).to receive(:dispatch_post).with(instance_of(StatusMessage), hash_including(service_types: []))\n StatusMessageCreationService.new(alice).create(params)\n end\n\n it \"dispatches the StatusMessage to services\" do\n expect(alice).to receive(:dispatch_post)\n .with(instance_of(StatusMessage),\n hash_including(service_types: array_including(%w[Services::Tumblr Services::Twitter])))\n StatusMessageCreationService.new(alice).create(params.merge(services: %w[twitter tumblr]))\n end\n\n context \"with mention\" do\n let(:text) { text_mentioning(eve) }\n\n # this is only required until changes from #6818 are deployed on every pod\n it \"filters out mentions from text attribute\" do\n status_message = StatusMessageCreationService.new(alice).create(params)\n expect(status_message.text).not_to include(eve.diaspora_handle)\n end\n end\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass PostService\n def initialize(user=nil)\n @user = user\n end\n\n def find(id)\n if user\n user.find_visible_shareable_by_id(Post, id)\n else\n Post.find_by_id_and_public(id, true)\n end\n end\n\n def find!(id_or_guid)\n if user\n find_non_public_by_guid_or_id_with_user!(id_or_guid)\n else\n find_public!(id_or_guid)\n end\n end\n\n def present_json\n PostPresenter.new(post, user)\n end\n\n def present_interactions_json\n PostInteractionPresenter.new(post, user)\n end\n\n def mark_user_notifications(post_id)\n return unless user\n mark_comment_reshare_like_notifications_read(post_id)\n mark_mention_notifications_read(post_id)\n end\n\n def destroy(post_id, private_allowed=true)\n post = if private_allowed\n find_non_public_by_guid_or_id_with_user!(post_id)\n else\n find_public!(post_id)\n end\n raise Diaspora::NotMine unless post.author == user.person\n\n user.retract(post)\n end\n\n def mentionable_in_comment(post_id, query)\n post = find!(post_id)\n Person\n .allowed_to_be_mentioned_in_a_comment_to(post)\n .where.not(id: user.person_id)\n .find_by_substring(query)\n .sort_for_mention_suggestion(post, user)\n .for_json\n .limit(15)\n end\n\n private\n\n attr_reader :user\n\n def find_public!(id_or_guid)\n Post.where(post_key(id_or_guid) => id_or_guid).first.tap do |post|\n raise ActiveRecord::RecordNotFound, \"could not find a post with id #{id_or_guid}\" unless post\n raise Diaspora::NonPublic unless post.public?\n end\n end\n\n def find_non_public_by_guid_or_id_with_user!(id_or_guid)\n user.find_visible_shareable_by_id(Post, id_or_guid, key: post_key(id_or_guid)).tap do |post|\n raise ActiveRecord::RecordNotFound, \"could not find a post with id #{id_or_guid} for user #{user.id}\" unless post\n end\n end\n\n # We can assume a guid is at least 16 characters long as we have guids set to hex(8) since we started using them.\n def post_key(id_or_guid)\n id_or_guid.to_s.length < 16 ? :id : :guid\n end\n\n def mark_comment_reshare_like_notifications_read(post_id)\n Notification.where(recipient_id: user.id, target_type: \"Post\", target_id: post_id, unread: true)\n .update_all(unread: false)\n end\n\n def mark_mention_notifications_read(post_id)\n mention_ids = Mention.where(\n mentions_container_id: post_id,\n mentions_container_type: \"Post\",\n person_id: user.person_id\n ).ids\n mention_ids.concat(mentions_in_comments_for_post(post_id).pluck(:id))\n\n Notification.where(recipient_id: user.id, target_type: \"Mention\", target_id: mention_ids, unread: true)\n .update_all(unread: false) if mention_ids.any?\n end\n\n def mentions_in_comments_for_post(post_id)\n Mention\n .joins(\"INNER JOIN comments ON mentions_container_id = comments.id AND mentions_container_type = 'Comment'\")\n .where(comments: {commentable_id: post_id, commentable_type: \"Post\"})\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe PostService do\n let(:post) { alice.post(:status_message, text: \"ohai\", to: alice.aspects.first) }\n let(:public) { alice.post(:status_message, text: \"hey\", public: true) }\n\n describe \"#find\" do\n context \"with user\" do\n it \"returns the post, if it is the users post\" do\n expect(PostService.new(alice).find(post.id)).to eq(post)\n end\n\n it \"returns the post, if the user can see the it\" do\n expect(PostService.new(bob).find(post.id)).to eq(post)\n end\n\n it \"returns the post, if it is public\" do\n expect(PostService.new(eve).find(public.id)).to eq(public)\n end\n\n it \"does not return the post, if the post cannot be found\" do\n expect(PostService.new(alice).find(\"unknown\")).to be_nil\n end\n\n it \"does not return the post, if user cannot see the post\" do\n expect(PostService.new(eve).find(post.id)).to be_nil\n end\n end\n\n context \"without user\" do\n it \"returns the post, if it is public\" do\n expect(PostService.new.find(public.id)).to eq(public)\n end\n\n it \"does not return the post, if the post is private\" do\n expect(PostService.new.find(post.id)).to be_nil\n end\n\n it \"does not return the post, if the post cannot be found\" do\n expect(PostService.new.find(\"unknown\")).to be_nil\n end\n end\n end\n\n describe \"#find!\" do\n context \"with user\" do\n it \"returns the post, if it is the users post\" do\n expect(PostService.new(alice).find!(post.id)).to eq(post)\n end\n\n it \"works with guid\" do\n expect(PostService.new(alice).find!(post.guid)).to eq(post)\n end\n\n it \"returns the post, if the user can see the it\" do\n expect(PostService.new(bob).find!(post.id)).to eq(post)\n end\n\n it \"returns the post, if it is public\" do\n expect(PostService.new(eve).find!(public.id)).to eq(public)\n end\n\n it \"RecordNotFound if the post cannot be found\" do\n expect {\n PostService.new(alice).find!(\"unknown\")\n }.to raise_error ActiveRecord::RecordNotFound, \"could not find a post with id unknown for user #{alice.id}\"\n end\n\n it \"RecordNotFound if user cannot see the post\" do\n expect {\n PostService.new(eve).find!(post.id)\n }.to raise_error ActiveRecord::RecordNotFound, \"could not find a post with id #{post.id} for user #{eve.id}\"\n end\n end\n\n context \"without user\" do\n it \"returns the post, if it is public\" do\n expect(PostService.new.find!(public.id)).to eq(public)\n end\n\n it \"works with guid\" do\n expect(PostService.new.find!(public.guid)).to eq(public)\n end\n\n it \"NonPublic if the post is private\" do\n expect {\n PostService.new.find!(post.id)\n }.to raise_error Diaspora::NonPublic\n end\n\n it \"RecordNotFound if the post cannot be found\" do\n expect {\n PostService.new.find!(\"unknown\")\n }.to raise_error ActiveRecord::RecordNotFound, \"could not find a post with id unknown\"\n end\n end\n\n context \"id\/guid switch\" do\n let(:public) { alice.post(:status_message, text: \"ohai\", public: true) }\n\n it \"assumes ids less than 16 chars are ids and not guids\" do\n post = Post.where(id: public.id)\n expect(Post).to receive(:where).with(hash_including(id: \"123456789012345\")).and_return(post).at_least(:once)\n PostService.new(alice).find!(\"123456789012345\")\n end\n\n it \"assumes ids more than (or equal to) 16 chars are actually guids\" do\n post = Post.where(guid: public.guid)\n expect(Post).to receive(:where).with(hash_including(guid: \"1234567890123456\")).and_return(post).at_least(:once)\n PostService.new(alice).find!(\"1234567890123456\")\n end\n end\n end\n\n describe \"#mark_user_notifications\" do\n let(:status_text) { text_mentioning(alice) }\n\n it \"marks a corresponding notifications as read\" do\n FactoryBot.create(:notification, recipient: alice, target: post, unread: true)\n FactoryBot.create(:notification, recipient: alice, target: post, unread: true)\n\n expect {\n PostService.new(alice).mark_user_notifications(post.id)\n }.to change(Notification.where(unread: true), :count).by(-2)\n end\n\n it \"marks a corresponding mention notification as read\" do\n mention_post = bob.post(:status_message, text: status_text, public: true)\n\n expect {\n PostService.new(alice).mark_user_notifications(mention_post.id)\n }.to change(Notification.where(unread: true), :count).by(-1)\n end\n\n it \"marks a corresponding mention in comment notification as read\" do\n notification = FactoryBot.create(:notification_mentioned_in_comment)\n status_message = notification.target.mentions_container.parent\n user = notification.recipient\n\n expect {\n PostService.new(user).mark_user_notifications(status_message.id)\n }.to change(Notification.where(unread: true), :count).by(-1)\n end\n\n it \"does not change the update_at date\/time for post notifications\" do\n notification = Timecop.travel(1.minute.ago) do\n FactoryBot.create(:notification, recipient: alice, target: post, unread: true)\n end\n\n expect {\n PostService.new(alice).mark_user_notifications(post.id)\n }.not_to change { Notification.where(id: notification.id).pluck(:updated_at) }\n end\n\n it \"does not change the update_at date\/time for mention notifications\" do\n mention_post = Timecop.travel(1.minute.ago) do\n bob.post(:status_message, text: status_text, public: true)\n end\n mention = mention_post.mentions.where(person_id: alice.person.id).first\n\n expect {\n PostService.new(alice).mark_user_notifications(post.id)\n }.not_to change { Notification.where(target_type: \"Mention\", target_id: mention.id).pluck(:updated_at) }\n end\n\n it \"does nothing without a user\" do\n expect_any_instance_of(PostService).not_to receive(:mark_comment_reshare_like_notifications_read).with(post.id)\n expect_any_instance_of(PostService).not_to receive(:mark_mention_notifications_read).with(post.id)\n PostService.new.mark_user_notifications(post.id)\n end\n end\n\n describe \"#destroy\" do\n it \"let a user delete his message\" do\n PostService.new(alice).destroy(post.id)\n expect(StatusMessage.find_by_id(post.id)).to be_nil\n end\n\n it \"sends a retraction on delete\" do\n expect(alice).to receive(:retract).with(post)\n PostService.new(alice).destroy(post.id)\n end\n\n it \"won't delete private post if explicitly unallowed\" do\n expect {\n PostService.new(alice).destroy(post.id, false)\n }.to raise_error Diaspora::NonPublic\n expect(StatusMessage.find_by(id: post.id)).not_to be_nil\n end\n\n it \"will not let you destroy posts visible to you but that you do not own\" do\n expect {\n PostService.new(bob).destroy(post.id)\n }.to raise_error Diaspora::NotMine\n expect(StatusMessage.find_by_id(post.id)).not_to be_nil\n end\n\n it \"will not let you destroy posts that are not visible to you\" do\n expect {\n PostService.new(eve).destroy(post.id)\n }.to raise_error(ActiveRecord::RecordNotFound)\n expect(StatusMessage.find_by_id(post.id)).not_to be_nil\n end\n end\n\n describe \"#mentionable_in_comment\" do\n describe \"semi-integration test\" do\n let(:post_author_attributes) { {first_name: \"Ro#{r_str}\"} }\n let(:post_author) { FactoryBot.create(:person, post_author_attributes) }\n let(:current_user) { FactoryBot.create(:user_with_aspect) }\n let(:post_service) { PostService.new(current_user) }\n\n shared_context \"with commenters and likers\" do\n # randomize ids of the created people so that the test doesn't pass just because of\n # the id sequence matched against the expected ordering\n let(:ids) { (1..4).map {|i| Person.maximum(:id) + i }.shuffle }\n\n before do\n # in case when post_author has't been instantiated before this context, specify id\n # in order to avoid id conflict with the people generated here\n post_author_attributes.merge!(id: ids.max + 1)\n end\n\n let!(:commenter1) {\n FactoryBot.create(:person, id: ids.shift, first_name: \"Ro1#{r_str}\").tap {|person|\n FactoryBot.create(:comment, author: person, post: post)\n }\n }\n\n let!(:commenter2) {\n FactoryBot.create(:person, id: ids.shift, first_name: \"Ro2#{r_str}\").tap {|person|\n FactoryBot.create(:comment, author: person, post: post)\n }\n }\n\n let!(:liker1) {\n FactoryBot.create(:person, id: ids.shift, first_name: \"Ro1#{r_str}\").tap {|person|\n FactoryBot.create(:like, author: person, target: post)\n }\n }\n\n let!(:liker2) {\n FactoryBot.create(:person, id: ids.shift, first_name: \"Ro2#{r_str}\").tap {|person|\n FactoryBot.create(:like, author: person, target: post)\n }\n }\n end\n\n shared_context \"with a current user's friend\" do\n let!(:current_users_friend) {\n FactoryBot.create(:person).tap {|friend|\n current_user.contacts.create!(\n person: friend,\n aspects: [current_user.aspects.first],\n sharing: true,\n receiving: true\n )\n }\n }\n end\n\n context \"with private post\" do\n let(:post) { FactoryBot.create(:status_message, text: \"ohai\", author: post_author) }\n\n context \"when the post doesn't have a visibility for the current user\" do\n it \"doesn't find a post and raises an exception\" do\n expect {\n post_service.mentionable_in_comment(post.id, \"Ro\")\n }.to raise_error(ActiveRecord::RecordNotFound)\n end\n end\n\n context \"when the post has a visibility for the current user\" do\n before do\n ShareVisibility.batch_import([current_user.id], post)\n end\n\n context \"with commenters and likers\" do\n include_context \"with commenters and likers\"\n\n it \"returns mention suggestions in the correct order\" do\n expected_suggestions = [\n post_author, commenter1, commenter2, liker1, liker2\n ]\n expect(post_service.mentionable_in_comment(post.id, \"Ro\")).to eq(expected_suggestions)\n end\n end\n\n context \"with a current user's friend\" do\n include_context \"with a current user's friend\"\n\n it \"doesn't include a contact\" do\n expect(post_service.mentionable_in_comment(post.id, current_users_friend.first_name)).to be_empty\n end\n end\n\n it \"doesn't include a non contact\" do\n expect(post_service.mentionable_in_comment(post.id, eve.person.first_name)).to be_empty\n end\n end\n end\n\n context \"with public post\" do\n let(:post) { FactoryBot.create(:status_message, text: \"ohai\", public: true, author: post_author) }\n\n context \"with commenters and likers and with a current user's friend\" do\n include_context \"with commenters and likers\"\n include_context \"with a current user's friend\"\n\n it \"returns mention suggestions in the correct order\" do\n result = post_service.mentionable_in_comment(post.id, \"Ro\").to_a\n expect(result.size).to be > 7\n # participants: post author, comments, likers\n expect(result[0..4]).to eq([post_author, commenter1, commenter2, liker1, liker2])\n # contacts\n expect(result[5]).to eq(current_users_friend)\n # non-contacts\n result[6..-1].each {|person|\n expect(person.contacts.where(user_id: current_user.id)).to be_empty\n expect(person.profile.first_name).to include(\"Ro\")\n }\n end\n\n it \"doesn't include people with non-matching names\" do\n commenter = FactoryBot.create(:person, first_name: \"RRR#{r_str}\")\n FactoryBot.create(:comment, author: commenter)\n liker = FactoryBot.create(:person, first_name: \"RRR#{r_str}\")\n FactoryBot.create(:like, author: liker)\n friend = FactoryBot.create(:person, first_name: \"RRR#{r_str}\")\n current_user.contacts.create!(\n person: friend,\n aspects: [current_user.aspects.first],\n sharing: true,\n receiving: true\n )\n\n result = post_service.mentionable_in_comment(post.id, \"Ro\")\n expect(result).not_to include(commenter)\n expect(result).not_to include(liker)\n expect(result).not_to include(friend)\n end\n end\n\n shared_examples \"current user can't mention themself\" do\n before do\n current_user.profile.update(first_name: \"Ro#{r_str}\")\n end\n\n it \"doesn't include current user\" do\n expect(post_service.mentionable_in_comment(post.id, \"Ro\")).not_to include(current_user.person)\n end\n end\n\n context \"when current user is a post author\" do\n let(:post_author) { current_user.person }\n\n include_examples \"current user can't mention themself\"\n end\n\n context \"current user is a participant\" do\n before do\n current_user.like!(post)\n current_user.comment!(post, \"hello\")\n end\n\n include_examples \"current user can't mention themself\"\n end\n\n context \"current user is a stranger matching a search pattern\" do\n include_examples \"current user can't mention themself\"\n end\n\n it \"doesn't fail when the post author doesn't match the requested pattern\" do\n expect(post_service.mentionable_in_comment(post.id, \"#{r_str}#{r_str}#{r_str}\")).to be_empty\n end\n\n it \"renders a commenter with multiple comments only once\" do\n person = FactoryBot.create(:person, first_name: \"Ro2#{r_str}\")\n 2.times { FactoryBot.create(:comment, author: person, post: post) }\n expect(post_service.mentionable_in_comment(post.id, person.first_name).length).to eq(1)\n end\n end\n end\n\n describe \"unit test\" do\n let(:post_service) { PostService.new(alice) }\n\n before do\n expect(post_service).to receive(:find!).and_return(post)\n end\n\n it \"calls Person.allowed_to_be_mentioned_in_a_comment_to\" do\n expect(Person).to receive(:allowed_to_be_mentioned_in_a_comment_to).with(post).and_call_original\n post_service.mentionable_in_comment(post.id, \"whatever\")\n end\n\n it \"calls Person.find_by_substring\" do\n expect(Person).to receive(:find_by_substring).with(\"whatever\").and_call_original\n post_service.mentionable_in_comment(post.id, \"whatever\")\n end\n\n it \"calls Person.sort_for_mention_suggestion\" do\n expect(Person).to receive(:sort_for_mention_suggestion).with(post, alice).and_call_original\n post_service.mentionable_in_comment(post.id, \"whatever\")\n end\n\n it \"calls Person.limit\" do\n 16.times {\n FactoryBot.create(:comment, author: FactoryBot.create(:person, first_name: \"Ro#{r_str}\"), post: post)\n }\n expect(post_service.mentionable_in_comment(post.id, \"Ro\").length).to eq(15)\n end\n\n it \"contains a constraint on a current user\" do\n expect(Person).to receive(:allowed_to_be_mentioned_in_a_comment_to) { Person.all }\n expect(Person).to receive(:find_by_substring) { Person.all }\n expect(Person).to receive(:sort_for_mention_suggestion) { Person.all }\n expect(post_service.mentionable_in_comment(post.id, alice.person.first_name))\n .not_to include(alice.person)\n end\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass NotificationService\n NOTIFICATION_TYPES = {\n Comment => [Notifications::MentionedInComment, Notifications::CommentOnPost, Notifications::AlsoCommented],\n Like => [Notifications::Liked, Notifications::LikedComment],\n StatusMessage => [Notifications::MentionedInPost],\n Conversation => [Notifications::PrivateMessage],\n Message => [Notifications::PrivateMessage],\n Reshare => [Notifications::Reshared],\n Contact => [Notifications::StartedSharing]\n }.freeze\n\n NOTIFICATIONS_JSON_TYPES = {\n \"also_commented\" => \"Notifications::AlsoCommented\",\n \"comment_on_post\" => \"Notifications::CommentOnPost\",\n \"liked\" => \"Notifications::Liked\",\n \"liked_comment\" => \"Notifications::LikedComment\",\n \"mentioned\" => \"Notifications::MentionedInPost\",\n \"mentioned_in_comment\" => \"Notifications::MentionedInComment\",\n \"reshared\" => \"Notifications::Reshared\",\n \"started_sharing\" => \"Notifications::StartedSharing\",\n \"contacts_birthday\" => \"Notifications::ContactsBirthday\"\n }.freeze\n\n NOTIFICATIONS_REVERSE_JSON_TYPES = NOTIFICATIONS_JSON_TYPES.invert.freeze\n\n def initialize(user=nil)\n @user = user\n end\n\n def index(unread_only=nil, only_after=nil)\n query_string = \"recipient_id = ? \"\n query_string += \"AND unread = true \" if unread_only\n where_clause = [query_string, @user.id]\n if only_after\n query_string += \" AND created_at >= ?\"\n where_clause = [query_string, @user.id, only_after]\n end\n Notification.where(where_clause).includes(:target, actors: :profile)\n end\n\n def get_by_guid(guid)\n Notification.where(recipient_id: @user.id, guid: guid).first\n end\n\n def update_status_by_guid(guid, is_read_status)\n notification = get_by_guid(guid)\n raise ActiveRecord::RecordNotFound unless notification\n\n notification.set_read_state(is_read_status)\n true\n end\n\n def notify(object, recipient_user_ids)\n notification_types(object).each {|type| type.notify(object, recipient_user_ids) }\n end\n\n private\n\n def notification_types(object)\n NOTIFICATION_TYPES.fetch(object.class, [])\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe NotificationService do\n describe \"notification interrelation\" do\n context \"with mention in comment\" do\n let(:status_message) {\n FactoryBot.create(:status_message, public: true, author: alice.person).tap {|status_message|\n eve.comment!(status_message, \"whatever\")\n }\n }\n\n let(:comment) {\n FactoryBot.create(\n :comment,\n author: bob.person,\n text: text_mentioning(alice, eve),\n post: status_message\n )\n }\n\n it \"sends only mention notification\" do\n [alice, eve].each do |user|\n expect(Workers::Mail::MentionedInComment).to receive(:perform_async).with(\n user.id,\n bob.person.id,\n *comment.mentions.where(person: user.person).ids\n )\n end\n\n expect {\n NotificationService.new.notify(comment, [])\n }.to change { Notification.where(recipient_id: alice).count }.by(1)\n .and change { Notification.where(recipient_id: eve).count }.by(1)\n\n [alice, eve].each do |user|\n expect(\n Notifications::MentionedInComment.where(target: comment.mentions, recipient_id: user.id)\n ).to exist\n\n expect(\n Notifications::CommentOnPost.where(target: comment.parent, recipient_id: user.id)\n ).not_to exist\n\n expect(\n Notifications::AlsoCommented.where(target: comment.parent, recipient_id: user.id)\n ).not_to exist\n end\n end\n\n context \"with \\\"mentioned in comment\\\" email turned off\" do\n before do\n alice.user_preferences.create(email_type: \"mentioned_in_comment\")\n eve.user_preferences.create(email_type: \"mentioned_in_comment\")\n end\n\n it \"calls appropriate mail worker instead\" do\n expect(Workers::Mail::MentionedInComment).not_to receive(:perform_async)\n\n expect(Workers::Mail::CommentOnPost).to receive(:perform_async).with(\n alice.id,\n bob.person.id,\n *comment.mentions.where(person: alice.person).ids\n )\n\n expect(Workers::Mail::AlsoCommented).to receive(:perform_async).with(\n eve.id,\n bob.person.id,\n *comment.mentions.where(person: eve.person).ids\n )\n\n NotificationService.new.notify(comment, [])\n end\n end\n end\n end\n\n describe \"query methods\" do\n before do\n @post = alice.post(\n :status_message,\n text: \"This is a status message\",\n public: true,\n to: \"all\"\n )\n @notification = FactoryBot.create(:notification, recipient: alice, target: @post)\n @service = NotificationService.new(alice)\n end\n\n describe \"#index\" do\n it \"gets all\" do\n notifications = @service.index\n expect(notifications.length).to eq(1)\n end\n\n it \"gets unread only\" do\n notifications = @service.index(true)\n expect(notifications.length).to eq(1)\n @notification.set_read_state(true)\n notifications = @service.index(true)\n expect(notifications.length).to eq(0)\n end\n\n it \"gets only after\" do\n notifications = @service.index(nil, (Time.current - 1.day))\n expect(notifications.length).to eq(1)\n @notification.set_read_state(true)\n notifications = @service.index(nil, (Time.current + 1.day))\n expect(notifications.length).to eq(0)\n end\n\n it \"combined filtering\" do\n notifications = @service.index(true, (Time.current - 1.day))\n expect(notifications.length).to eq(1)\n end\n end\n\n describe \"#show\" do\n it \"succeeds with valid GUID\" do\n notification = @service.get_by_guid(@notification.guid)\n expect(notification).not_to be_nil\n end\n end\n\n describe \"#update\" do\n it \"succeeds with valid GUID\" do\n expect(@service.update_status_by_guid(@notification.guid, true)).to be_truthy\n expect(@notification.reload.unread).to eq(false)\n expect(@service.update_status_by_guid(@notification.guid, false)).to be_truthy\n expect(@notification.reload.unread).to eq(true)\n end\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\n# Encapsulates logic of processing diaspora:\/\/ links\nclass DiasporaLinkService\n attr_reader :type, :author, :guid\n\n def initialize(link)\n @link = link.dup\n parse\n end\n\n def find_or_fetch_entity\n if type && guid\n entity_finder.find || fetch_entity\n elsif author\n find_or_fetch_person\n end\n end\n\n private\n\n attr_accessor :link\n\n def fetch_entity\n DiasporaFederation::Federation::Fetcher.fetch_public(author, type, guid)\n entity_finder.find\n rescue DiasporaFederation::Federation::Fetcher::NotFetchable\n nil\n end\n\n def entity_finder\n @entity_finder ||= Diaspora::EntityFinder.new(type, guid)\n end\n\n def find_or_fetch_person\n Person.find_or_fetch_by_identifier(author)\n rescue DiasporaFederation::Discovery::DiscoveryError\n nil\n end\n\n def normalize\n link.gsub!(%r{^web\\+diaspora:\/\/}, \"diaspora:\/\/\") ||\n link.gsub!(%r{^\/\/}, \"diaspora:\/\/\") ||\n %r{^diaspora:\/\/}.match(link) ||\n self.link = \"diaspora:\/\/#{link}\"\n end\n\n def parse\n normalize\n match = DiasporaFederation::Federation::DiasporaUrlParser::DIASPORA_URL_REGEX.match(link)\n if match\n @author, @type, @guid = match.captures\n else\n @author = %r{^diaspora:\/\/(#{Validation::Rule::DiasporaId::DIASPORA_ID_REGEX})$}u.match(link)&.captures&.first\n end\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe DiasporaLinkService do\n let(:service) { described_class.new(link) }\n\n describe \"#find_or_fetch_entity\" do\n context \"when entity is known\" do\n let(:post) { FactoryBot.create(:status_message) }\n let(:link) { \"diaspora:\/\/#{post.author.diaspora_handle}\/post\/#{post.guid}\" }\n\n it \"returns the entity\" do\n expect(service.find_or_fetch_entity).to eq(post)\n end\n end\n\n context \"when entity is unknown\" do\n let(:remote_person) { FactoryBot.create(:person) }\n let(:guid) { \"1234567890abcdef\" }\n let(:link) { \"diaspora:\/\/#{remote_person.diaspora_handle}\/post\/#{guid}\" }\n\n it \"fetches entity\" do\n expect(DiasporaFederation::Federation::Fetcher)\n .to receive(:fetch_public)\n .with(remote_person.diaspora_handle, \"post\", guid) {\n FactoryBot.create(:status_message, author: remote_person, guid: guid)\n }\n\n entity = service.find_or_fetch_entity\n expect(entity).to be_a(StatusMessage)\n expect(entity.guid).to eq(guid)\n expect(entity.author).to eq(remote_person)\n end\n\n it \"returns nil when entity is non fetchable\" do\n expect(DiasporaFederation::Federation::Fetcher)\n .to receive(:fetch_public)\n .with(remote_person.diaspora_handle, \"post\", guid)\n .and_raise(DiasporaFederation::Federation::Fetcher::NotFetchable)\n\n expect(service.find_or_fetch_entity).to be_nil\n end\n end\n\n context \"with invalid links\" do\n it \"returns nil when the link is invalid\" do\n service = described_class.new(\"web+diaspora:\/\/something_invalid\")\n expect(service.find_or_fetch_entity).to be_nil\n end\n\n it \"returns nil when the author is valid, but rest of the link is invalid\" do\n service = described_class.new(\"web+diaspora:\/\/#{alice.diaspora_handle}\/foo\/bar\")\n expect(service.find_or_fetch_entity).to be_nil\n end\n end\n\n context \"with only a diaspora ID\" do\n let(:person) { FactoryBot.create(:person) }\n let(:link) { \"diaspora:\/\/#{person.diaspora_handle}\" }\n\n it \"returns the person\" do\n expect(service.find_or_fetch_entity).to eq(person)\n end\n\n it \"returns nil when person is non fetchable\" do\n expect(Person).to receive(:find_or_fetch_by_identifier)\n .with(person.diaspora_handle).and_raise(DiasporaFederation::Discovery::DiscoveryError)\n\n expect(service.find_or_fetch_entity).to be_nil\n end\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass PollParticipationService\n def initialize(user)\n @user = user\n end\n\n def vote(post_id, answer_id)\n answer = PollAnswer.find(answer_id)\n @user.participate_in_poll!(target(post_id), answer) if target(post_id)\n end\n\n private\n\n def target(post_id)\n @target ||= @user.find_visible_shareable_by_id(Post, post_id) || raise(ActiveRecord::RecordNotFound.new)\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe PollParticipationService do\n let(:poll_post) { FactoryBot.create(:status_message_with_poll, public: true) }\n let(:poll_answer) { poll_post.poll.poll_answers.first }\n\n describe \"voting on poll\" do\n it \"succeeds\" do\n expect(poll_service.vote(poll_post.id, poll_answer.id)).not_to be_nil\n end\n\n it \"fails to vote twice\" do\n expect(poll_service.vote(poll_post.id, poll_answer.id)).not_to be_nil\n expect { poll_service.vote(poll_post.id, poll_answer.id) }.to raise_error(ActiveRecord::RecordInvalid)\n end\n\n it \"fails with bad answer id\" do\n expect { poll_service.vote(poll_post.id, -2) }.to raise_error(ActiveRecord::RecordNotFound)\n end\n\n it \"fails with bad post id\" do\n expect { poll_service.vote(-1, poll_answer.id) }.to raise_error(ActiveRecord::RecordNotFound)\n end\n end\n\n def poll_service(user=alice)\n PollParticipationService.new(user)\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass ReshareService\n def initialize(user=nil)\n @user = user\n end\n\n def create(post_id)\n post = post_service.find!(post_id)\n post = post.absolute_root if post.is_a? Reshare\n user.reshare!(post)\n end\n\n def find_for_post(post_id)\n reshares = post_service.find!(post_id).reshares\n user ? reshares.order(Arel.sql(\"author_id = #{user.person.id} DESC\")) : reshares\n end\n\n private\n\n attr_reader :user\n\n def post_service\n @post_service ||= PostService.new(user)\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe ReshareService do\n let(:post) { alice.post(:status_message, text: \"hello\", public: true) }\n\n describe \"#create\" do\n it \"doesn't create a reshare of my own post\" do\n expect {\n ReshareService.new(alice).create(post.id)\n }.to raise_error RuntimeError\n end\n\n it \"creates a reshare of a post of a contact\" do\n expect {\n ReshareService.new(bob).create(post.id)\n }.not_to raise_error\n end\n\n it \"attaches the reshare to the post\" do\n reshare = ReshareService.new(bob).create(post.id)\n expect(post.reshares.first.id).to eq(reshare.id)\n end\n\n it \"reshares the original post when called with a reshare\" do\n reshare = ReshareService.new(bob).create(post.id)\n reshare2 = ReshareService.new(eve).create(reshare.id)\n expect(post.reshares.map(&:id)).to include(reshare2.id)\n end\n\n it \"fails if the post does not exist\" do\n expect {\n ReshareService.new(bob).create(\"unknown id\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"fails if the post is not public\" do\n post = alice.post(:status_message, text: \"hello\", to: alice.aspects.first)\n\n expect {\n ReshareService.new(bob).create(post.id)\n }.to raise_error ActiveRecord::RecordInvalid\n end\n\n it \"fails if the user already reshared the post\" do\n ReshareService.new(bob).create(post.id)\n expect {\n ReshareService.new(bob).create(post.id)\n }.to raise_error ActiveRecord::RecordInvalid\n end\n\n it \"fails if the user already reshared the original post\" do\n reshare = ReshareService.new(bob).create(post.id)\n expect {\n ReshareService.new(bob).create(reshare.id)\n }.to raise_error ActiveRecord::RecordInvalid\n end\n end\n\n describe \"#find_for_post\" do\n context \"with user\" do\n it \"returns reshares for a public post\" do\n reshare = ReshareService.new(bob).create(post.id)\n expect(ReshareService.new(eve).find_for_post(post.id)).to include(reshare)\n end\n\n it \"returns reshares for a visible private post\" do\n post = alice.post(:status_message, text: \"hello\", to: alice.aspects.first)\n expect(ReshareService.new(bob).find_for_post(post.id)).to be_empty\n end\n\n it \"doesn't return reshares for a private post the user can not see\" do\n post = alice.post(:status_message, text: \"hello\", to: alice.aspects.first)\n expect {\n ReshareService.new(eve).find_for_post(post.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"returns the user's reshare first\" do\n [bob, eve].map {|user| ReshareService.new(user).create(post.id) }\n\n [bob, eve].each do |user|\n expect(\n ReshareService.new(user).find_for_post(post.id).first.author.id\n ).to be user.person.id\n end\n end\n end\n\n context \"without user\" do\n it \"returns reshares for a public post\" do\n reshare = ReshareService.new(bob).create(post.id)\n expect(ReshareService.new.find_for_post(post.id)).to include(reshare)\n end\n\n it \"doesn't return reshares a for private post\" do\n post = alice.post(:status_message, text: \"hello\", to: alice.aspects.first)\n expect {\n ReshareService.new.find_for_post(post.id)\n }.to raise_error Diaspora::NonPublic\n end\n end\n\n it \"returns all reshares of a post\" do\n reshares = [bob, eve].map {|user| ReshareService.new(user).create(post.id) }\n\n expect(ReshareService.new.find_for_post(post.id)).to match_array(reshares)\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass PhotoService\n def initialize(user=nil, deny_raw_files=true)\n @user = user\n @deny_raw_files = deny_raw_files\n end\n\n def visible_photo(photo_guid)\n Photo.owned_or_visible_by_user(@user).where(guid: photo_guid).first\n end\n\n def create_from_params_and_file(base_params, uploaded_file)\n photo_params = build_params(base_params)\n raise RuntimeError if @deny_raw_files && !confirm_uploaded_file_settings(uploaded_file)\n\n photo_params[:user_file] = uploaded_file\n photo = @user.build_post(:photo, photo_params)\n raise RuntimeError unless photo.save\n\n send_messages(photo, photo_params)\n update_profile_photo(photo) if photo_params[:set_profile_photo]\n\n photo\n end\n\n private\n\n def build_params(base_params)\n photo_params = base_params.permit(:pending, :set_profile_photo, aspect_ids: [])\n if base_params.permit(:aspect_ids)[:aspect_ids] == \"all\"\n photo_params[:aspect_ids] = @user.aspects.map(&:id)\n elsif photo_params[:aspect_ids].is_a?(Hash)\n photo_params[:aspect_ids] = params[:photo][:aspect_ids].values\n end\n photo_params\n end\n\n def confirm_uploaded_file_settings(uploaded_file)\n unless uploaded_file.is_a?(ActionDispatch::Http::UploadedFile) || uploaded_file.is_a?(Rack::Test::UploadedFile)\n return false\n end\n return false if uploaded_file.original_filename.empty?\n\n return false if uploaded_file.content_type.empty?\n\n true\n end\n\n def send_messages(photo, photo_params)\n send_to_streams(photo, photo_params) unless photo.pending && photo.public?\n\n @user.dispatch_post(photo, to: photo_params[:aspect_ids]) unless photo.pending\n end\n\n def update_profile_photo(photo)\n @user.update_profile(photo: photo)\n end\n\n def send_to_streams(photo, photo_params)\n aspects = @user.aspects_from_ids(photo_params[:aspect_ids])\n @user.add_to_streams(photo, aspects)\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe PhotoService do\n before do\n alice_eve_spec = alice.aspects.create(name: \"eve aspect\")\n alice.share_with(eve.person, alice_eve_spec)\n alice_bob_spec = alice.aspects.create(name: \"bob aspect\")\n alice.share_with(bob.person, alice_bob_spec)\n @alice_eve_photo = alice.post(:photo, pending: false, user_file: File.open(photo_fixture_name),\n to: alice_eve_spec.id)\n @alice_bob_photo = alice.post(:photo, pending: false, user_file: File.open(photo_fixture_name),\n to: alice_bob_spec.id)\n @alice_public_photo = alice.post(:photo, pending: false, user_file: File.open(photo_fixture_name), public: true)\n @bob_photo1 = bob.post(:photo, pending: true, user_file: File.open(photo_fixture_name), public: true)\n end\n\n describe \"visible_photo\" do\n it \"returns a user's photo\" do\n photo = photo_service.visible_photo(@bob_photo1.guid)\n expect(photo.guid).to eq(@bob_photo1.guid)\n end\n\n it \"returns another user's public photo\" do\n photo = photo_service.visible_photo(@alice_public_photo.guid)\n expect(photo.guid).to eq(@alice_public_photo.guid)\n end\n\n it \"returns another user's shared photo\" do\n photo = photo_service.visible_photo(@alice_bob_photo.guid)\n expect(photo.guid).to eq(@alice_bob_photo.guid)\n end\n\n it \"returns nil for other user's private photo\" do\n photo = photo_service.visible_photo(@alice_eve_photo.guid)\n expect(photo).to be_nil\n end\n end\n\n describe \"create\" do\n before do\n @image_file = Rack::Test::UploadedFile.new(Rails.root.join(\"spec\", \"fixtures\", \"button.png\").to_s, \"image\/png\")\n end\n\n context \"succeeds\" do\n it \"accepts a photo from a regular form uploaded file no parameters\" do\n params = ActionController::Parameters.new\n photo = photo_service.create_from_params_and_file(params, @image_file)\n expect(photo).not_to be_nil\n expect(photo.pending?).to be_falsey\n expect(photo.public?).to be_falsey\n end\n\n it \"honors pending\" do\n params = ActionController::Parameters.new(pending: true)\n photo = photo_service.create_from_params_and_file(params, @image_file)\n expect(photo).not_to be_nil\n expect(photo.pending?).to be_truthy\n expect(photo.public?).to be_falsey\n end\n\n it \"sets a user profile when requested\" do\n original_profile_pic = bob.person.profile.image_url\n params = ActionController::Parameters.new(set_profile_photo: true)\n photo = photo_service.create_from_params_and_file(params, @image_file)\n expect(photo).not_to be_nil\n expect(bob.reload.person.profile.image_url).not_to eq(original_profile_pic)\n end\n\n it \"has correct aspects settings for limited shared\" do\n params = ActionController::Parameters.new(pending: false, aspect_ids: [bob.aspects.first.id])\n photo = photo_service.create_from_params_and_file(params, @image_file)\n expect(photo).not_to be_nil\n expect(photo.pending?).to be_falsey\n expect(photo.public?).to be_falsey\n end\n\n it \"allow raw file if explicitly allowing\" do\n params = ActionController::Parameters.new\n photo = photo_service(bob, false).create_from_params_and_file(params, uploaded_photo)\n expect(photo).not_to be_nil\n end\n end\n\n context \"fails\" do\n before do\n @params = ActionController::Parameters.new\n end\n\n it \"fails if given a raw file\" do\n expect {\n photo_service.create_from_params_and_file(@params, uploaded_photo)\n }.to raise_error RuntimeError\n end\n\n it \"file type isn't an image\" do\n text_file = Rack::Test::UploadedFile.new(Rails.root.join(\"README.md\").to_s, \"text\/plain\")\n expect {\n photo_service.create_from_params_and_file(@params, text_file)\n }.to raise_error CarrierWave::IntegrityError\n\n text_file = Rack::Test::UploadedFile.new(Rails.root.join(\"README.md\").to_s, \"image\/png\")\n expect {\n photo_service.create_from_params_and_file(@params, text_file)\n }.to raise_error CarrierWave::IntegrityError\n end\n end\n end\n\n def photo_service(user=bob, deny_raw_files=true)\n PhotoService.new(user, deny_raw_files)\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass ConversationService\n def initialize(user=nil)\n @user = user\n end\n\n def all_for_user(filter={})\n conversation_filter = {}\n unless filter[:only_after].nil?\n conversation_filter = \\\n \"conversations.created_at >= ?\", filter[:only_after]\n end\n\n visibility_filter = if filter[:unread]\n {\n person_id: @user.person_id,\n unread: 1\n }\n else\n {person_id: @user.person_id}\n end\n\n Conversation.where(conversation_filter)\n .joins(:conversation_visibilities)\n .where(conversation_visibilities: visibility_filter)\n .all\n end\n\n def build(subject, text, recipients)\n person_ids = @user.contacts\n .mutual\n .where(person_id: recipients)\n .pluck(:person_id)\n\n opts = {\n subject: subject,\n message: {text: text},\n participant_ids: person_ids\n }\n\n @user.build_conversation(opts)\n end\n\n def find!(conversation_guid)\n conversation = Conversation.find_by!(guid: conversation_guid)\n @user.conversations\n .joins(:conversation_visibilities)\n .where(conversation_visibilities: {\n person_id: @user.person_id,\n conversation_id: conversation.id\n }).first!\n end\n\n def destroy!(conversation_guid)\n conversation = find!(conversation_guid)\n conversation.destroy!\n end\n\n def get_visibility(conversation_guid)\n conversation = find!(conversation_guid)\n ConversationVisibility.where(\n person_id: @user.person.id,\n conversation_id: conversation.id\n ).first!\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe ConversationService do\n before do\n opts = {\n subject: \"conversation subject\",\n message: {text: \"conversation text\"},\n participant_ids: [bob.person.id]\n }\n @conversation = alice.build_conversation(opts)\n @conversation.created_at = 2.hours.ago\n @conversation.save!\n end\n\n describe \"#all_for_user\" do\n before do\n opts = {\n subject: \"conversation subject 2\",\n message: {text: \"conversation text 2\"},\n participant_ids: [bob.person.id]\n }\n @conversation = alice.build_conversation(opts)\n @conversation.created_at = 1.hour.ago\n @conversation.save!\n @date = @conversation.created_at\n opts = {\n subject: \"conversation subject 3\",\n message: {text: \"conversation text 3\"},\n participant_ids: []\n }\n @conversation = bob.build_conversation(opts)\n @conversation.save!\n end\n\n it \"returns all conversations\" do\n expect(alice_conversation_service.all_for_user.length).to eq(2)\n expect(bob_conversation_service.all_for_user.length).to eq(3)\n end\n\n it \"returns all unread conversations\" do\n @conversation.conversation_visibilities[0].unread = true\n @conversation.conversation_visibilities[0].save!\n conversations = bob_conversation_service.all_for_user(unread: true)\n expect(conversations.length).to eq(1)\n end\n\n it \"returns conversation after a given date\" do\n conversations = bob_conversation_service.all_for_user(only_after: @date)\n expect(conversations.length).to eq(2)\n end\n end\n\n describe \"#find!\" do\n it \"returns the conversation, if it is the user's conversation\" do\n expect(bob_conversation_service.find!(@conversation.guid)).to eq(\n @conversation\n )\n end\n\n it \"returns the conversation, if the user is recipient\" do\n expect(bob_conversation_service.find!(@conversation.guid)).to eq(\n @conversation\n )\n end\n\n it \"raises RecordNotFound if the conversation cannot be found\" do\n expect {\n alice_conversation_service.find!(\"unknown\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"raises RecordNotFound if the user is not recipient\" do\n expect {\n eve_conversation_service.find!(@conversation.guid)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n\n describe \"#build\" do\n it \"creates the conversation for given user and recipients\" do\n new_conversation = alice_conversation_service.build(\n \"subject test\",\n \"message test\",\n [bob.person.id]\n )\n expect(new_conversation.subject).to eq(\"subject test\")\n expect(new_conversation.author_id).to eq(alice.person.id)\n expect(new_conversation.messages[0].text).to eq(\"message test\")\n expect(new_conversation.messages[0].author_id).to eq(alice.person.id)\n expect(new_conversation.participants.length).to eq(2)\n end\n\n it \"doesn't add recipients if they are not user contacts\" do\n new_conversation = alice_conversation_service.build(\n \"subject test\",\n \"message test\",\n [bob.person.id, eve.person.id]\n )\n expect(new_conversation.participants.length).to eq(2)\n expect(new_conversation.messages[0].text).to eq(\"message test\")\n expect(new_conversation.messages[0].author_id).to eq(alice.person.id)\n end\n end\n\n describe \"#get_visibility\" do\n it \"returns visibility for current user\" do\n visibility = alice_conversation_service.get_visibility(\n @conversation.guid\n )\n expect(visibility).to_not be_nil\n end\n\n it \"raises RecordNotFound if the user has no visibility\" do\n expect {\n eve_conversation_service.get_visibility(@conversation.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n\n describe \"#destroy!\" do\n it \"deletes the conversation, when it is the user conversation\" do\n alice_conversation_service.destroy!(@conversation.guid)\n expect {\n alice_conversation_service.find!(@conversation.guid)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"raises RecordNotFound if the conversation cannot be found\" do\n expect {\n alice_conversation_service.destroy!(\"unknown\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"raises RecordNotFound if the user is not part of the conversation\" do\n expect {\n eve_conversation_service.destroy!(@conversation.guid)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n\n def alice_conversation_service\n ConversationService.new(alice)\n end\n\n def bob_conversation_service\n ConversationService.new(bob)\n end\n\n def eve_conversation_service\n ConversationService.new(eve)\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass CommentService\n def initialize(user=nil)\n @user = user\n end\n\n def create(post_id, text)\n post = post_service.find!(post_id)\n user.comment!(post, text)\n end\n\n def find_for_post(post_id)\n post_service.find!(post_id).comments.for_a_stream\n end\n\n def find!(id_or_guid)\n Comment.find_by!(comment_key(id_or_guid) => id_or_guid)\n end\n\n def destroy(comment_id)\n comment = Comment.find(comment_id)\n if user.owns?(comment) || user.owns?(comment.parent)\n user.retract(comment)\n true\n else\n false\n end\n end\n\n def destroy!(comment_guid)\n comment = find!(comment_guid)\n if user.owns?(comment)\n user.retract(comment)\n elsif user.owns?(comment.parent)\n user.retract(comment)\n elsif comment\n raise ActiveRecord::RecordInvalid\n else\n raise ActiveRecord::RecordNotFound\n end\n end\n\n private\n\n attr_reader :user\n\n # We can assume a guid is at least 16 characters long as we have guids set to hex(8) since we started using them.\n def comment_key(id_or_guid)\n id_or_guid.to_s.length < 16 ? :id : :guid\n end\n\n def post_service\n @post_service ||= PostService.new(user)\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\ndescribe CommentService do\n let(:post) { alice.post(:status_message, text: \"hello\", to: alice.aspects.first) }\n\n describe \"#create\" do\n it \"creates a comment on my own post\" do\n comment = CommentService.new(alice).create(post.id, \"hi\")\n expect(comment.text).to eq(\"hi\")\n end\n\n it \"creates a comment on post of a contact\" do\n comment = CommentService.new(bob).create(post.id, \"hi\")\n expect(comment.text).to eq(\"hi\")\n end\n\n it \"attaches the comment to the post\" do\n comment = CommentService.new(alice).create(post.id, \"hi\")\n expect(post.comments.first.text).to eq(\"hi\")\n expect(post.comments.first.id).to eq(comment.id)\n end\n\n it \"fail if the post does not exist\" do\n expect {\n CommentService.new(alice).create(\"unknown id\", \"hi\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n\n it \"fail if the user can not see the post\" do\n expect {\n CommentService.new(eve).create(post.id, \"hi\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n\n describe \"#find!\" do\n let(:comment) { CommentService.new(bob).create(post.id, \"hi\") }\n\n it \"returns comment\" do\n result = CommentService.new(bob).find!(comment.guid)\n expect(result.id).to eq(comment.id)\n end\n\n it \"raises exception the comment does not exist\" do\n expect {\n CommentService.new(bob).find!(\"unknown id\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n\n describe \"#destroy\" do\n let(:comment) { CommentService.new(bob).create(post.id, \"hi\") }\n\n it \"lets the user destroy his own comment\" do\n result = CommentService.new(bob).destroy(comment.id)\n expect(result).to be_truthy\n end\n\n it \"lets the parent author destroy others comment\" do\n result = CommentService.new(alice).destroy(comment.id)\n expect(result).to be_truthy\n end\n\n it \"does not let someone destroy others comment\" do\n result = CommentService.new(eve).destroy(comment.id)\n expect(result).to be_falsey\n end\n\n it \"fails if the comment does not exist\" do\n expect {\n CommentService.new(bob).destroy(\"unknown id\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n\n describe \"#destroy!\" do\n let(:comment) { CommentService.new(bob).create(post.id, \"hi\") }\n\n it \"lets the user destroy his own comment\" do\n result = CommentService.new(bob).destroy!(comment.guid)\n expect(result).to be_truthy\n end\n\n it \"lets the parent author destroy others comment\" do\n result = CommentService.new(alice).destroy!(comment.guid)\n expect(result).to be_truthy\n end\n\n it \"does not let someone destroy others comment\" do\n expect {\n CommentService.new(eve).destroy!(comment.guid)\n }.to raise_error ActiveRecord::RecordInvalid\n end\n\n it \"raises exception the comment does not exist\" do\n expect {\n CommentService.new(bob).destroy!(\"unknown id\")\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n\n describe \"#find_for_post\" do\n context \"with user\" do\n it \"returns comments for a public post\" do\n post = alice.post(:status_message, text: \"hello\", public: true)\n comment = CommentService.new(alice).create(post.id, \"hi\")\n expect(CommentService.new(eve).find_for_post(post.id)).to include(comment)\n end\n\n it \"returns comments for a visible private post\" do\n comment = CommentService.new(alice).create(post.id, \"hi\")\n expect(CommentService.new(bob).find_for_post(post.id)).to include(comment)\n end\n\n it \"does not return comments for private post the user can not see\" do\n expect {\n CommentService.new(eve).find_for_post(post.id)\n }.to raise_error ActiveRecord::RecordNotFound\n end\n end\n\n context \"without user\" do\n it \"returns comments for a public post\" do\n post = alice.post(:status_message, text: \"hello\", public: true)\n comment = CommentService.new(alice).create(post.id, \"hi\")\n expect(CommentService.new.find_for_post(post.id)).to include(comment)\n end\n\n it \"does not return comments for private post\" do\n expect {\n CommentService.new.find_for_post(post.id)\n }.to raise_error Diaspora::NonPublic\n end\n end\n\n it \"returns all comments of a post\" do\n post = alice.post(:status_message, text: \"hello\", public: true)\n comments = [alice, bob, eve].map {|user| CommentService.new(user).create(post.id, \"hi\") }\n\n expect(CommentService.new.find_for_post(post.id)).to match_array(comments)\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nrequire 'csv'\n\n# NOTE: This is a deprecated service, only kept to not break ongoing imports\n# on upgrade. See `BulkImportService` for its replacement.\n\nclass ImportService < BaseService\n ROWS_PROCESSING_LIMIT = 20_000\n\n def call(import)\n @import = import\n @account = @import.account\n\n case @import.type\n when 'following'\n import_follows!\n when 'blocking'\n import_blocks!\n when 'muting'\n import_mutes!\n when 'domain_blocking'\n import_domain_blocks!\n when 'bookmarks'\n import_bookmarks!\n end\n end\n\n private\n\n def import_follows!\n parse_import_data!(['Account address'])\n import_relationships!('follow', 'unfollow', @account.following, ROWS_PROCESSING_LIMIT, reblogs: { header: 'Show boosts', default: true }, notify: { header: 'Notify on new posts', default: false }, languages: { header: 'Languages', default: nil })\n end\n\n def import_blocks!\n parse_import_data!(['Account address'])\n import_relationships!('block', 'unblock', @account.blocking, ROWS_PROCESSING_LIMIT)\n end\n\n def import_mutes!\n parse_import_data!(['Account address'])\n import_relationships!('mute', 'unmute', @account.muting, ROWS_PROCESSING_LIMIT, notifications: { header: 'Hide notifications', default: true })\n end\n\n def import_domain_blocks!\n parse_import_data!(['#domain'])\n items = @data.take(ROWS_PROCESSING_LIMIT).map { |row| row['#domain'].strip }\n\n if @import.overwrite?\n presence_hash = items.index_with(true)\n\n @account.domain_blocks.find_each do |domain_block|\n if presence_hash[domain_block.domain]\n items.delete(domain_block.domain)\n else\n @account.unblock_domain!(domain_block.domain)\n end\n end\n end\n\n items.each do |domain|\n @account.block_domain!(domain)\n end\n\n AfterAccountDomainBlockWorker.push_bulk(items) do |domain|\n [@account.id, domain]\n end\n end\n\n def import_relationships!(action, undo_action, overwrite_scope, limit, extra_fields = {})\n local_domain_suffix = \"@#{Rails.configuration.x.local_domain}\"\n items = @data.take(limit).map { |row| [row['Account address']&.strip&.delete_suffix(local_domain_suffix), extra_fields.to_h { |key, field_settings| [key, row[field_settings[:header]]&.strip || field_settings[:default]] }] }.reject { |(id, _)| id.blank? }\n\n if @import.overwrite?\n presence_hash = items.each_with_object({}) { |(id, extra), mapping| mapping[id] = [true, extra] }\n\n overwrite_scope.reorder(nil).find_each do |target_account|\n if presence_hash[target_account.acct]\n items.delete(target_account.acct)\n extra = presence_hash[target_account.acct][1]\n Import::RelationshipWorker.perform_async(@account.id, target_account.acct, action, extra.stringify_keys)\n else\n Import::RelationshipWorker.perform_async(@account.id, target_account.acct, undo_action)\n end\n end\n end\n\n head_items = items.uniq { |acct, _| acct.split('@')[1] }\n tail_items = items - head_items\n\n Import::RelationshipWorker.push_bulk(head_items + tail_items) do |acct, extra|\n [@account.id, acct, action, extra.stringify_keys]\n end\n end\n\n def import_bookmarks!\n parse_import_data!(['#uri'])\n items = @data.take(ROWS_PROCESSING_LIMIT).map { |row| row['#uri'].strip }\n\n if @import.overwrite?\n presence_hash = items.index_with(true)\n\n @account.bookmarks.find_each do |bookmark|\n if presence_hash[bookmark.status.uri]\n items.delete(bookmark.status.uri)\n else\n bookmark.destroy!\n end\n end\n end\n\n statuses = items.filter_map do |uri|\n status = ActivityPub::TagManager.instance.uri_to_resource(uri, Status)\n next if status.nil? && ActivityPub::TagManager.instance.local_uri?(uri)\n\n status || ActivityPub::FetchRemoteStatusService.new.call(uri)\n rescue HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::UnexpectedResponseError\n nil\n rescue => e\n Rails.logger.warn \"Unexpected error when importing bookmark: #{e}\"\n nil\n end\n\n account_ids = statuses.map(&:account_id)\n preloaded_relations = @account.relations_map(account_ids, skip_blocking_and_muting: true)\n\n statuses.keep_if { |status| StatusPolicy.new(@account, status, preloaded_relations).show? }\n\n statuses.each do |status|\n @account.bookmarks.find_or_create_by!(account: @account, status: status)\n end\n end\n\n def parse_import_data!(default_headers)\n data = CSV.parse(import_data, headers: true)\n data = CSV.parse(import_data, headers: default_headers) unless data.headers&.first&.strip&.include?(' ')\n @data = data.compact_blank\n end\n\n def import_data\n Paperclip.io_adapters.for(@import.data).read.force_encoding(Encoding::UTF_8)\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe ImportService, type: :service do\n include RoutingHelper\n\n let!(:account) { Fabricate(:account, locked: false) }\n let!(:bob) { Fabricate(:account, username: 'bob', locked: false) }\n let!(:eve) { Fabricate(:account, username: 'eve', domain: 'example.com', locked: false, protocol: :activitypub, inbox_url: 'https:\/\/example.com\/inbox') }\n\n before do\n stub_request(:post, 'https:\/\/example.com\/inbox').to_return(status: 200)\n end\n\n context 'when importing old-style list of muted users' do\n subject { described_class.new }\n\n let(:csv) { attachment_fixture('mute-imports.txt') }\n\n describe 'when no accounts are muted' do\n let(:import) { Import.create(account: account, type: 'muting', data: csv) }\n\n it 'mutes the listed accounts, including notifications' do\n subject.call(import)\n expect(account.muting.count).to eq 2\n expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true\n end\n end\n\n describe 'when some accounts are muted and overwrite is not set' do\n let(:import) { Import.create(account: account, type: 'muting', data: csv) }\n\n it 'mutes the listed accounts, including notifications' do\n account.mute!(bob, notifications: false)\n subject.call(import)\n expect(account.muting.count).to eq 2\n expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true\n end\n end\n\n describe 'when some accounts are muted and overwrite is set' do\n let(:import) { Import.create(account: account, type: 'muting', data: csv, overwrite: true) }\n\n it 'mutes the listed accounts, including notifications' do\n account.mute!(bob, notifications: false)\n subject.call(import)\n expect(account.muting.count).to eq 2\n expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true\n end\n end\n end\n\n context 'when importing new-style list of muted users' do\n subject { described_class.new }\n\n let(:csv) { attachment_fixture('new-mute-imports.txt') }\n\n describe 'when no accounts are muted' do\n let(:import) { Import.create(account: account, type: 'muting', data: csv) }\n\n it 'mutes the listed accounts, respecting notifications' do\n subject.call(import)\n expect(account.muting.count).to eq 2\n expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true\n expect(Mute.find_by(account: account, target_account: eve).hide_notifications).to be false\n end\n end\n\n describe 'when some accounts are muted and overwrite is not set' do\n let(:import) { Import.create(account: account, type: 'muting', data: csv) }\n\n it 'mutes the listed accounts, respecting notifications' do\n account.mute!(bob, notifications: true)\n subject.call(import)\n expect(account.muting.count).to eq 2\n expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true\n expect(Mute.find_by(account: account, target_account: eve).hide_notifications).to be false\n end\n end\n\n describe 'when some accounts are muted and overwrite is set' do\n let(:import) { Import.create(account: account, type: 'muting', data: csv, overwrite: true) }\n\n it 'mutes the listed accounts, respecting notifications' do\n account.mute!(bob, notifications: true)\n subject.call(import)\n expect(account.muting.count).to eq 2\n expect(Mute.find_by(account: account, target_account: bob).hide_notifications).to be true\n expect(Mute.find_by(account: account, target_account: eve).hide_notifications).to be false\n end\n end\n end\n\n context 'when importing old-style list of followed users' do\n subject { described_class.new }\n\n let(:csv) { attachment_fixture('mute-imports.txt') }\n\n describe 'when no accounts are followed' do\n let(:import) { Import.create(account: account, type: 'following', data: csv) }\n\n it 'follows the listed accounts, including boosts' do\n subject.call(import)\n\n expect(account.following.count).to eq 1\n expect(account.follow_requests.count).to eq 1\n expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true\n end\n end\n\n describe 'when some accounts are already followed and overwrite is not set' do\n let(:import) { Import.create(account: account, type: 'following', data: csv) }\n\n it 'follows the listed accounts, including notifications' do\n account.follow!(bob, reblogs: false)\n subject.call(import)\n expect(account.following.count).to eq 1\n expect(account.follow_requests.count).to eq 1\n expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true\n end\n end\n\n describe 'when some accounts are already followed and overwrite is set' do\n let(:import) { Import.create(account: account, type: 'following', data: csv, overwrite: true) }\n\n it 'mutes the listed accounts, including notifications' do\n account.follow!(bob, reblogs: false)\n subject.call(import)\n expect(account.following.count).to eq 1\n expect(account.follow_requests.count).to eq 1\n expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true\n end\n end\n end\n\n context 'when importing new-style list of followed users' do\n subject { described_class.new }\n\n let(:csv) { attachment_fixture('new-following-imports.txt') }\n\n describe 'when no accounts are followed' do\n let(:import) { Import.create(account: account, type: 'following', data: csv) }\n\n it 'follows the listed accounts, respecting boosts' do\n subject.call(import)\n expect(account.following.count).to eq 1\n expect(account.follow_requests.count).to eq 1\n expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true\n expect(FollowRequest.find_by(account: account, target_account: eve).show_reblogs).to be false\n end\n end\n\n describe 'when some accounts are already followed and overwrite is not set' do\n let(:import) { Import.create(account: account, type: 'following', data: csv) }\n\n it 'mutes the listed accounts, respecting notifications' do\n account.follow!(bob, reblogs: true)\n subject.call(import)\n expect(account.following.count).to eq 1\n expect(account.follow_requests.count).to eq 1\n expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true\n expect(FollowRequest.find_by(account: account, target_account: eve).show_reblogs).to be false\n end\n end\n\n describe 'when some accounts are already followed and overwrite is set' do\n let(:import) { Import.create(account: account, type: 'following', data: csv, overwrite: true) }\n\n it 'mutes the listed accounts, respecting notifications' do\n account.follow!(bob, reblogs: true)\n subject.call(import)\n expect(account.following.count).to eq 1\n expect(account.follow_requests.count).to eq 1\n expect(Follow.find_by(account: account, target_account: bob).show_reblogs).to be true\n expect(FollowRequest.find_by(account: account, target_account: eve).show_reblogs).to be false\n end\n end\n end\n\n # Based on the bug report 20571 where UTF-8 encoded domains were rejecting import of their users\n #\n # https:\/\/github.com\/mastodon\/mastodon\/issues\/20571\n context 'with a utf-8 encoded domains' do\n subject { described_class.new }\n\n let!(:nare) { Fabricate(:account, username: 'nare', domain: '\u0569\u0578\u0582\u0569.\u0570\u0561\u0575', locked: false, protocol: :activitypub, inbox_url: 'https:\/\/\u0569\u0578\u0582\u0569.\u0570\u0561\u0575\/inbox') }\n let(:csv) { attachment_fixture('utf8-followers.txt') }\n let(:import) { Import.create(account: account, type: 'following', data: csv) }\n\n # Make sure to not actually go to the remote server\n before do\n stub_request(:post, 'https:\/\/\u0569\u0578\u0582\u0569.\u0570\u0561\u0575\/inbox').to_return(status: 200)\n end\n\n it 'follows the listed account' do\n expect(account.follow_requests.count).to eq 0\n subject.call(import)\n expect(account.follow_requests.count).to eq 1\n end\n end\n\n context 'when importing bookmarks' do\n subject { described_class.new }\n\n let(:csv) { attachment_fixture('bookmark-imports.txt') }\n let(:local_account) { Fabricate(:account, username: 'foo', domain: '') }\n let!(:remote_status) { Fabricate(:status, uri: 'https:\/\/example.com\/statuses\/1312') }\n let!(:direct_status) { Fabricate(:status, uri: 'https:\/\/example.com\/statuses\/direct', visibility: :direct) }\n\n around do |example|\n local_before = Rails.configuration.x.local_domain\n web_before = Rails.configuration.x.web_domain\n Rails.configuration.x.local_domain = 'local.com'\n Rails.configuration.x.web_domain = 'local.com'\n example.run\n Rails.configuration.x.web_domain = web_before\n Rails.configuration.x.local_domain = local_before\n end\n\n before do\n service = instance_double(ActivityPub::FetchRemoteStatusService)\n allow(ActivityPub::FetchRemoteStatusService).to receive(:new).and_return(service)\n allow(service).to receive(:call).with('https:\/\/unknown-remote.com\/users\/bar\/statuses\/1') do\n Fabricate(:status, uri: 'https:\/\/unknown-remote.com\/users\/bar\/statuses\/1')\n end\n end\n\n describe 'when no bookmarks are set' do\n let(:import) { Import.create(account: account, type: 'bookmarks', data: csv) }\n\n it 'adds the toots the user has access to to bookmarks' do\n local_status = Fabricate(:status, account: local_account, uri: 'https:\/\/local.com\/users\/foo\/statuses\/42', id: 42, local: true)\n subject.call(import)\n expect(account.bookmarks.map { |bookmark| bookmark.status.id }).to include(local_status.id)\n expect(account.bookmarks.map { |bookmark| bookmark.status.id }).to include(remote_status.id)\n expect(account.bookmarks.map { |bookmark| bookmark.status.id }).to_not include(direct_status.id)\n expect(account.bookmarks.count).to eq 3\n end\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass AuthorizeFollowService < BaseService\n include Payloadable\n\n def call(source_account, target_account, **options)\n if options[:skip_follow_request]\n follow_request = FollowRequest.new(account: source_account, target_account: target_account, uri: options[:follow_request_uri])\n else\n follow_request = FollowRequest.find_by!(account: source_account, target_account: target_account)\n follow_request.authorize!\n end\n\n create_notification(follow_request) if !source_account.local? && source_account.activitypub?\n follow_request\n end\n\n private\n\n def create_notification(follow_request)\n ActivityPub::DeliveryWorker.perform_async(build_json(follow_request), follow_request.target_account_id, follow_request.account.inbox_url)\n end\n\n def build_json(follow_request)\n Oj.dump(serialize_payload(follow_request, ActivityPub::AcceptFollowSerializer))\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe AuthorizeFollowService, type: :service do\n subject { described_class.new }\n\n let(:sender) { Fabricate(:account, username: 'alice') }\n\n describe 'local' do\n let(:bob) { Fabricate(:account, username: 'bob') }\n\n before do\n FollowRequest.create(account: bob, target_account: sender)\n subject.call(bob, sender)\n end\n\n it 'removes follow request' do\n expect(bob.requested?(sender)).to be false\n end\n\n it 'creates follow relation' do\n expect(bob.following?(sender)).to be true\n end\n end\n\n describe 'remote ActivityPub' do\n let(:bob) { Fabricate(:account, username: 'bob', domain: 'example.com', protocol: :activitypub, inbox_url: 'http:\/\/example.com\/inbox') }\n\n before do\n FollowRequest.create(account: bob, target_account: sender)\n stub_request(:post, bob.inbox_url).to_return(status: 200)\n subject.call(bob, sender)\n end\n\n it 'removes follow request' do\n expect(bob.requested?(sender)).to be false\n end\n\n it 'creates follow relation' do\n expect(bob.following?(sender)).to be true\n end\n\n it 'sends an accept activity' do\n expect(a_request(:post, bob.inbox_url)).to have_been_made.once\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass PrecomputeFeedService < BaseService\n include Redisable\n\n def call(account)\n FeedManager.instance.populate_home(account)\n ensure\n redis.del(\"account:#{account.id}:regeneration\")\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe PrecomputeFeedService, type: :service do\n subject { described_class.new }\n\n describe 'call' do\n let(:account) { Fabricate(:account) }\n\n it 'fills a user timeline with statuses' do\n account = Fabricate(:account)\n status = Fabricate(:status, account: account)\n\n subject.call(account)\n\n expect(redis.zscore(FeedManager.instance.key(:home, account.id), status.id)).to be_within(0.1).of(status.id.to_f)\n end\n\n it 'does not raise an error even if it could not find any status' do\n account = Fabricate(:account)\n expect { subject.call(account) }.to_not raise_error\n end\n\n it 'filters statuses' do\n account = Fabricate(:account)\n muted_account = Fabricate(:account)\n Fabricate(:mute, account: account, target_account: muted_account)\n reblog = Fabricate(:status, account: muted_account)\n Fabricate(:status, account: account, reblog: reblog)\n\n subject.call(account)\n\n expect(redis.zscore(FeedManager.instance.key(:home, account.id), reblog.id)).to be_nil\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass PostStatusService < BaseService\n include Redisable\n include LanguagesHelper\n\n MIN_SCHEDULE_OFFSET = 5.minutes.freeze\n\n class UnexpectedMentionsError < StandardError\n attr_reader :accounts\n\n def initialize(message, accounts)\n super(message)\n @accounts = accounts\n end\n end\n\n # Post a text status update, fetch and notify remote users mentioned\n # @param [Account] account Account from which to post\n # @param [Hash] options\n # @option [String] :text Message\n # @option [Status] :thread Optional status to reply to\n # @option [Boolean] :sensitive\n # @option [String] :visibility\n # @option [String] :spoiler_text\n # @option [String] :language\n # @option [String] :scheduled_at\n # @option [Hash] :poll Optional poll to attach\n # @option [Enumerable] :media_ids Optional array of media IDs to attach\n # @option [Doorkeeper::Application] :application\n # @option [String] :idempotency Optional idempotency key\n # @option [Boolean] :with_rate_limit\n # @option [Enumerable] :allowed_mentions Optional array of expected mentioned account IDs, raises `UnexpectedMentionsError` if unexpected accounts end up in mentions\n # @return [Status]\n def call(account, options = {})\n @account = account\n @options = options\n @text = @options[:text] || ''\n @in_reply_to = @options[:thread]\n\n return idempotency_duplicate if idempotency_given? && idempotency_duplicate?\n\n validate_media!\n preprocess_attributes!\n\n if scheduled?\n schedule_status!\n else\n process_status!\n end\n\n redis.setex(idempotency_key, 3_600, @status.id) if idempotency_given?\n\n unless scheduled?\n postprocess_status!\n bump_potential_friendship!\n end\n\n @status\n end\n\n private\n\n def preprocess_attributes!\n @sensitive = (@options[:sensitive].nil? ? @account.user&.setting_default_sensitive : @options[:sensitive]) || @options[:spoiler_text].present?\n @text = @options.delete(:spoiler_text) if @text.blank? && @options[:spoiler_text].present?\n @visibility = @options[:visibility] || @account.user&.setting_default_privacy\n @visibility = :unlisted if @visibility&.to_sym == :public && @account.silenced?\n @scheduled_at = @options[:scheduled_at]&.to_datetime\n @scheduled_at = nil if scheduled_in_the_past?\n rescue ArgumentError\n raise ActiveRecord::RecordInvalid\n end\n\n def process_status!\n @status = @account.statuses.new(status_attributes)\n process_mentions_service.call(@status, save_records: false)\n safeguard_mentions!(@status)\n\n # The following transaction block is needed to wrap the UPDATEs to\n # the media attachments when the status is created\n ApplicationRecord.transaction do\n @status.save!\n end\n end\n\n def safeguard_mentions!(status)\n return if @options[:allowed_mentions].nil?\n\n expected_account_ids = @options[:allowed_mentions].map(&:to_i)\n\n unexpected_accounts = status.mentions.map(&:account).to_a.reject { |mentioned_account| expected_account_ids.include?(mentioned_account.id) }\n return if unexpected_accounts.empty?\n\n raise UnexpectedMentionsError.new('Post would be sent to unexpected accounts', unexpected_accounts)\n end\n\n def schedule_status!\n status_for_validation = @account.statuses.build(status_attributes)\n\n if status_for_validation.valid?\n # Marking the status as destroyed is necessary to prevent the status from being\n # persisted when the associated media attachments get updated when creating the\n # scheduled status.\n status_for_validation.destroy\n\n # The following transaction block is needed to wrap the UPDATEs to\n # the media attachments when the scheduled status is created\n\n ApplicationRecord.transaction do\n @status = @account.scheduled_statuses.create!(scheduled_status_attributes)\n end\n else\n raise ActiveRecord::RecordInvalid\n end\n end\n\n def postprocess_status!\n process_hashtags_service.call(@status)\n Trends.tags.register(@status)\n LinkCrawlWorker.perform_async(@status.id)\n DistributionWorker.perform_async(@status.id)\n ActivityPub::DistributionWorker.perform_async(@status.id)\n PollExpirationNotifyWorker.perform_at(@status.poll.expires_at, @status.poll.id) if @status.poll\n end\n\n def validate_media!\n if @options[:media_ids].blank? || !@options[:media_ids].is_a?(Enumerable)\n @media = []\n return\n end\n\n raise Mastodon::ValidationError, I18n.t('media_attachments.validations.too_many') if @options[:media_ids].size > 4 || @options[:poll].present?\n\n @media = @account.media_attachments.where(status_id: nil).where(id: @options[:media_ids].take(4).map(&:to_i))\n\n raise Mastodon::ValidationError, I18n.t('media_attachments.validations.images_and_video') if @media.size > 1 && @media.find(&:audio_or_video?)\n raise Mastodon::ValidationError, I18n.t('media_attachments.validations.not_ready') if @media.any?(&:not_processed?)\n end\n\n def process_mentions_service\n ProcessMentionsService.new\n end\n\n def process_hashtags_service\n ProcessHashtagsService.new\n end\n\n def scheduled?\n @scheduled_at.present?\n end\n\n def idempotency_key\n \"idempotency:status:#{@account.id}:#{@options[:idempotency]}\"\n end\n\n def idempotency_given?\n @options[:idempotency].present?\n end\n\n def idempotency_duplicate\n if scheduled?\n @account.schedule_statuses.find(@idempotency_duplicate)\n else\n @account.statuses.find(@idempotency_duplicate)\n end\n end\n\n def idempotency_duplicate?\n @idempotency_duplicate = redis.get(idempotency_key)\n end\n\n def scheduled_in_the_past?\n @scheduled_at.present? && @scheduled_at <= Time.now.utc + MIN_SCHEDULE_OFFSET\n end\n\n def bump_potential_friendship!\n return if !@status.reply? || @account.id == @status.in_reply_to_account_id\n\n ActivityTracker.increment('activity:interactions')\n return if @account.following?(@status.in_reply_to_account_id)\n\n PotentialFriendshipTracker.record(@account.id, @status.in_reply_to_account_id, :reply)\n end\n\n def status_attributes\n {\n text: @text,\n media_attachments: @media || [],\n ordered_media_attachment_ids: (@options[:media_ids] || []).map(&:to_i) & @media.map(&:id),\n thread: @in_reply_to,\n poll_attributes: poll_attributes,\n sensitive: @sensitive,\n spoiler_text: @options[:spoiler_text] || '',\n visibility: @visibility,\n language: valid_locale_cascade(@options[:language], @account.user&.preferred_posting_language, I18n.default_locale),\n application: @options[:application],\n rate_limit: @options[:with_rate_limit],\n }.compact\n end\n\n def scheduled_status_attributes\n {\n scheduled_at: @scheduled_at,\n media_attachments: @media || [],\n params: scheduled_options,\n }\n end\n\n def poll_attributes\n return if @options[:poll].blank?\n\n @options[:poll].merge(account: @account, voters_count: 0)\n end\n\n def scheduled_options\n @options.tap do |options_hash|\n options_hash[:in_reply_to_id] = options_hash.delete(:thread)&.id\n options_hash[:application_id] = options_hash.delete(:application)&.id\n options_hash[:scheduled_at] = nil\n options_hash[:idempotency] = nil\n options_hash[:with_rate_limit] = false\n end\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe PostStatusService, type: :service do\n subject { described_class.new }\n\n it 'creates a new status' do\n account = Fabricate(:account)\n text = 'test status update'\n\n status = subject.call(account, text: text)\n\n expect(status).to be_persisted\n expect(status.text).to eq text\n end\n\n it 'creates a new response status' do\n in_reply_to_status = Fabricate(:status)\n account = Fabricate(:account)\n text = 'test status update'\n\n status = subject.call(account, text: text, thread: in_reply_to_status)\n\n expect(status).to be_persisted\n expect(status.text).to eq text\n expect(status.thread).to eq in_reply_to_status\n end\n\n context 'when scheduling a status' do\n let!(:account) { Fabricate(:account) }\n let!(:future) { Time.now.utc + 2.hours }\n let!(:previous_status) { Fabricate(:status, account: account) }\n\n it 'schedules a status' do\n status = subject.call(account, text: 'Hi future!', scheduled_at: future)\n expect(status).to be_a ScheduledStatus\n expect(status.scheduled_at).to eq future\n expect(status.params['text']).to eq 'Hi future!'\n end\n\n it 'does not immediately create a status' do\n media = Fabricate(:media_attachment, account: account)\n status = subject.call(account, text: 'Hi future!', media_ids: [media.id], scheduled_at: future)\n\n expect(status).to be_a ScheduledStatus\n expect(status.scheduled_at).to eq future\n expect(status.params['text']).to eq 'Hi future!'\n expect(status.params['media_ids']).to eq [media.id]\n expect(media.reload.status).to be_nil\n expect(Status.where(text: 'Hi future!')).to_not exist\n end\n\n it 'does not change statuses count' do\n expect { subject.call(account, text: 'Hi future!', scheduled_at: future, thread: previous_status) }.to_not(change { [account.statuses_count, previous_status.replies_count] })\n end\n end\n\n it 'creates response to the original status of boost' do\n boosted_status = Fabricate(:status)\n in_reply_to_status = Fabricate(:status, reblog: boosted_status)\n account = Fabricate(:account)\n text = 'test status update'\n\n status = subject.call(account, text: text, thread: in_reply_to_status)\n\n expect(status).to be_persisted\n expect(status.text).to eq text\n expect(status.thread).to eq boosted_status\n end\n\n it 'creates a sensitive status' do\n status = create_status_with_options(sensitive: true)\n\n expect(status).to be_persisted\n expect(status).to be_sensitive\n end\n\n it 'creates a status with spoiler text' do\n spoiler_text = 'spoiler text'\n\n status = create_status_with_options(spoiler_text: spoiler_text)\n\n expect(status).to be_persisted\n expect(status.spoiler_text).to eq spoiler_text\n end\n\n it 'creates a sensitive status when there is a CW but no text' do\n status = subject.call(Fabricate(:account), text: '', spoiler_text: 'foo')\n\n expect(status).to be_persisted\n expect(status).to be_sensitive\n end\n\n it 'creates a status with empty default spoiler text' do\n status = create_status_with_options(spoiler_text: nil)\n\n expect(status).to be_persisted\n expect(status.spoiler_text).to eq ''\n end\n\n it 'creates a status with the given visibility' do\n status = create_status_with_options(visibility: :private)\n\n expect(status).to be_persisted\n expect(status.visibility).to eq 'private'\n end\n\n it 'creates a status with limited visibility for silenced users' do\n status = subject.call(Fabricate(:account, silenced: true), text: 'test', visibility: :public)\n\n expect(status).to be_persisted\n expect(status.visibility).to eq 'unlisted'\n end\n\n it 'creates a status for the given application' do\n application = Fabricate(:application)\n\n status = create_status_with_options(application: application)\n\n expect(status).to be_persisted\n expect(status.application).to eq application\n end\n\n it 'creates a status with a language set' do\n account = Fabricate(:account)\n text = 'This is an English text.'\n\n status = subject.call(account, text: text)\n\n expect(status.language).to eq 'en'\n end\n\n it 'processes mentions' do\n mention_service = instance_double(ProcessMentionsService)\n allow(mention_service).to receive(:call)\n allow(ProcessMentionsService).to receive(:new).and_return(mention_service)\n account = Fabricate(:account)\n\n status = subject.call(account, text: 'test status update')\n\n expect(ProcessMentionsService).to have_received(:new)\n expect(mention_service).to have_received(:call).with(status, save_records: false)\n end\n\n it 'safeguards mentions' do\n account = Fabricate(:account)\n mentioned_account = Fabricate(:account, username: 'alice')\n unexpected_mentioned_account = Fabricate(:account, username: 'bob')\n\n expect do\n subject.call(account, text: '@alice hm, @bob is really annoying lately', allowed_mentions: [mentioned_account.id])\n end.to raise_error(an_instance_of(PostStatusService::UnexpectedMentionsError).and(having_attributes(accounts: [unexpected_mentioned_account])))\n end\n\n it 'processes duplicate mentions correctly' do\n account = Fabricate(:account)\n Fabricate(:account, username: 'alice')\n\n expect do\n subject.call(account, text: '@alice @alice @alice hey @alice')\n end.to_not raise_error\n end\n\n it 'processes hashtags' do\n hashtags_service = instance_double(ProcessHashtagsService)\n allow(hashtags_service).to receive(:call)\n allow(ProcessHashtagsService).to receive(:new).and_return(hashtags_service)\n account = Fabricate(:account)\n\n status = subject.call(account, text: 'test status update')\n\n expect(ProcessHashtagsService).to have_received(:new)\n expect(hashtags_service).to have_received(:call).with(status)\n end\n\n it 'gets distributed' do\n allow(DistributionWorker).to receive(:perform_async)\n allow(ActivityPub::DistributionWorker).to receive(:perform_async)\n\n account = Fabricate(:account)\n\n status = subject.call(account, text: 'test status update')\n\n expect(DistributionWorker).to have_received(:perform_async).with(status.id)\n expect(ActivityPub::DistributionWorker).to have_received(:perform_async).with(status.id)\n end\n\n it 'crawls links' do\n allow(LinkCrawlWorker).to receive(:perform_async)\n account = Fabricate(:account)\n\n status = subject.call(account, text: 'test status update')\n\n expect(LinkCrawlWorker).to have_received(:perform_async).with(status.id)\n end\n\n it 'attaches the given media to the created status' do\n account = Fabricate(:account)\n media = Fabricate(:media_attachment, account: account)\n\n status = subject.call(\n account,\n text: 'test status update',\n media_ids: [media.id]\n )\n\n expect(media.reload.status).to eq status\n end\n\n it 'does not attach media from another account to the created status' do\n account = Fabricate(:account)\n media = Fabricate(:media_attachment, account: Fabricate(:account))\n\n subject.call(\n account,\n text: 'test status update',\n media_ids: [media.id]\n )\n\n expect(media.reload.status).to be_nil\n end\n\n it 'does not allow attaching more than 4 files' do\n account = Fabricate(:account)\n\n expect do\n subject.call(\n account,\n text: 'test status update',\n media_ids: [\n Fabricate(:media_attachment, account: account),\n Fabricate(:media_attachment, account: account),\n Fabricate(:media_attachment, account: account),\n Fabricate(:media_attachment, account: account),\n Fabricate(:media_attachment, account: account),\n ].map(&:id)\n )\n end.to raise_error(\n Mastodon::ValidationError,\n I18n.t('media_attachments.validations.too_many')\n )\n end\n\n it 'does not allow attaching both videos and images' do\n account = Fabricate(:account)\n video = Fabricate(:media_attachment, type: :video, account: account)\n image = Fabricate(:media_attachment, type: :image, account: account)\n\n video.update(type: :video)\n\n expect do\n subject.call(\n account,\n text: 'test status update',\n media_ids: [\n video,\n image,\n ].map(&:id)\n )\n end.to raise_error(\n Mastodon::ValidationError,\n I18n.t('media_attachments.validations.images_and_video')\n )\n end\n\n it 'returns existing status when used twice with idempotency key' do\n account = Fabricate(:account)\n status1 = subject.call(account, text: 'test', idempotency: 'meepmeep')\n status2 = subject.call(account, text: 'test', idempotency: 'meepmeep')\n expect(status2.id).to eq status1.id\n end\n\n def create_status_with_options(**options)\n subject.call(Fabricate(:account), options.merge(text: 'test'))\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass AccountSearchService < BaseService\n attr_reader :query, :limit, :offset, :options, :account\n\n MENTION_ONLY_RE = \/\\A#{Account::MENTION_RE}\\z\/i\n\n # Min. number of characters to look for non-exact matches\n MIN_QUERY_LENGTH = 5\n\n class QueryBuilder\n def initialize(query, account, options = {})\n @query = query\n @account = account\n @options = options\n end\n\n def build\n AccountsIndex.query(\n bool: {\n must: {\n function_score: {\n query: {\n bool: {\n must: must_clauses,\n },\n },\n\n functions: [\n reputation_score_function,\n followers_score_function,\n time_distance_function,\n ],\n },\n },\n\n should: should_clauses,\n }\n )\n end\n\n private\n\n def must_clauses\n if @account && @options[:following]\n [core_query, only_following_query]\n else\n [core_query]\n end\n end\n\n def should_clauses\n if @account && !@options[:following]\n [boost_following_query]\n else\n []\n end\n end\n\n # This function limits results to only the accounts the user is following\n def only_following_query\n {\n terms: {\n id: following_ids,\n },\n }\n end\n\n # This function promotes accounts the user is following\n def boost_following_query\n {\n terms: {\n id: following_ids,\n boost: 100,\n },\n }\n end\n\n # This function deranks accounts that follow more people than follow them\n def reputation_score_function\n {\n script_score: {\n script: {\n source: \"(Math.max(doc['followers_count'].value, 0) + 0.0) \/ (Math.max(doc['followers_count'].value, 0) + Math.max(doc['following_count'].value, 0) + 1)\",\n },\n },\n }\n end\n\n # This function promotes accounts that have more followers\n def followers_score_function\n {\n script_score: {\n script: {\n source: \"(Math.max(doc['followers_count'].value, 0) \/ (Math.max(doc['followers_count'].value, 0) + 1))\",\n },\n },\n }\n end\n\n # This function deranks accounts that haven't posted in a long time\n def time_distance_function\n {\n gauss: {\n last_status_at: {\n scale: '30d',\n offset: '30d',\n decay: 0.3,\n },\n },\n }\n end\n\n def following_ids\n @following_ids ||= @account.active_relationships.pluck(:target_account_id) + [@account.id]\n end\n end\n\n class AutocompleteQueryBuilder < QueryBuilder\n private\n\n def core_query\n {\n multi_match: {\n query: @query,\n type: 'bool_prefix',\n fields: %w(username^2 username.*^2 display_name display_name.*),\n },\n }\n end\n end\n\n class FullQueryBuilder < QueryBuilder\n private\n\n def core_query\n {\n multi_match: {\n query: @query,\n type: 'most_fields',\n fields: %w(username^2 display_name^2 text text.*),\n operator: 'and',\n },\n }\n end\n end\n\n def call(query, account = nil, options = {})\n @query = query&.strip&.gsub(\/\\A@\/, '')\n @limit = options[:limit].to_i\n @offset = options[:offset].to_i\n @options = options\n @account = account\n\n search_service_results.compact.uniq\n end\n\n private\n\n def search_service_results\n return [] if query.blank? || limit < 1\n\n [exact_match] + search_results\n end\n\n def exact_match\n return unless offset.zero? && username_complete?\n\n return @exact_match if defined?(@exact_match)\n\n match = if options[:resolve]\n ResolveAccountService.new.call(query)\n elsif domain_is_local?\n Account.find_local(query_username)\n else\n Account.find_remote(query_username, query_domain)\n end\n\n match = nil if !match.nil? && !account.nil? && options[:following] && !account.following?(match)\n\n @exact_match = match\n end\n\n def search_results\n return [] if limit_for_non_exact_results.zero?\n\n @search_results ||= begin\n results = from_elasticsearch if Chewy.enabled?\n results ||= from_database\n results\n end\n end\n\n def from_database\n if account\n advanced_search_results\n else\n simple_search_results\n end\n end\n\n def advanced_search_results\n Account.advanced_search_for(terms_for_query, account, limit: limit_for_non_exact_results, following: options[:following], offset: offset)\n end\n\n def simple_search_results\n Account.search_for(terms_for_query, limit: limit_for_non_exact_results, offset: offset)\n end\n\n def from_elasticsearch\n query_builder = begin\n if options[:use_searchable_text]\n FullQueryBuilder.new(terms_for_query, account, options.slice(:following))\n else\n AutocompleteQueryBuilder.new(terms_for_query, account, options.slice(:following))\n end\n end\n\n records = query_builder.build.limit(limit_for_non_exact_results).offset(offset).objects.compact\n\n ActiveRecord::Associations::Preloader.new(records: records, associations: :account_stat)\n\n records\n rescue Faraday::ConnectionFailed, Parslet::ParseFailed\n nil\n end\n\n def limit_for_non_exact_results\n return 0 if @account.nil? && query.size < MIN_QUERY_LENGTH\n\n if exact_match?\n limit - 1\n else\n limit\n end\n end\n\n def terms_for_query\n if domain_is_local?\n query_username\n else\n query\n end\n end\n\n def split_query_string\n @split_query_string ||= query.split('@')\n end\n\n def query_username\n @query_username ||= split_query_string.first || ''\n end\n\n def query_domain\n @query_domain ||= query_without_split? ? nil : split_query_string.last\n end\n\n def query_without_split?\n split_query_string.size == 1\n end\n\n def domain_is_local?\n @domain_is_local ||= TagManager.instance.local_domain?(query_domain)\n end\n\n def exact_match?\n exact_match.present?\n end\n\n def username_complete?\n query.include?('@') && \"@#{query}\".match?(MENTION_ONLY_RE)\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\ndescribe AccountSearchService, type: :service do\n describe '#call' do\n context 'with a query to ignore' do\n it 'returns empty array for missing query' do\n results = subject.call('', nil, limit: 10)\n\n expect(results).to eq []\n end\n\n it 'returns empty array for limit zero' do\n Fabricate(:account, username: 'match')\n\n results = subject.call('match', nil, limit: 0)\n\n expect(results).to eq []\n end\n end\n\n context 'when searching for a simple term that is not an exact match' do\n it 'does not return a nil entry in the array for the exact match' do\n account = Fabricate(:account, username: 'matchingusername')\n results = subject.call('match', nil, limit: 5)\n\n expect(results).to eq [account]\n end\n end\n\n context 'when there is a local domain' do\n around do |example|\n before = Rails.configuration.x.local_domain\n\n example.run\n\n Rails.configuration.x.local_domain = before\n end\n\n it 'returns exact match first' do\n remote = Fabricate(:account, username: 'a', domain: 'remote', display_name: 'e')\n remote_too = Fabricate(:account, username: 'b', domain: 'remote', display_name: 'e')\n exact = Fabricate(:account, username: 'e')\n\n Rails.configuration.x.local_domain = 'example.com'\n\n results = subject.call('e@example.com', nil, limit: 2)\n\n expect(results).to eq([exact, remote]).or eq([exact, remote_too])\n end\n end\n\n context 'when there is a domain but no exact match' do\n it 'follows the remote account when resolve is true' do\n service = instance_double(ResolveAccountService, call: nil)\n allow(ResolveAccountService).to receive(:new).and_return(service)\n\n subject.call('newuser@remote.com', nil, limit: 10, resolve: true)\n expect(service).to have_received(:call).with('newuser@remote.com')\n end\n\n it 'does not follow the remote account when resolve is false' do\n service = instance_double(ResolveAccountService, call: nil)\n allow(ResolveAccountService).to receive(:new).and_return(service)\n\n subject.call('newuser@remote.com', nil, limit: 10, resolve: false)\n expect(service).to_not have_received(:call)\n end\n end\n\n it 'returns the fuzzy match first, and does not return suspended exacts' do\n partial = Fabricate(:account, username: 'exactness')\n Fabricate(:account, username: 'exact', suspended: true)\n results = subject.call('exact', nil, limit: 10)\n\n expect(results.size).to eq 1\n expect(results).to eq [partial]\n end\n\n it 'does not return suspended remote accounts' do\n Fabricate(:account, username: 'a', domain: 'remote', display_name: 'e', suspended: true)\n results = subject.call('a@example.com', nil, limit: 2)\n\n expect(results.size).to eq 0\n expect(results).to eq []\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass SoftwareUpdateCheckService < BaseService\n def call\n clean_outdated_updates!\n return unless SoftwareUpdate.check_enabled?\n\n process_update_notices!(fetch_update_notices)\n end\n\n private\n\n def clean_outdated_updates!\n SoftwareUpdate.find_each do |software_update|\n software_update.delete if Mastodon::Version.gem_version >= software_update.gem_version\n rescue ArgumentError\n software_update.delete\n end\n end\n\n def fetch_update_notices\n Request.new(:get, \"#{api_url}?version=#{version}\").add_headers('Accept' => 'application\/json', 'User-Agent' => 'Mastodon update checker').perform do |res|\n return Oj.load(res.body_with_limit, mode: :strict) if res.code == 200\n end\n rescue HTTP::Error, OpenSSL::SSL::SSLError, Oj::ParseError\n nil\n end\n\n def api_url\n ENV.fetch('UPDATE_CHECK_URL', 'https:\/\/api.joinmastodon.org\/update-check')\n end\n\n def version\n @version ||= Mastodon::Version.to_s.split('+')[0]\n end\n\n def process_update_notices!(update_notices)\n return if update_notices.blank? || update_notices['updatesAvailable'].nil?\n\n # Clear notices that are not listed by the update server anymore\n SoftwareUpdate.where.not(version: update_notices['updatesAvailable'].pluck('version')).delete_all\n\n return if update_notices['updatesAvailable'].blank?\n\n # Check if any of the notices is new, and issue notifications\n known_versions = SoftwareUpdate.where(version: update_notices['updatesAvailable'].pluck('version')).pluck(:version)\n new_update_notices = update_notices['updatesAvailable'].filter { |notice| known_versions.exclude?(notice['version']) }\n return if new_update_notices.blank?\n\n new_updates = new_update_notices.map do |notice|\n SoftwareUpdate.create!(version: notice['version'], urgent: notice['urgent'], type: notice['type'], release_notes: notice['releaseNotes'])\n end\n\n notify_devops!(new_updates)\n end\n\n def should_notify_user?(user, urgent_version, patch_version)\n case user.settings['notification_emails.software_updates']\n when 'none'\n false\n when 'critical'\n urgent_version\n when 'patch'\n urgent_version || patch_version\n when 'all'\n true\n end\n end\n\n def notify_devops!(new_updates)\n has_new_urgent_version = new_updates.any?(&:urgent?)\n has_new_patch_version = new_updates.any?(&:patch_type?)\n\n User.those_who_can(:view_devops).includes(:account).find_each do |user|\n next unless should_notify_user?(user, has_new_urgent_version, has_new_patch_version)\n\n if has_new_urgent_version\n AdminMailer.with(recipient: user.account).new_critical_software_updates.deliver_later\n else\n AdminMailer.with(recipient: user.account).new_software_updates.deliver_later\n end\n end\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe SoftwareUpdateCheckService, type: :service do\n subject { described_class.new }\n\n shared_examples 'when the feature is enabled' do\n let(:full_update_check_url) { \"#{update_check_url}?version=#{Mastodon::Version.to_s.split('+')[0]}\" }\n\n let(:devops_role) { Fabricate(:user_role, name: 'DevOps', permissions: UserRole::FLAGS[:view_devops]) }\n let(:owner_user) { Fabricate(:user, role: UserRole.find_by(name: 'Owner')) }\n let(:old_devops_user) { Fabricate(:user) }\n let(:none_user) { Fabricate(:user, role: devops_role) }\n let(:patch_user) { Fabricate(:user, role: devops_role) }\n let(:critical_user) { Fabricate(:user, role: devops_role) }\n\n around do |example|\n queue_adapter = ActiveJob::Base.queue_adapter\n ActiveJob::Base.queue_adapter = :test\n\n example.run\n\n ActiveJob::Base.queue_adapter = queue_adapter\n end\n\n before do\n Fabricate(:software_update, version: '3.5.0', type: 'major', urgent: false)\n Fabricate(:software_update, version: '42.13.12', type: 'major', urgent: false)\n\n owner_user.settings.update('notification_emails.software_updates': 'all')\n owner_user.save!\n\n old_devops_user.settings.update('notification_emails.software_updates': 'all')\n old_devops_user.save!\n\n none_user.settings.update('notification_emails.software_updates': 'none')\n none_user.save!\n\n patch_user.settings.update('notification_emails.software_updates': 'patch')\n patch_user.save!\n\n critical_user.settings.update('notification_emails.software_updates': 'critical')\n critical_user.save!\n end\n\n context 'when the update server errors out' do\n before do\n stub_request(:get, full_update_check_url).to_return(status: 404)\n end\n\n it 'deletes outdated update records but keeps valid update records' do\n expect { subject.call }.to change { SoftwareUpdate.pluck(:version).sort }.from(['3.5.0', '42.13.12']).to(['42.13.12'])\n end\n end\n\n context 'when the server returns new versions' do\n let(:server_json) do\n {\n updatesAvailable: [\n {\n version: '4.2.1',\n urgent: false,\n type: 'patch',\n releaseNotes: 'https:\/\/github.com\/mastodon\/mastodon\/releases\/v4.2.1',\n },\n {\n version: '4.3.0',\n urgent: false,\n type: 'minor',\n releaseNotes: 'https:\/\/github.com\/mastodon\/mastodon\/releases\/v4.3.0',\n },\n {\n version: '5.0.0',\n urgent: false,\n type: 'minor',\n releaseNotes: 'https:\/\/github.com\/mastodon\/mastodon\/releases\/v5.0.0',\n },\n ],\n }\n end\n\n before do\n stub_request(:get, full_update_check_url).to_return(body: Oj.dump(server_json))\n end\n\n it 'updates the list of known updates' do\n expect { subject.call }.to change { SoftwareUpdate.pluck(:version).sort }.from(['3.5.0', '42.13.12']).to(['4.2.1', '4.3.0', '5.0.0'])\n end\n\n context 'when no update is urgent' do\n it 'sends e-mail notifications according to settings', :aggregate_failures do\n expect { subject.call }.to have_enqueued_mail(AdminMailer, :new_software_updates)\n .with(hash_including(params: { recipient: owner_user.account })).once\n .and(have_enqueued_mail(AdminMailer, :new_software_updates).with(hash_including(params: { recipient: patch_user.account })).once)\n .and(have_enqueued_mail.at_most(2))\n end\n end\n\n context 'when an update is urgent' do\n let(:server_json) do\n {\n updatesAvailable: [\n {\n version: '5.0.0',\n urgent: true,\n type: 'minor',\n releaseNotes: 'https:\/\/github.com\/mastodon\/mastodon\/releases\/v5.0.0',\n },\n ],\n }\n end\n\n it 'sends e-mail notifications according to settings', :aggregate_failures do\n expect { subject.call }.to have_enqueued_mail(AdminMailer, :new_critical_software_updates)\n .with(hash_including(params: { recipient: owner_user.account })).once\n .and(have_enqueued_mail(AdminMailer, :new_critical_software_updates).with(hash_including(params: { recipient: patch_user.account })).once)\n .and(have_enqueued_mail(AdminMailer, :new_critical_software_updates).with(hash_including(params: { recipient: critical_user.account })).once)\n .and(have_enqueued_mail.at_most(3))\n end\n end\n end\n end\n\n context 'when update checking is disabled' do\n around do |example|\n ClimateControl.modify UPDATE_CHECK_URL: '' do\n example.run\n end\n end\n\n before do\n Fabricate(:software_update, version: '3.5.0', type: 'major', urgent: false)\n end\n\n it 'deletes outdated update records' do\n expect { subject.call }.to change(SoftwareUpdate, :count).from(1).to(0)\n end\n end\n\n context 'when using the default update checking API' do\n let(:update_check_url) { 'https:\/\/api.joinmastodon.org\/update-check' }\n\n it_behaves_like 'when the feature is enabled'\n end\n\n context 'when using a custom update check URL' do\n let(:update_check_url) { 'https:\/\/api.example.com\/update_check' }\n\n around do |example|\n ClimateControl.modify UPDATE_CHECK_URL: 'https:\/\/api.example.com\/update_check' do\n example.run\n end\n end\n\n it_behaves_like 'when the feature is enabled'\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass UnsuspendAccountService < BaseService\n include Payloadable\n\n # Restores a recently-unsuspended account\n # @param [Account] account Account to restore\n def call(account)\n @account = account\n\n refresh_remote_account!\n\n return if @account.nil? || @account.suspended?\n\n merge_into_home_timelines!\n merge_into_list_timelines!\n publish_media_attachments!\n distribute_update_actor!\n end\n\n private\n\n def refresh_remote_account!\n return if @account.local?\n\n # While we had the remote account suspended, it could be that\n # it got suspended on its origin, too. So, we need to refresh\n # it straight away so it gets marked as remotely suspended in\n # that case.\n\n @account.update!(last_webfingered_at: nil)\n @account = ResolveAccountService.new.call(@account)\n\n # Worth noting that it is possible that the remote has not only\n # been suspended, but deleted permanently, in which case\n # @account would now be nil.\n end\n\n def distribute_update_actor!\n return unless @account.local?\n\n account_reach_finder = AccountReachFinder.new(@account)\n\n ActivityPub::DeliveryWorker.push_bulk(account_reach_finder.inboxes, limit: 1_000) do |inbox_url|\n [signed_activity_json, @account.id, inbox_url]\n end\n end\n\n def merge_into_home_timelines!\n @account.followers_for_local_distribution.reorder(nil).find_each do |follower|\n FeedManager.instance.merge_into_home(@account, follower)\n end\n end\n\n def merge_into_list_timelines!\n @account.lists_for_local_distribution.reorder(nil).find_each do |list|\n FeedManager.instance.merge_into_list(@account, list)\n end\n end\n\n def publish_media_attachments!\n attachment_names = MediaAttachment.attachment_definitions.keys\n\n @account.media_attachments.find_each do |media_attachment|\n attachment_names.each do |attachment_name|\n attachment = media_attachment.public_send(attachment_name)\n styles = MediaAttachment::DEFAULT_STYLES | attachment.styles.keys\n\n next if attachment.blank?\n\n styles.each do |style|\n case Paperclip::Attachment.default_options[:storage]\n when :s3\n # Prevent useless S3 calls if ACLs are disabled\n next if ENV['S3_PERMISSION'] == ''\n\n begin\n attachment.s3_object(style).acl.put(acl: Paperclip::Attachment.default_options[:s3_permissions])\n rescue Aws::S3::Errors::NoSuchKey\n Rails.logger.warn \"Tried to change acl on non-existent key #{attachment.s3_object(style).key}\"\n rescue Aws::S3::Errors::NotImplemented => e\n Rails.logger.error \"Error trying to change ACL on #{attachment.s3_object(style).key}: #{e.message}\"\n end\n when :fog, :azure\n # Not supported\n when :filesystem\n begin\n FileUtils.chmod(0o666 & ~File.umask, attachment.path(style)) unless attachment.path(style).nil?\n rescue Errno::ENOENT\n Rails.logger.warn \"Tried to change permission on non-existent file #{attachment.path(style)}\"\n end\n end\n\n CacheBusterWorker.perform_async(attachment.path(style)) if Rails.configuration.x.cache_buster_enabled\n end\n end\n end\n end\n\n def signed_activity_json\n @signed_activity_json ||= Oj.dump(serialize_payload(@account, ActivityPub::UpdateSerializer, signer: @account))\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe UnsuspendAccountService, type: :service do\n shared_context 'with common context' do\n subject { described_class.new.call(account) }\n\n let!(:local_follower) { Fabricate(:user, current_sign_in_at: 1.hour.ago).account }\n let!(:list) { Fabricate(:list, account: local_follower) }\n\n before do\n allow(FeedManager.instance).to receive_messages(merge_into_home: nil, merge_into_list: nil)\n\n local_follower.follow!(account)\n list.accounts << account\n\n account.unsuspend!\n end\n end\n\n describe 'unsuspending a local account' do\n def match_update_actor_request(req, account)\n json = JSON.parse(req.body)\n actor_id = ActivityPub::TagManager.instance.uri_for(account)\n json['type'] == 'Update' && json['actor'] == actor_id && json['object']['id'] == actor_id && !json['object']['suspended']\n end\n\n before do\n stub_request(:post, 'https:\/\/alice.com\/inbox').to_return(status: 201)\n stub_request(:post, 'https:\/\/bob.com\/inbox').to_return(status: 201)\n end\n\n it 'does not change the \u201csuspended\u201d flag' do\n expect { subject }.to_not change(account, :suspended?)\n end\n\n include_examples 'with common context' do\n let!(:account) { Fabricate(:account) }\n let!(:remote_follower) { Fabricate(:account, uri: 'https:\/\/alice.com', inbox_url: 'https:\/\/alice.com\/inbox', protocol: :activitypub, domain: 'alice.com') }\n let!(:remote_reporter) { Fabricate(:account, uri: 'https:\/\/bob.com', inbox_url: 'https:\/\/bob.com\/inbox', protocol: :activitypub, domain: 'bob.com') }\n let!(:report) { Fabricate(:report, account: remote_reporter, target_account: account) }\n\n before do\n remote_follower.follow!(account)\n end\n\n it \"merges back into local followers' feeds\" do\n subject\n expect(FeedManager.instance).to have_received(:merge_into_home).with(account, local_follower)\n expect(FeedManager.instance).to have_received(:merge_into_list).with(account, list)\n end\n\n it 'sends an update actor to followers and reporters' do\n subject\n expect(a_request(:post, remote_follower.inbox_url).with { |req| match_update_actor_request(req, account) }).to have_been_made.once\n expect(a_request(:post, remote_reporter.inbox_url).with { |req| match_update_actor_request(req, account) }).to have_been_made.once\n end\n end\n end\n\n describe 'unsuspending a remote account' do\n include_examples 'with common context' do\n let!(:account) { Fabricate(:account, domain: 'bob.com', uri: 'https:\/\/bob.com', inbox_url: 'https:\/\/bob.com\/inbox', protocol: :activitypub) }\n let!(:resolve_account_service) { instance_double(ResolveAccountService) }\n\n before do\n allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service)\n end\n\n context 'when the account is not remotely suspended' do\n before do\n allow(resolve_account_service).to receive(:call).with(account).and_return(account)\n end\n\n it 're-fetches the account' do\n subject\n expect(resolve_account_service).to have_received(:call).with(account)\n end\n\n it \"merges back into local followers' feeds\" do\n subject\n expect(FeedManager.instance).to have_received(:merge_into_home).with(account, local_follower)\n expect(FeedManager.instance).to have_received(:merge_into_list).with(account, list)\n end\n\n it 'does not change the \u201csuspended\u201d flag' do\n expect { subject }.to_not change(account, :suspended?)\n end\n end\n\n context 'when the account is remotely suspended' do\n before do\n allow(resolve_account_service).to receive(:call).with(account) do |account|\n account.suspend!(origin: :remote)\n account\n end\n end\n\n it 're-fetches the account' do\n subject\n expect(resolve_account_service).to have_received(:call).with(account)\n end\n\n it \"does not merge back into local followers' feeds\" do\n subject\n expect(FeedManager.instance).to_not have_received(:merge_into_home).with(account, local_follower)\n expect(FeedManager.instance).to_not have_received(:merge_into_list).with(account, list)\n end\n\n it 'marks account as suspended' do\n expect { subject }.to change(account, :suspended?).from(false).to(true)\n end\n end\n\n context 'when the account is remotely deleted' do\n before do\n allow(resolve_account_service).to receive(:call).with(account).and_return(nil)\n end\n\n it 're-fetches the account' do\n subject\n expect(resolve_account_service).to have_received(:call).with(account)\n end\n\n it \"does not merge back into local followers' feeds\" do\n subject\n expect(FeedManager.instance).to_not have_received(:merge_into_home).with(account, local_follower)\n expect(FeedManager.instance).to_not have_received(:merge_into_list).with(account, list)\n end\n end\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass AfterBlockDomainFromAccountService < BaseService\n include Payloadable\n\n # This service does not create an AccountDomainBlock record,\n # it's meant to be called after such a record has been created\n # synchronously, to \"clean up\"\n def call(account, domain)\n @account = account\n @domain = domain\n\n clear_notifications!\n remove_follows!\n reject_existing_followers!\n reject_pending_follow_requests!\n end\n\n private\n\n def remove_follows!\n @account.active_relationships.where(target_account: Account.where(domain: @domain)).includes(:target_account).reorder(nil).find_each do |follow|\n UnfollowService.new.call(@account, follow.target_account)\n end\n end\n\n def clear_notifications!\n Notification.where(account: @account).where(from_account: Account.where(domain: @domain)).in_batches.delete_all\n end\n\n def reject_existing_followers!\n @account.passive_relationships.where(account: Account.where(domain: @domain)).includes(:account).reorder(nil).find_each do |follow|\n reject_follow!(follow)\n end\n end\n\n def reject_pending_follow_requests!\n FollowRequest.where(target_account: @account).where(account: Account.where(domain: @domain)).includes(:account).reorder(nil).find_each do |follow_request|\n reject_follow!(follow_request)\n end\n end\n\n def reject_follow!(follow)\n follow.destroy\n\n return unless follow.account.activitypub?\n\n ActivityPub::DeliveryWorker.perform_async(Oj.dump(serialize_payload(follow, ActivityPub::RejectFollowSerializer)), @account.id, follow.account.inbox_url)\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe AfterBlockDomainFromAccountService, type: :service do\n subject { described_class.new }\n\n let!(:wolf) { Fabricate(:account, username: 'wolf', domain: 'evil.org', inbox_url: 'https:\/\/evil.org\/inbox', protocol: :activitypub) }\n let!(:alice) { Fabricate(:account, username: 'alice') }\n\n before do\n allow(ActivityPub::DeliveryWorker).to receive(:perform_async)\n end\n\n it 'purge followers from blocked domain' do\n wolf.follow!(alice)\n subject.call(alice, 'evil.org')\n expect(wolf.following?(alice)).to be false\n end\n\n it 'sends Reject->Follow to followers from blocked domain' do\n wolf.follow!(alice)\n subject.call(alice, 'evil.org')\n expect(ActivityPub::DeliveryWorker).to have_received(:perform_async).once\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass BlockDomainService < BaseService\n attr_reader :domain_block\n\n def call(domain_block, update = false)\n @domain_block = domain_block\n process_domain_block!\n process_retroactive_updates! if update\n end\n\n private\n\n def process_retroactive_updates!\n # If the domain block severity has been changed, undo the appropriate limitations\n scope = Account.by_domain_and_subdomains(domain_block.domain)\n\n scope.where(silenced_at: domain_block.created_at).in_batches.update_all(silenced_at: nil) unless domain_block.silence?\n scope.where(suspended_at: domain_block.created_at).in_batches.update_all(suspended_at: nil, suspension_origin: nil) unless domain_block.suspend?\n end\n\n def process_domain_block!\n if domain_block.silence?\n silence_accounts!\n elsif domain_block.suspend?\n suspend_accounts!\n end\n\n DomainClearMediaWorker.perform_async(domain_block.id) if domain_block.reject_media?\n end\n\n def silence_accounts!\n blocked_domain_accounts.without_silenced.in_batches.update_all(silenced_at: @domain_block.created_at)\n end\n\n def suspend_accounts!\n blocked_domain_accounts.without_suspended.in_batches.update_all(suspended_at: @domain_block.created_at, suspension_origin: :local)\n\n blocked_domain_accounts.where(suspended_at: @domain_block.created_at).reorder(nil).find_each do |account|\n DeleteAccountService.new.call(account, reserve_username: true, suspended_at: @domain_block.created_at)\n end\n end\n\n def blocked_domain\n domain_block.domain\n end\n\n def blocked_domain_accounts\n Account.by_domain_and_subdomains(blocked_domain)\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe BlockDomainService, type: :service do\n subject { described_class.new }\n\n let!(:bad_account) { Fabricate(:account, username: 'badguy666', domain: 'evil.org') }\n let!(:bad_status_plain) { Fabricate(:status, account: bad_account, text: 'You suck') }\n let!(:bad_status_with_attachment) { Fabricate(:status, account: bad_account, text: 'Hahaha') }\n let!(:bad_attachment) { Fabricate(:media_attachment, account: bad_account, status: bad_status_with_attachment, file: attachment_fixture('attachment.jpg')) }\n let!(:already_banned_account) { Fabricate(:account, username: 'badguy', domain: 'evil.org', suspended: true, silenced: true) }\n\n describe 'for a suspension' do\n before do\n subject.call(DomainBlock.create!(domain: 'evil.org', severity: :suspend))\n end\n\n it 'creates a domain block' do\n expect(DomainBlock.blocked?('evil.org')).to be true\n end\n\n it 'removes remote accounts from that domain' do\n expect(Account.find_remote('badguy666', 'evil.org').suspended?).to be true\n end\n\n it 'records suspension date appropriately' do\n expect(Account.find_remote('badguy666', 'evil.org').suspended_at).to eq DomainBlock.find_by(domain: 'evil.org').created_at\n end\n\n it 'keeps already-banned accounts banned' do\n expect(Account.find_remote('badguy', 'evil.org').suspended?).to be true\n end\n\n it 'does not overwrite suspension date of already-banned accounts' do\n expect(Account.find_remote('badguy', 'evil.org').suspended_at).to_not eq DomainBlock.find_by(domain: 'evil.org').created_at\n end\n\n it 'removes the remote accounts\\'s statuses and media attachments' do\n expect { bad_status_plain.reload }.to raise_exception ActiveRecord::RecordNotFound\n expect { bad_status_with_attachment.reload }.to raise_exception ActiveRecord::RecordNotFound\n expect { bad_attachment.reload }.to raise_exception ActiveRecord::RecordNotFound\n end\n end\n\n describe 'for a silence with reject media' do\n before do\n subject.call(DomainBlock.create!(domain: 'evil.org', severity: :silence, reject_media: true))\n end\n\n it 'does not create a domain block' do\n expect(DomainBlock.blocked?('evil.org')).to be false\n end\n\n it 'silences remote accounts from that domain' do\n expect(Account.find_remote('badguy666', 'evil.org').silenced?).to be true\n end\n\n it 'records suspension date appropriately' do\n expect(Account.find_remote('badguy666', 'evil.org').silenced_at).to eq DomainBlock.find_by(domain: 'evil.org').created_at\n end\n\n it 'keeps already-banned accounts banned' do\n expect(Account.find_remote('badguy', 'evil.org').silenced?).to be true\n end\n\n it 'does not overwrite suspension date of already-banned accounts' do\n expect(Account.find_remote('badguy', 'evil.org').silenced_at).to_not eq DomainBlock.find_by(domain: 'evil.org').created_at\n end\n\n it 'leaves the domains status and attachments, but clears media' do\n expect { bad_status_plain.reload }.to_not raise_error\n expect { bad_status_with_attachment.reload }.to_not raise_error\n expect { bad_attachment.reload }.to_not raise_error\n expect(bad_attachment.file.exists?).to be false\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass BlockService < BaseService\n include Payloadable\n\n def call(account, target_account)\n return if account.id == target_account.id\n\n UnfollowService.new.call(account, target_account) if account.following?(target_account)\n UnfollowService.new.call(target_account, account) if target_account.following?(account)\n RejectFollowService.new.call(target_account, account) if target_account.requested?(account)\n\n block = account.block!(target_account)\n\n BlockWorker.perform_async(account.id, target_account.id)\n create_notification(block) if !target_account.local? && target_account.activitypub?\n block\n end\n\n private\n\n def create_notification(block)\n ActivityPub::DeliveryWorker.perform_async(build_json(block), block.account_id, block.target_account.inbox_url)\n end\n\n def build_json(block)\n Oj.dump(serialize_payload(block, ActivityPub::BlockSerializer))\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe BlockService, type: :service do\n subject { described_class.new }\n\n let(:sender) { Fabricate(:account, username: 'alice') }\n\n describe 'local' do\n let(:bob) { Fabricate(:account, username: 'bob') }\n\n before do\n subject.call(sender, bob)\n end\n\n it 'creates a blocking relation' do\n expect(sender.blocking?(bob)).to be true\n end\n end\n\n describe 'remote ActivityPub' do\n let(:bob) { Fabricate(:account, username: 'bob', protocol: :activitypub, domain: 'example.com', inbox_url: 'http:\/\/example.com\/inbox') }\n\n before do\n stub_request(:post, 'http:\/\/example.com\/inbox').to_return(status: 200)\n subject.call(sender, bob)\n end\n\n it 'creates a blocking relation' do\n expect(sender.blocking?(bob)).to be true\n end\n\n it 'sends a block activity' do\n expect(a_request(:post, 'http:\/\/example.com\/inbox')).to have_been_made.once\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass UnfollowService < BaseService\n include Payloadable\n include Redisable\n include Lockable\n\n # Unfollow and notify the remote user\n # @param [Account] source_account Where to unfollow from\n # @param [Account] target_account Which to unfollow\n # @param [Hash] options\n # @option [Boolean] :skip_unmerge\n def call(source_account, target_account, options = {})\n @source_account = source_account\n @target_account = target_account\n @options = options\n\n with_redis_lock(\"relationship:#{[source_account.id, target_account.id].sort.join(':')}\") do\n unfollow! || undo_follow_request!\n end\n end\n\n private\n\n def unfollow!\n follow = Follow.find_by(account: @source_account, target_account: @target_account)\n\n return unless follow\n\n follow.destroy!\n\n create_notification(follow) if !@target_account.local? && @target_account.activitypub?\n create_reject_notification(follow) if @target_account.local? && !@source_account.local? && @source_account.activitypub?\n UnmergeWorker.perform_async(@target_account.id, @source_account.id) unless @options[:skip_unmerge]\n\n follow\n end\n\n def undo_follow_request!\n follow_request = FollowRequest.find_by(account: @source_account, target_account: @target_account)\n\n return unless follow_request\n\n follow_request.destroy!\n\n create_notification(follow_request) unless @target_account.local?\n\n follow_request\n end\n\n def create_notification(follow)\n ActivityPub::DeliveryWorker.perform_async(build_json(follow), follow.account_id, follow.target_account.inbox_url)\n end\n\n def create_reject_notification(follow)\n ActivityPub::DeliveryWorker.perform_async(build_reject_json(follow), follow.target_account_id, follow.account.inbox_url)\n end\n\n def build_json(follow)\n Oj.dump(serialize_payload(follow, ActivityPub::UndoFollowSerializer))\n end\n\n def build_reject_json(follow)\n Oj.dump(serialize_payload(follow, ActivityPub::RejectFollowSerializer))\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe UnfollowService, type: :service do\n subject { described_class.new }\n\n let(:sender) { Fabricate(:account, username: 'alice') }\n\n describe 'local' do\n let(:bob) { Fabricate(:account, username: 'bob') }\n\n before do\n sender.follow!(bob)\n subject.call(sender, bob)\n end\n\n it 'destroys the following relation' do\n expect(sender.following?(bob)).to be false\n end\n end\n\n describe 'remote ActivityPub' do\n let(:bob) { Fabricate(:account, username: 'bob', protocol: :activitypub, domain: 'example.com', inbox_url: 'http:\/\/example.com\/inbox') }\n\n before do\n sender.follow!(bob)\n stub_request(:post, 'http:\/\/example.com\/inbox').to_return(status: 200)\n subject.call(sender, bob)\n end\n\n it 'destroys the following relation' do\n expect(sender.following?(bob)).to be false\n end\n\n it 'sends an unfollow activity' do\n expect(a_request(:post, 'http:\/\/example.com\/inbox')).to have_been_made.once\n end\n end\n\n describe 'remote ActivityPub (reverse)' do\n let(:bob) { Fabricate(:account, username: 'bob', protocol: :activitypub, domain: 'example.com', inbox_url: 'http:\/\/example.com\/inbox') }\n\n before do\n bob.follow!(sender)\n stub_request(:post, 'http:\/\/example.com\/inbox').to_return(status: 200)\n subject.call(bob, sender)\n end\n\n it 'destroys the following relation' do\n expect(bob.following?(sender)).to be false\n end\n\n it 'sends a reject activity' do\n expect(a_request(:post, 'http:\/\/example.com\/inbox')).to have_been_made.once\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass SuspendAccountService < BaseService\n include Payloadable\n\n # Carry out the suspension of a recently-suspended account\n # @param [Account] account Account to suspend\n def call(account)\n return unless account.suspended?\n\n @account = account\n\n reject_remote_follows!\n distribute_update_actor!\n unmerge_from_home_timelines!\n unmerge_from_list_timelines!\n privatize_media_attachments!\n end\n\n private\n\n def reject_remote_follows!\n return if @account.local? || !@account.activitypub?\n\n # When suspending a remote account, the account obviously doesn't\n # actually become suspended on its origin server, i.e. unlike a\n # locally suspended account it continues to have access to its home\n # feed and other content. To prevent it from being able to continue\n # to access toots it would receive because it follows local accounts,\n # we have to force it to unfollow them. Unfortunately, there is no\n # counterpart to this operation, i.e. you can't then force a remote\n # account to re-follow you, so this part is not reversible.\n\n Follow.where(account: @account).find_in_batches do |follows|\n ActivityPub::DeliveryWorker.push_bulk(follows) do |follow|\n [Oj.dump(serialize_payload(follow, ActivityPub::RejectFollowSerializer)), follow.target_account_id, @account.inbox_url]\n end\n\n follows.each(&:destroy)\n end\n end\n\n def distribute_update_actor!\n return unless @account.local?\n\n account_reach_finder = AccountReachFinder.new(@account)\n\n ActivityPub::DeliveryWorker.push_bulk(account_reach_finder.inboxes, limit: 1_000) do |inbox_url|\n [signed_activity_json, @account.id, inbox_url]\n end\n end\n\n def unmerge_from_home_timelines!\n @account.followers_for_local_distribution.reorder(nil).find_each do |follower|\n FeedManager.instance.unmerge_from_home(@account, follower)\n end\n end\n\n def unmerge_from_list_timelines!\n @account.lists_for_local_distribution.reorder(nil).find_each do |list|\n FeedManager.instance.unmerge_from_list(@account, list)\n end\n end\n\n def privatize_media_attachments!\n attachment_names = MediaAttachment.attachment_definitions.keys\n\n @account.media_attachments.find_each do |media_attachment|\n attachment_names.each do |attachment_name|\n attachment = media_attachment.public_send(attachment_name)\n styles = MediaAttachment::DEFAULT_STYLES | attachment.styles.keys\n\n next if attachment.blank?\n\n styles.each do |style|\n case Paperclip::Attachment.default_options[:storage]\n when :s3\n # Prevent useless S3 calls if ACLs are disabled\n next if ENV['S3_PERMISSION'] == ''\n\n begin\n attachment.s3_object(style).acl.put(acl: 'private')\n rescue Aws::S3::Errors::NoSuchKey\n Rails.logger.warn \"Tried to change acl on non-existent key #{attachment.s3_object(style).key}\"\n rescue Aws::S3::Errors::NotImplemented => e\n Rails.logger.error \"Error trying to change ACL on #{attachment.s3_object(style).key}: #{e.message}\"\n end\n when :fog, :azure\n # Not supported\n when :filesystem\n begin\n FileUtils.chmod(0o600 & ~File.umask, attachment.path(style)) unless attachment.path(style).nil?\n rescue Errno::ENOENT\n Rails.logger.warn \"Tried to change permission on non-existent file #{attachment.path(style)}\"\n end\n end\n\n CacheBusterWorker.perform_async(attachment.path(style)) if Rails.configuration.x.cache_buster_enabled\n end\n end\n end\n end\n\n def signed_activity_json\n @signed_activity_json ||= Oj.dump(serialize_payload(@account, ActivityPub::UpdateSerializer, signer: @account))\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe SuspendAccountService, type: :service do\n shared_examples 'common behavior' do\n subject { described_class.new.call(account) }\n\n let!(:local_follower) { Fabricate(:user, current_sign_in_at: 1.hour.ago).account }\n let!(:list) { Fabricate(:list, account: local_follower) }\n\n before do\n allow(FeedManager.instance).to receive_messages(unmerge_from_home: nil, unmerge_from_list: nil)\n\n local_follower.follow!(account)\n list.accounts << account\n\n account.suspend!\n end\n\n it \"unmerges from local followers' feeds\" do\n subject\n expect(FeedManager.instance).to have_received(:unmerge_from_home).with(account, local_follower)\n expect(FeedManager.instance).to have_received(:unmerge_from_list).with(account, list)\n end\n\n it 'does not change the \u201csuspended\u201d flag' do\n expect { subject }.to_not change(account, :suspended?)\n end\n end\n\n describe 'suspending a local account' do\n def match_update_actor_request(req, account)\n json = JSON.parse(req.body)\n actor_id = ActivityPub::TagManager.instance.uri_for(account)\n json['type'] == 'Update' && json['actor'] == actor_id && json['object']['id'] == actor_id && json['object']['suspended']\n end\n\n before do\n stub_request(:post, 'https:\/\/alice.com\/inbox').to_return(status: 201)\n stub_request(:post, 'https:\/\/bob.com\/inbox').to_return(status: 201)\n end\n\n include_examples 'common behavior' do\n let!(:account) { Fabricate(:account) }\n let!(:remote_follower) { Fabricate(:account, uri: 'https:\/\/alice.com', inbox_url: 'https:\/\/alice.com\/inbox', protocol: :activitypub, domain: 'alice.com') }\n let!(:remote_reporter) { Fabricate(:account, uri: 'https:\/\/bob.com', inbox_url: 'https:\/\/bob.com\/inbox', protocol: :activitypub, domain: 'bob.com') }\n let!(:report) { Fabricate(:report, account: remote_reporter, target_account: account) }\n\n before do\n remote_follower.follow!(account)\n end\n\n it 'sends an update actor to followers and reporters' do\n subject\n expect(a_request(:post, remote_follower.inbox_url).with { |req| match_update_actor_request(req, account) }).to have_been_made.once\n expect(a_request(:post, remote_reporter.inbox_url).with { |req| match_update_actor_request(req, account) }).to have_been_made.once\n end\n end\n end\n\n describe 'suspending a remote account' do\n def match_reject_follow_request(req, account, followee)\n json = JSON.parse(req.body)\n json['type'] == 'Reject' && json['actor'] == ActivityPub::TagManager.instance.uri_for(followee) && json['object']['actor'] == account.uri\n end\n\n before do\n stub_request(:post, 'https:\/\/bob.com\/inbox').to_return(status: 201)\n end\n\n include_examples 'common behavior' do\n let!(:account) { Fabricate(:account, domain: 'bob.com', uri: 'https:\/\/bob.com', inbox_url: 'https:\/\/bob.com\/inbox', protocol: :activitypub) }\n let!(:local_followee) { Fabricate(:account) }\n\n before do\n account.follow!(local_followee)\n end\n\n it 'sends a reject follow' do\n subject\n expect(a_request(:post, account.inbox_url).with { |req| match_reject_follow_request(req, account, local_followee) }).to have_been_made.once\n end\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass BulkImportService < BaseService\n def call(import)\n @import = import\n @account = @import.account\n\n case @import.type.to_sym\n when :following\n import_follows!\n when :blocking\n import_blocks!\n when :muting\n import_mutes!\n when :domain_blocking\n import_domain_blocks!\n when :bookmarks\n import_bookmarks!\n when :lists\n import_lists!\n end\n\n @import.update!(state: :finished, finished_at: Time.now.utc) if @import.processed_items == @import.total_items\n rescue\n @import.update!(state: :finished, finished_at: Time.now.utc)\n\n raise\n end\n\n private\n\n def extract_rows_by_acct\n local_domain_suffix = \"@#{Rails.configuration.x.local_domain}\"\n @import.rows.to_a.index_by { |row| row.data['acct'].delete_suffix(local_domain_suffix) }\n end\n\n def import_follows!\n rows_by_acct = extract_rows_by_acct\n\n if @import.overwrite?\n @account.following.reorder(nil).find_each do |followee|\n row = rows_by_acct.delete(followee.acct)\n\n if row.nil?\n UnfollowService.new.call(@account, followee)\n else\n row.destroy\n @import.processed_items += 1\n @import.imported_items += 1\n\n # Since we're updating the settings of an existing relationship, we can safely call\n # FollowService directly\n FollowService.new.call(@account, followee, reblogs: row.data['show_reblogs'], notify: row.data['notify'], languages: row.data['languages'])\n end\n end\n\n # Save pending infos due to `overwrite?` handling\n @import.save!\n end\n\n Import::RowWorker.push_bulk(rows_by_acct.values) do |row|\n [row.id]\n end\n end\n\n def import_blocks!\n rows_by_acct = extract_rows_by_acct\n\n if @import.overwrite?\n @account.blocking.reorder(nil).find_each do |blocked_account|\n row = rows_by_acct.delete(blocked_account.acct)\n\n if row.nil?\n UnblockService.new.call(@account, blocked_account)\n else\n row.destroy\n @import.processed_items += 1\n @import.imported_items += 1\n BlockService.new.call(@account, blocked_account)\n end\n end\n\n # Save pending infos due to `overwrite?` handling\n @import.save!\n end\n\n Import::RowWorker.push_bulk(rows_by_acct.values) do |row|\n [row.id]\n end\n end\n\n def import_mutes!\n rows_by_acct = extract_rows_by_acct\n\n if @import.overwrite?\n @account.muting.reorder(nil).find_each do |muted_account|\n row = rows_by_acct.delete(muted_account.acct)\n\n if row.nil?\n UnmuteService.new.call(@account, muted_account)\n else\n row.destroy\n @import.processed_items += 1\n @import.imported_items += 1\n MuteService.new.call(@account, muted_account, notifications: row.data['hide_notifications'])\n end\n end\n\n # Save pending infos due to `overwrite?` handling\n @import.save!\n end\n\n Import::RowWorker.push_bulk(rows_by_acct.values) do |row|\n [row.id]\n end\n end\n\n def import_domain_blocks!\n domains = @import.rows.map { |row| row.data['domain'] }\n\n if @import.overwrite?\n @account.domain_blocks.find_each do |domain_block|\n domain = domains.delete(domain_block)\n\n @account.unblock_domain!(domain_block.domain) if domain.nil?\n end\n end\n\n @import.rows.delete_all\n domains.each { |domain| @account.block_domain!(domain) }\n @import.update!(processed_items: @import.total_items, imported_items: @import.total_items)\n\n AfterAccountDomainBlockWorker.push_bulk(domains) do |domain|\n [@account.id, domain]\n end\n end\n\n def import_bookmarks!\n rows_by_uri = @import.rows.index_by { |row| row.data['uri'] }\n\n if @import.overwrite?\n @account.bookmarks.includes(:status).find_each do |bookmark|\n row = rows_by_uri.delete(ActivityPub::TagManager.instance.uri_for(bookmark.status))\n\n if row.nil?\n bookmark.destroy!\n else\n row.destroy\n @import.processed_items += 1\n @import.imported_items += 1\n end\n end\n\n # Save pending infos due to `overwrite?` handling\n @import.save!\n end\n\n Import::RowWorker.push_bulk(rows_by_uri.values) do |row|\n [row.id]\n end\n end\n\n def import_lists!\n rows = @import.rows.to_a\n included_lists = rows.map { |row| row.data['list_name'] }.uniq\n\n if @import.overwrite?\n @account.owned_lists.where.not(title: included_lists).destroy_all\n\n # As list membership changes do not retroactively change timeline\n # contents, simplify things by just clearing everything\n @account.owned_lists.find_each do |list|\n list.list_accounts.destroy_all\n end\n end\n\n included_lists.each do |title|\n @account.owned_lists.find_or_create_by!(title: title)\n end\n\n Import::RowWorker.push_bulk(rows) do |row|\n [row.id]\n end\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe BulkImportService do\n subject { described_class.new }\n\n let(:account) { Fabricate(:account) }\n let(:import) { Fabricate(:bulk_import, account: account, type: import_type, overwrite: overwrite, state: :in_progress, imported_items: 0, processed_items: 0) }\n\n before do\n import.update(total_items: import.rows.count)\n end\n\n describe '#call', :sidekiq_fake do\n context 'when importing follows' do\n let(:import_type) { 'following' }\n let(:overwrite) { false }\n\n let!(:rows) do\n [\n { 'acct' => 'user@foo.bar' },\n { 'acct' => 'unknown@unknown.bar' },\n ].map { |data| import.rows.create!(data: data) }\n end\n\n before do\n account.follow!(Fabricate(:account))\n end\n\n it 'does not immediately change who the account follows' do\n expect { subject.call(import) }.to_not(change { account.reload.active_relationships.to_a })\n end\n\n it 'enqueues workers for the expected rows' do\n subject.call(import)\n expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows.map(&:id))\n end\n\n it 'requests to follow all the listed users once the workers have run' do\n subject.call(import)\n\n resolve_account_service_double = instance_double(ResolveAccountService)\n allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)\n allow(resolve_account_service_double).to receive(:call).with('user@foo.bar', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }\n allow(resolve_account_service_double).to receive(:call).with('unknown@unknown.bar', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }\n\n Import::RowWorker.drain\n\n expect(FollowRequest.includes(:target_account).where(account: account).map { |follow_request| follow_request.target_account.acct }).to contain_exactly('user@foo.bar', 'unknown@unknown.bar')\n end\n end\n\n context 'when importing follows with overwrite' do\n let(:import_type) { 'following' }\n let(:overwrite) { true }\n\n let!(:followed) { Fabricate(:account, username: 'followed', domain: 'foo.bar', protocol: :activitypub) }\n let!(:to_be_unfollowed) { Fabricate(:account, username: 'to_be_unfollowed', domain: 'foo.bar', protocol: :activitypub) }\n\n let!(:rows) do\n [\n { 'acct' => 'followed@foo.bar', 'show_reblogs' => false, 'notify' => true, 'languages' => ['en'] },\n { 'acct' => 'user@foo.bar' },\n { 'acct' => 'unknown@unknown.bar' },\n ].map { |data| import.rows.create!(data: data) }\n end\n\n before do\n account.follow!(followed, reblogs: true, notify: false)\n account.follow!(to_be_unfollowed)\n end\n\n it 'unfollows user not present on list' do\n subject.call(import)\n expect(account.following?(to_be_unfollowed)).to be false\n end\n\n it 'updates the existing follow relationship as expected' do\n expect { subject.call(import) }.to change { Follow.where(account: account, target_account: followed).pick(:show_reblogs, :notify, :languages) }.from([true, false, nil]).to([false, true, ['en']])\n end\n\n it 'enqueues workers for the expected rows' do\n subject.call(import)\n expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows[1..].map(&:id))\n end\n\n it 'requests to follow all the expected users once the workers have run' do\n subject.call(import)\n\n resolve_account_service_double = instance_double(ResolveAccountService)\n allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)\n allow(resolve_account_service_double).to receive(:call).with('user@foo.bar', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }\n allow(resolve_account_service_double).to receive(:call).with('unknown@unknown.bar', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }\n\n Import::RowWorker.drain\n\n expect(FollowRequest.includes(:target_account).where(account: account).map { |follow_request| follow_request.target_account.acct }).to contain_exactly('user@foo.bar', 'unknown@unknown.bar')\n end\n end\n\n context 'when importing blocks' do\n let(:import_type) { 'blocking' }\n let(:overwrite) { false }\n\n let!(:rows) do\n [\n { 'acct' => 'user@foo.bar' },\n { 'acct' => 'unknown@unknown.bar' },\n ].map { |data| import.rows.create!(data: data) }\n end\n\n before do\n account.block!(Fabricate(:account, username: 'already_blocked', domain: 'remote.org'))\n end\n\n it 'does not immediately change who the account blocks' do\n expect { subject.call(import) }.to_not(change { account.reload.blocking.to_a })\n end\n\n it 'enqueues workers for the expected rows' do\n subject.call(import)\n expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows.map(&:id))\n end\n\n it 'blocks all the listed users once the workers have run' do\n subject.call(import)\n\n resolve_account_service_double = instance_double(ResolveAccountService)\n allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)\n allow(resolve_account_service_double).to receive(:call).with('user@foo.bar', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }\n allow(resolve_account_service_double).to receive(:call).with('unknown@unknown.bar', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }\n\n Import::RowWorker.drain\n\n expect(account.blocking.map(&:acct)).to contain_exactly('already_blocked@remote.org', 'user@foo.bar', 'unknown@unknown.bar')\n end\n end\n\n context 'when importing blocks with overwrite' do\n let(:import_type) { 'blocking' }\n let(:overwrite) { true }\n\n let!(:blocked) { Fabricate(:account, username: 'blocked', domain: 'foo.bar', protocol: :activitypub) }\n let!(:to_be_unblocked) { Fabricate(:account, username: 'to_be_unblocked', domain: 'foo.bar', protocol: :activitypub) }\n\n let!(:rows) do\n [\n { 'acct' => 'blocked@foo.bar' },\n { 'acct' => 'user@foo.bar' },\n { 'acct' => 'unknown@unknown.bar' },\n ].map { |data| import.rows.create!(data: data) }\n end\n\n before do\n account.block!(blocked)\n account.block!(to_be_unblocked)\n end\n\n it 'unblocks user not present on list' do\n subject.call(import)\n expect(account.blocking?(to_be_unblocked)).to be false\n end\n\n it 'enqueues workers for the expected rows' do\n subject.call(import)\n expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows[1..].map(&:id))\n end\n\n it 'requests to follow all the expected users once the workers have run' do\n subject.call(import)\n\n resolve_account_service_double = instance_double(ResolveAccountService)\n allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)\n allow(resolve_account_service_double).to receive(:call).with('user@foo.bar', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }\n allow(resolve_account_service_double).to receive(:call).with('unknown@unknown.bar', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }\n\n Import::RowWorker.drain\n\n expect(account.blocking.map(&:acct)).to contain_exactly('blocked@foo.bar', 'user@foo.bar', 'unknown@unknown.bar')\n end\n end\n\n context 'when importing mutes' do\n let(:import_type) { 'muting' }\n let(:overwrite) { false }\n\n let!(:rows) do\n [\n { 'acct' => 'user@foo.bar' },\n { 'acct' => 'unknown@unknown.bar' },\n ].map { |data| import.rows.create!(data: data) }\n end\n\n before do\n account.mute!(Fabricate(:account, username: 'already_muted', domain: 'remote.org'))\n end\n\n it 'does not immediately change who the account blocks' do\n expect { subject.call(import) }.to_not(change { account.reload.muting.to_a })\n end\n\n it 'enqueues workers for the expected rows' do\n subject.call(import)\n expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows.map(&:id))\n end\n\n it 'mutes all the listed users once the workers have run' do\n subject.call(import)\n\n resolve_account_service_double = instance_double(ResolveAccountService)\n allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)\n allow(resolve_account_service_double).to receive(:call).with('user@foo.bar', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }\n allow(resolve_account_service_double).to receive(:call).with('unknown@unknown.bar', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }\n\n Import::RowWorker.drain\n\n expect(account.muting.map(&:acct)).to contain_exactly('already_muted@remote.org', 'user@foo.bar', 'unknown@unknown.bar')\n end\n end\n\n context 'when importing mutes with overwrite' do\n let(:import_type) { 'muting' }\n let(:overwrite) { true }\n\n let!(:muted) { Fabricate(:account, username: 'muted', domain: 'foo.bar', protocol: :activitypub) }\n let!(:to_be_unmuted) { Fabricate(:account, username: 'to_be_unmuted', domain: 'foo.bar', protocol: :activitypub) }\n\n let!(:rows) do\n [\n { 'acct' => 'muted@foo.bar', 'hide_notifications' => true },\n { 'acct' => 'user@foo.bar' },\n { 'acct' => 'unknown@unknown.bar' },\n ].map { |data| import.rows.create!(data: data) }\n end\n\n before do\n account.mute!(muted, notifications: false)\n account.mute!(to_be_unmuted)\n end\n\n it 'updates the existing mute as expected' do\n expect { subject.call(import) }.to change { Mute.where(account: account, target_account: muted).pick(:hide_notifications) }.from(false).to(true)\n end\n\n it 'unblocks user not present on list' do\n subject.call(import)\n expect(account.muting?(to_be_unmuted)).to be false\n end\n\n it 'enqueues workers for the expected rows' do\n subject.call(import)\n expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows[1..].map(&:id))\n end\n\n it 'requests to follow all the expected users once the workers have run' do\n subject.call(import)\n\n resolve_account_service_double = instance_double(ResolveAccountService)\n allow(ResolveAccountService).to receive(:new).and_return(resolve_account_service_double)\n allow(resolve_account_service_double).to receive(:call).with('user@foo.bar', any_args) { Fabricate(:account, username: 'user', domain: 'foo.bar', protocol: :activitypub) }\n allow(resolve_account_service_double).to receive(:call).with('unknown@unknown.bar', any_args) { Fabricate(:account, username: 'unknown', domain: 'unknown.bar', protocol: :activitypub) }\n\n Import::RowWorker.drain\n\n expect(account.muting.map(&:acct)).to contain_exactly('muted@foo.bar', 'user@foo.bar', 'unknown@unknown.bar')\n end\n end\n\n context 'when importing domain blocks' do\n let(:import_type) { 'domain_blocking' }\n let(:overwrite) { false }\n\n let!(:rows) do\n [\n { 'domain' => 'blocked.com' },\n { 'domain' => 'to_block.com' },\n ].map { |data| import.rows.create!(data: data) }\n end\n\n before do\n account.block_domain!('alreadyblocked.com')\n account.block_domain!('blocked.com')\n end\n\n it 'blocks all the new domains' do\n subject.call(import)\n expect(account.domain_blocks.pluck(:domain)).to contain_exactly('alreadyblocked.com', 'blocked.com', 'to_block.com')\n end\n\n it 'marks the import as finished' do\n subject.call(import)\n expect(import.reload.finished?).to be true\n end\n end\n\n context 'when importing domain blocks with overwrite' do\n let(:import_type) { 'domain_blocking' }\n let(:overwrite) { true }\n\n let!(:rows) do\n [\n { 'domain' => 'blocked.com' },\n { 'domain' => 'to_block.com' },\n ].map { |data| import.rows.create!(data: data) }\n end\n\n before do\n account.block_domain!('alreadyblocked.com')\n account.block_domain!('blocked.com')\n end\n\n it 'blocks all the new domains' do\n subject.call(import)\n expect(account.domain_blocks.pluck(:domain)).to contain_exactly('blocked.com', 'to_block.com')\n end\n\n it 'marks the import as finished' do\n subject.call(import)\n expect(import.reload.finished?).to be true\n end\n end\n\n context 'when importing bookmarks' do\n let(:import_type) { 'bookmarks' }\n let(:overwrite) { false }\n\n let!(:already_bookmarked) { Fabricate(:status, uri: 'https:\/\/already.bookmarked\/1') }\n let!(:status) { Fabricate(:status, uri: 'https:\/\/foo.bar\/posts\/1') }\n let!(:inaccessible_status) { Fabricate(:status, uri: 'https:\/\/foo.bar\/posts\/inaccessible', visibility: :direct) }\n let!(:bookmarked) { Fabricate(:status, uri: 'https:\/\/foo.bar\/posts\/already-bookmarked') }\n\n let!(:rows) do\n [\n { 'uri' => status.uri },\n { 'uri' => inaccessible_status.uri },\n { 'uri' => bookmarked.uri },\n { 'uri' => 'https:\/\/domain.unknown\/foo' },\n { 'uri' => 'https:\/\/domain.unknown\/private' },\n ].map { |data| import.rows.create!(data: data) }\n end\n\n before do\n account.bookmarks.create!(status: already_bookmarked)\n account.bookmarks.create!(status: bookmarked)\n end\n\n it 'enqueues workers for the expected rows' do\n subject.call(import)\n expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows.map(&:id))\n end\n\n it 'updates the bookmarks as expected once the workers have run' do\n subject.call(import)\n\n service_double = instance_double(ActivityPub::FetchRemoteStatusService)\n allow(ActivityPub::FetchRemoteStatusService).to receive(:new).and_return(service_double)\n allow(service_double).to receive(:call).with('https:\/\/domain.unknown\/foo') { Fabricate(:status, uri: 'https:\/\/domain.unknown\/foo') }\n allow(service_double).to receive(:call).with('https:\/\/domain.unknown\/private') { Fabricate(:status, uri: 'https:\/\/domain.unknown\/private', visibility: :direct) }\n\n Import::RowWorker.drain\n\n expect(account.bookmarks.map { |bookmark| bookmark.status.uri }).to contain_exactly(already_bookmarked.uri, status.uri, bookmarked.uri, 'https:\/\/domain.unknown\/foo')\n end\n end\n\n context 'when importing bookmarks with overwrite' do\n let(:import_type) { 'bookmarks' }\n let(:overwrite) { true }\n\n let!(:already_bookmarked) { Fabricate(:status, uri: 'https:\/\/already.bookmarked\/1') }\n let!(:status) { Fabricate(:status, uri: 'https:\/\/foo.bar\/posts\/1') }\n let!(:inaccessible_status) { Fabricate(:status, uri: 'https:\/\/foo.bar\/posts\/inaccessible', visibility: :direct) }\n let!(:bookmarked) { Fabricate(:status, uri: 'https:\/\/foo.bar\/posts\/already-bookmarked') }\n\n let!(:rows) do\n [\n { 'uri' => status.uri },\n { 'uri' => inaccessible_status.uri },\n { 'uri' => bookmarked.uri },\n { 'uri' => 'https:\/\/domain.unknown\/foo' },\n { 'uri' => 'https:\/\/domain.unknown\/private' },\n ].map { |data| import.rows.create!(data: data) }\n end\n\n before do\n account.bookmarks.create!(status: already_bookmarked)\n account.bookmarks.create!(status: bookmarked)\n end\n\n it 'enqueues workers for the expected rows' do\n subject.call(import)\n expect(Import::RowWorker.jobs.pluck('args').flatten).to match_array(rows.map(&:id))\n end\n\n it 'updates the bookmarks as expected once the workers have run' do\n subject.call(import)\n\n service_double = instance_double(ActivityPub::FetchRemoteStatusService)\n allow(ActivityPub::FetchRemoteStatusService).to receive(:new).and_return(service_double)\n allow(service_double).to receive(:call).with('https:\/\/domain.unknown\/foo') { Fabricate(:status, uri: 'https:\/\/domain.unknown\/foo') }\n allow(service_double).to receive(:call).with('https:\/\/domain.unknown\/private') { Fabricate(:status, uri: 'https:\/\/domain.unknown\/private', visibility: :direct) }\n\n Import::RowWorker.drain\n\n expect(account.bookmarks.map { |bookmark| bookmark.status.uri }).to contain_exactly(status.uri, bookmarked.uri, 'https:\/\/domain.unknown\/foo')\n end\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass AfterBlockService < BaseService\n def call(account, target_account)\n @account = account\n @target_account = target_account\n\n clear_home_feed!\n clear_list_feeds!\n clear_notifications!\n clear_conversations!\n end\n\n private\n\n def clear_home_feed!\n FeedManager.instance.clear_from_home(@account, @target_account)\n end\n\n def clear_list_feeds!\n FeedManager.instance.clear_from_lists(@account, @target_account)\n end\n\n def clear_conversations!\n AccountConversation.where(account: @account).where('? = ANY(participant_account_ids)', @target_account.id).in_batches.destroy_all\n end\n\n def clear_notifications!\n Notification.where(account: @account).where(from_account: @target_account).in_batches.delete_all\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe AfterBlockService, type: :service do\n subject { described_class.new.call(account, target_account) }\n\n let(:account) { Fabricate(:account) }\n let(:target_account) { Fabricate(:account) }\n let(:status) { Fabricate(:status, account: target_account) }\n let(:other_status) { Fabricate(:status, account: target_account) }\n let(:other_account_status) { Fabricate(:status) }\n let(:other_account_reblog) { Fabricate(:status, reblog_of_id: other_status.id) }\n\n describe 'home timeline' do\n let(:home_timeline_key) { FeedManager.instance.key(:home, account.id) }\n\n before do\n redis.del(home_timeline_key)\n end\n\n it \"clears account's statuses\" do\n FeedManager.instance.push_to_home(account, status)\n FeedManager.instance.push_to_home(account, other_account_status)\n FeedManager.instance.push_to_home(account, other_account_reblog)\n\n expect { subject }.to change {\n redis.zrange(home_timeline_key, 0, -1)\n }.from([status.id.to_s, other_account_status.id.to_s, other_account_reblog.id.to_s]).to([other_account_status.id.to_s])\n end\n end\n\n describe 'lists' do\n let(:list) { Fabricate(:list, account: account) }\n let(:list_timeline_key) { FeedManager.instance.key(:list, list.id) }\n\n before do\n redis.del(list_timeline_key)\n end\n\n it \"clears account's statuses\" do\n FeedManager.instance.push_to_list(list, status)\n FeedManager.instance.push_to_list(list, other_account_status)\n FeedManager.instance.push_to_list(list, other_account_reblog)\n\n expect { subject }.to change {\n redis.zrange(list_timeline_key, 0, -1)\n }.from([status.id.to_s, other_account_status.id.to_s, other_account_reblog.id.to_s]).to([other_account_status.id.to_s])\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass MuteService < BaseService\n def call(account, target_account, notifications: nil, duration: 0)\n return if account.id == target_account.id\n\n mute = account.mute!(target_account, notifications: notifications, duration: duration)\n\n if mute.hide_notifications?\n BlockWorker.perform_async(account.id, target_account.id)\n else\n MuteWorker.perform_async(account.id, target_account.id)\n end\n\n DeleteMuteWorker.perform_at(duration.seconds, mute.id) if duration != 0\n\n mute\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe MuteService, type: :service do\n subject { described_class.new.call(account, target_account) }\n\n let(:account) { Fabricate(:account) }\n let(:target_account) { Fabricate(:account) }\n\n describe 'home timeline' do\n let(:status) { Fabricate(:status, account: target_account) }\n let(:other_account_status) { Fabricate(:status) }\n let(:home_timeline_key) { FeedManager.instance.key(:home, account.id) }\n\n before do\n redis.del(home_timeline_key)\n end\n\n it \"clears account's statuses\" do\n FeedManager.instance.push_to_home(account, status)\n FeedManager.instance.push_to_home(account, other_account_status)\n\n expect { subject }.to change {\n redis.zrange(home_timeline_key, 0, -1)\n }.from([status.id.to_s, other_account_status.id.to_s]).to([other_account_status.id.to_s])\n end\n end\n\n it 'mutes account' do\n expect { subject }.to change {\n account.muting?(target_account)\n }.from(false).to(true)\n end\n\n context 'without specifying a notifications parameter' do\n it 'mutes notifications from the account' do\n expect { subject }.to change {\n account.muting_notifications?(target_account)\n }.from(false).to(true)\n end\n end\n\n context 'with a true notifications parameter' do\n subject { described_class.new.call(account, target_account, notifications: true) }\n\n it 'mutes notifications from the account' do\n expect { subject }.to change {\n account.muting_notifications?(target_account)\n }.from(false).to(true)\n end\n end\n\n context 'with a false notifications parameter' do\n subject { described_class.new.call(account, target_account, notifications: false) }\n\n it 'does not mute notifications from the account' do\n expect { subject }.to_not change {\n account.muting_notifications?(target_account)\n }.from(false)\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass RemoveFromFollowersService < BaseService\n include Payloadable\n\n def call(source_account, target_accounts)\n source_account.passive_relationships.where(account_id: target_accounts).find_each do |follow|\n follow.destroy\n\n create_notification(follow) if source_account.local? && !follow.account.local? && follow.account.activitypub?\n end\n end\n\n private\n\n def create_notification(follow)\n ActivityPub::DeliveryWorker.perform_async(build_json(follow), follow.target_account_id, follow.account.inbox_url)\n end\n\n def build_json(follow)\n Oj.dump(serialize_payload(follow, ActivityPub::RejectFollowSerializer))\n end\nend\n\n```","RESPONSE":"# frozen_string_literal: true\n\nrequire 'rails_helper'\n\nRSpec.describe RemoveFromFollowersService, type: :service do\n subject { described_class.new }\n\n let(:bob) { Fabricate(:account, username: 'bob') }\n\n describe 'local' do\n let(:sender) { Fabricate(:account, username: 'alice') }\n\n before do\n Follow.create(account: sender, target_account: bob)\n subject.call(bob, sender)\n end\n\n it 'does not create follow relation' do\n expect(bob.followed_by?(sender)).to be false\n end\n end\n\n describe 'remote ActivityPub' do\n let(:sender) { Fabricate(:account, username: 'alice', domain: 'example.com', protocol: :activitypub, inbox_url: 'http:\/\/example.com\/inbox') }\n\n before do\n Follow.create(account: sender, target_account: bob)\n stub_request(:post, sender.inbox_url).to_return(status: 200)\n subject.call(bob, sender)\n end\n\n it 'does not create follow relation' do\n expect(bob.followed_by?(sender)).to be false\n end\n\n it 'sends a reject activity' do\n expect(a_request(:post, sender.inbox_url)).to have_been_made.once\n end\n end\nend\n"} {"INSTRUCTION":"Write RSpec test file for following ruby class\n```ruby\n# frozen_string_literal: true\n\nclass FetchLinkCardService < BaseService\n include Redisable\n include Lockable\n\n URL_PATTERN = %r{\n (#{Twitter::TwitterText::Regex[:valid_url_preceding_chars]}) # $1 preceding chars\n ( # $2 URL\n (https?:\/\/) # $3 Protocol (required)\n (#{Twitter::TwitterText::Regex[:valid_domain]}) # $4 Domain(s)\n (?::(#{Twitter::TwitterText::Regex[:valid_port_number]}))? # $5 Port number (optional)\n (\/#{Twitter::TwitterText::Regex[:valid_url_path]}*)? # $6 URL Path and anchor\n (\\?#{Twitter::TwitterText::Regex[:valid_url_query_chars]}*#{Twitter::TwitterText::Regex[:valid_url_query_ending_chars]})? # $7 Query String\n )\n }iox\n\n def call(status)\n @status = status\n @original_url = parse_urls\n\n return if @original_url.nil? || @status.with_preview_card?\n\n @url = @original_url.to_s\n\n with_redis_lock(\"fetch:#{@original_url}\") do\n @card = PreviewCard.find_by(url: @url)\n process_url if @card.nil? || @card.updated_at <= 2.weeks.ago || @card.missing_image?\n end\n\n attach_card if @card&.persisted?\n rescue HTTP::Error, OpenSSL::SSL::SSLError, Addressable::URI::InvalidURIError, Mastodon::HostValidationError, Mastodon::LengthValidationError => e\n Rails.logger.debug { \"Error fetching link #{@original_url}: #{e}\" }\n nil\n end\n\n private\n\n def process_url\n @card ||= PreviewCard.new(url: @url)\n\n attempt_oembed || attempt_opengraph\n end\n\n def html\n return @html if defined?(@html)\n\n @html = Request.new(:get, @url).add_headers('Accept' => 'text\/html', 'User-Agent' => \"#{Mastodon::Version.user_agent} Bot\").perform do |res|\n next unless res.code == 200 && res.mime_type == 'text\/html'\n\n # We follow redirects, and ideally we want to save the preview card for\n # the destination URL and not any link shortener in-between, so here\n # we set the URL to the one of the last response in the redirect chain\n @url = res.request.uri.to_s\n @card = PreviewCard.find_or_initialize_by(url: @url) if @card.url != @url\n\n @html_charset = res.charset\n\n res.body_with_limit\n end\n end\n\n def attach_card\n with_redis_lock(\"attach_card:#{@status.id}\") do\n return if @status.with_preview_card?\n\n PreviewCardsStatus.create(status: @status, preview_card: @card, url: @original_url)\n Rails.cache.delete(@status)\n Trends.links.register(@status)\n end\n end\n\n def parse_urls\n urls = if @status.local?\n @status.text.scan(URL_PATTERN).map { |array| Addressable::URI.parse(array[1]).normalize }\n else\n document = Nokogiri::HTML(@status.text)\n links = document.css('a')\n\n links.filter_map { |a| Addressable::URI.parse(a['href']) unless skip_link?(a) }.filter_map(&:normalize)\n end\n\n urls.reject { |uri| bad_url?(uri) }.first\n end\n\n def bad_url?(uri)\n # Avoid local instance URLs and invalid URLs\n uri.host.blank? || TagManager.instance.local_url?(uri.to_s) || !%w(http https).include?(uri.scheme)\n end\n\n def mention_link?(anchor)\n @status.mentions.any? do |mention|\n anchor['href'] == ActivityPub::TagManager.instance.url_for(mention.account)\n end\n end\n\n def skip_link?(anchor)\n # Avoid links for hashtags and mentions (microformats)\n anchor['rel']&.include?('tag') || anchor['class']&.match?(\/u-url|h-card\/) || mention_link?(anchor)\n end\n\n def attempt_oembed\n service = FetchOEmbedService.new\n url_domain = Addressable::URI.parse(@url).normalized_host\n cached_endpoint = Rails.cache.read(\"oembed_endpoint:#{url_domain}\")\n\n embed = service.call(@url, cached_endpoint: cached_endpoint) unless cached_endpoint.nil?\n embed ||= service.call(@url, html: html) unless html.nil?\n\n return false if embed.nil?\n\n url = Addressable::URI.parse(service.endpoint_url)\n\n @card.type = embed[:type]\n @card.title = embed[:title] || ''\n @card.author_name = embed[:author_name] || ''\n @card.author_url = embed[:author_url].present? ? (url + embed[:author_url]).to_s : ''\n @card.provider_name = embed[:provider_name] || ''\n @card.provider_url = embed[:provider_url].present? ? (url + embed[:provider_url]).to_s : ''\n @card.width = 0\n @card.height = 0\n\n case @card.type\n when 'link'\n @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?\n when 'photo'\n return false if embed[:url].blank?\n\n @card.embed_url = (url + embed[:url]).to_s\n @card.image_remote_url = (url + embed[:url]).to_s\n @card.width = embed[:width].presence || 0\n @card.height = embed[:height].presence || 0\n when 'video'\n @card.width = embed[:width].presence || 0\n @card.height = embed[:height].presence || 0\n @card.html = Sanitize.fragment(embed[:html], Sanitize::Config::MASTODON_OEMBED)\n @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?\n when 'rich'\n # Most providers rely on