Change CreateJob to CreateWorker and move to sidekiq (#5559)

* Create new CreateWorker

* Create new spec for CreateWorker

* Change CreateJob to CreateWorker and move to sidekiq

* Update worker

* Update priority of Reactions Create Worker

* Remove leading spaces from spec
This commit is contained in:
Lucas Hiago 2020-01-20 13:29:13 -03:00 committed by Molly Struve
parent 511f7418dd
commit fb5cb7005c
3 changed files with 75 additions and 6 deletions

View file

@ -24,12 +24,7 @@ module Api
verify_authenticity_token
reactable_ids = JSON.parse(params[:articles]).map { |article| article["id"] }
reactable_ids.each do |article_id|
Reactions::CreateJob.perform_later(
user_id: current_user.id,
reactable_id: article_id,
reactable_type: "Article",
category: "readinglist",
)
Reactions::CreateWorker.perform_async(current_user.id, article_id, "Article", "readinglist")
end
end

View file

@ -0,0 +1,22 @@
module Reactions
class CreateWorker
include Sidekiq::Worker
sidekiq_options queue: :high_priority, retry: 10
def perform(user_id, reactable_id, reactable_type, category)
return unless %w[Article Comment].include?(reactable_type)
user = User.find_by(id: user_id)
reactable = reactable_type.constantize.find_by(id: reactable_id)
return unless user && reactable
Reaction.create!(
user: user,
reactable: reactable,
category: category,
)
end
end
end

View file

@ -0,0 +1,52 @@
require "rails_helper"
RSpec.describe Reactions::CreateWorker, type: :worker do
describe "#perform" do
let(:reactable_type) { "Comment" }
let(:user_id) { 8 }
let(:reactable_id) { 1 }
let(:category) { "like" }
let(:worker) { subject }
context "when no user found" do
before do
allow(User).to receive(:find_by)
allow(Reaction).to receive(:create)
end
it "does not create a reaction" do
worker.perform(user_id, reactable_id, reactable_type, category)
expect(Reaction).not_to have_received(:create)
end
end
context "when no reactable found" do
before do
allow(reactable_type.constantize).to receive(:find_by)
allow(Reaction).to receive(:create)
end
it "does not create a reaction" do
worker.perform(user_id, reactable_id, reactable_type, category)
expect(Reaction).not_to have_received(:create)
end
end
context "when user + reactable" do
let(:user) { create(:user) }
let(:reactable) { create(:comment, commentable: create(:article)) }
it "calls the service" do
allow(Reaction).to receive(:create!).with(user: user, reactable: reactable, category: "like")
worker.perform(user.id, reactable.id, reactable_type, category)
expect(Reaction).to have_received(:create!).with(user: user, reactable: reactable, category: "like")
end
it "creates a reaction" do
expect do
worker.perform(user.id, reactable.id, reactable_type, category)
end.to change(Reaction, :count).by(1)
end
end
end
end