FIX: Clean up unused staged users job not completing.

This commit is contained in:
Guo Xiang Tan 2017-04-26 10:51:36 +08:00
parent c3b5bca0e8
commit daa97c40ce
2 changed files with 52 additions and 5 deletions

View File

@ -6,11 +6,21 @@ module Jobs
def execute(args)
destroyer = UserDestroyer.new(Discourse.system_user)
User.joins(:user_stat)
.where(staged: true)
.where("users.created_at < ?", 1.year.ago)
.where("user_stats.post_count = 0")
.find_each { |user| destroyer.destroy(user) }
User.joins("LEFT JOIN posts ON posts.user_id = users.id")
.where("posts.user_id IS NULL")
.where(staged: true)
.where("users.created_at < ?", 1.year.ago)
.find_each do |user|
begin
destroyer.destroy(user)
rescue => e
Discourse.handle_job_exception(e,
message: "Cleaning up unused staged user",
extra: { user_id: user.id }
)
end
end
end
end

View File

@ -0,0 +1,37 @@
require 'rails_helper'
RSpec.describe Jobs::CleanUpUnusedStagedUsers do
let(:user) { Fabricate(:user) }
let(:staged_user) { Fabricate(:user, staged: true) }
context 'when staged user is unused' do
it 'should clean up the staged user' do
user
staged_user.update!(created_at: 2.years.ago)
expect { described_class.new.execute({}) }.to change { User.count }.by(-1)
expect(User.find_by(id: staged_user.id)).to eq(nil)
end
describe 'when staged user is not old enough' do
it 'should not clean up the staged user' do
user
staged_user.update!(created_at: 5.months.ago)
expect { described_class.new.execute({}) }.to_not change { User.count }
expect(User.find_by(id: staged_user.id)).to eq(staged_user)
end
end
end
context 'when staged user is not unused' do
it 'should not clean up the staged user' do
user
Fabricate(:post, user: staged_user)
user.update!(created_at: 2.years.ago)
expect { described_class.new.execute({}) }.to_not change { User.count }
expect(User.find_by(id: staged_user.id)).to eq(staged_user)
end
end
end