repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/find_subscriptions_with_missing_charge_worker_spec.rb | spec/sidekiq/find_subscriptions_with_missing_charge_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe FindSubscriptionsWithMissingChargeWorker do
describe "#perform" do
before do
described_class.jobs.clear
RecurringChargeWorker.jobs.clear
end
context "without a batch_number" do
it "queues a job for each of the 10 batches" do
freeze_time
described_class.new.perform
expect(described_class.jobs.size).to eq(10)
expect(described_class).to have_enqueued_sidekiq_job(0)
expect(described_class).to have_enqueued_sidekiq_job(1).in(20.minutes)
expect(described_class).to have_enqueued_sidekiq_job(4).in(80.minutes)
expect(described_class).to have_enqueued_sidekiq_job(9).in(180.minutes)
end
end
context "with a batch_number" do
before do
@product = create(:membership_product_with_preset_tiered_pricing)
@subscription = create(:subscription, link: @product, id: 1_000)
@initial_purchase_time = Time.utc(2020, 1, 1)
@six_months_after_purchase = Time.utc(2020, 6, 2)
price_cents = @product.default_tier.prices.first.price_cents
create(:membership_purchase, subscription: @subscription, succeeded_at: @initial_purchase_time,
price_cents:)
end
context "not matching a subscription id" do
before do
@batch_number = 1
end
it "does not queue overdue subscriptions with the wrong id" do
travel_to @six_months_after_purchase do
described_class.new.perform(@batch_number)
expect(RecurringChargeWorker.jobs.size).to eq(0)
end
end
end
context "matching a subscription id" do
before do
@batch_number = 0
end
it "queues subscriptions according to last charge's date" do
travel_to @six_months_after_purchase do
described_class.new.perform(@batch_number)
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(@subscription.id, true)
end
end
it "does not queue subscriptions that are not overdue for a charge" do
travel_to @initial_purchase_time + 15.days do
described_class.new.perform(@batch_number)
expect(RecurringChargeWorker.jobs.size).to eq(0)
end
end
it "does not queue subscriptions that are less than 75 minutes overdue for a charge" do
subscription_end_time = @initial_purchase_time + @subscription.period
travel_to subscription_end_time + 74.minutes do
described_class.new.perform(@batch_number)
expect(RecurringChargeWorker.jobs.size).to eq(0)
end
travel_to subscription_end_time + 76.minutes do
described_class.new.perform(@batch_number)
expect(RecurringChargeWorker).to have_enqueued_sidekiq_job(@subscription.id, true)
end
end
it "does not queue free subscriptions" do
travel_to @six_months_after_purchase do
@subscription.original_purchase.update_columns(price_cents: 0, displayed_price_cents: 0)
described_class.new.perform(@batch_number)
expect(RecurringChargeWorker.jobs.size).to eq(0)
end
end
it "queues subscriptions that were discounted to free with an elapsed discount" do
offer_code = create(:offer_code, products: [@product], duration_in_months: 1, amount_cents: @product.price_cents)
original_purchase = @subscription.original_purchase
original_purchase.update_columns(offer_code_id: offer_code.id, displayed_price_cents: 0, price_cents: 0)
original_purchase.create_purchase_offer_code_discount(offer_code:, offer_code_amount: @product.default_tier.prices.first.price_cents, offer_code_is_percent: false, pre_discount_minimum_price_cents: @product.default_tier.prices.first.price_cents, duration_in_billing_cycles: 1)
described_class.new.perform(@batch_number)
expect(RecurringChargeWorker.jobs.size).to eq(1)
end
it "does not queue subscriptions to products from suspended users" do
travel_to @six_months_after_purchase do
@subscription.link.user.update!(user_risk_state: "suspended_for_fraud")
described_class.new.perform(@batch_number)
expect(RecurringChargeWorker.jobs.size).to eq(0)
end
end
it "does not queue subscriptions that already have a charge in progress" do
travel_to @six_months_after_purchase do
create(:recurring_membership_purchase, subscription: @subscription, purchase_state: "in_progress")
described_class.new.perform(@batch_number)
expect(RecurringChargeWorker.jobs.size).to eq(0)
end
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/force_finish_long_running_community_chat_recap_runs_job_spec.rb | spec/sidekiq/force_finish_long_running_community_chat_recap_runs_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe ForceFinishLongRunningCommunityChatRecapRunsJob do
let(:job) { described_class.new }
describe "#perform" do
let(:recap_run) { create(:community_chat_recap_run) }
let(:community) { create(:community) }
let!(:recap) { create(:community_chat_recap, community:, community_chat_recap_run: recap_run) }
context "when recap run is already finished" do
before { recap_run.update!(finished_at: 1.hour.ago) }
it "does nothing" do
expect do
expect do
job.perform
end.not_to change { recap.reload.status }
end.not_to change { recap_run.reload.finished_at }
end
end
context "when recap run is running but not old enough" do
before { recap_run.update!(finished_at: nil, created_at: 1.hour.ago) }
it "does not update any recaps" do
expect do
expect do
job.perform
end.not_to change { recap.reload.status }
end.not_to change { recap_run.reload.finished_at }
end
end
context "when recap run is running and old enough" do
before { recap_run.update!(finished_at: nil, created_at: 7.hours.ago) }
context "when recap is pending" do
it "updates recap status to failed" do
expect do
job.perform
end.to change { recap.reload.status }.from("pending").to("failed")
.and change { recap.error_message }.to("Recap run cancelled because it took longer than 6 hours to complete")
.and change { recap_run.reload.finished_at }.from(nil).to(be_present)
.and change { recap_run.notified_at }.from(nil).to(be_present)
end
end
context "when recap is not pending" do
before { recap.update!(status: "finished") }
it "does not update recap status" do
expect do
expect do
job.perform
end.not_to change { recap.reload.status }
end.to change { recap_run.reload.finished_at }.from(nil).to(be_present)
.and change { recap_run.notified_at }.from(nil).to(be_present)
expect(recap.error_message).to be_nil
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/generate_large_sellers_analytics_cache_worker_spec.rb | spec/sidekiq/generate_large_sellers_analytics_cache_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GenerateLargeSellersAnalyticsCacheWorker do
describe "#perform" do
before do
@user_1 = create(:user)
create(:large_seller, user: @user_1)
@user_2 = create(:user)
create(:large_seller, user: @user_2)
create(:user, current_sign_in_at: 1.day.ago) # not a large seller
end
it "calls CreatorAnalytics::CachingProxy#generate_cache on large sellers" do
[@user_1, @user_2].each do |user|
service_object = double("CreatorAnalytics::CachingProxy object")
expect(CreatorAnalytics::CachingProxy).to receive(:new).with(user).and_return(service_object)
expect(service_object).to receive(:generate_cache)
end
described_class.new.perform
end
it "rescues and report errors" do
# user 1
expect(CreatorAnalytics::CachingProxy).to receive(:new).with(@user_1).and_raise("Something went wrong")
expect(Bugsnag).to receive(:notify) do |exception|
expect(exception.message).to eq("Something went wrong")
end
# user 2
service_object = double("CreatorAnalytics::CachingProxy object")
expect(CreatorAnalytics::CachingProxy).to receive(:new).with(@user_2).and_return(service_object)
expect(service_object).to receive(:generate_cache)
described_class.new.perform
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/generate_username_job_spec.rb | spec/sidekiq/generate_username_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GenerateUsernameJob do
describe "#perform" do
context "username is present" do
it "does not generate a new username" do
user = create(:user, username: "foo")
expect_any_instance_of(UsernameGeneratorService).not_to receive(:username)
described_class.new.perform(user.id)
end
end
context "username is blank" do
it "generates a new username" do
user = create(:user, username: nil)
expect_any_instance_of(UsernameGeneratorService).to receive(:username).and_return("foo")
described_class.new.perform(user.id)
expect(user.reload.username).to eq("foo")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/handle_sns_transcoder_event_worker_spec.rb | spec/sidekiq/handle_sns_transcoder_event_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe HandleSnsTranscoderEventWorker do
describe "#perform" do
before do
@product = create(:product)
@product.product_files << create(:product_file, link: @product,
url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/files/43a5363194e74e9ee75b6203eaea6705/original/test.mp4",
filegroup: "video", width: 640, height: 360, bitrate: 3_000)
end
it "marks the transcoded_video object as completed", :vcr do
travel_to(Time.current) do
TranscodeVideoForStreamingWorker.new.perform(@product.product_files.last.id, ProductFile.name)
expect(TranscodedVideo.last.state).to eq "processing"
TranscodedVideo.all.each do |transcoded_video|
webhook_params = {
"Type" => "Notification",
"Message" => "{\"state\" : \"COMPLETED\", \"jobId\": \"#{transcoded_video.job_id}\"}"
}
described_class.new.perform(webhook_params)
end
expect(TranscodedVideo.last.state).to eq "completed"
end
end
it "marks the transcoded_video object as failed", :vcr do
product_file_id = @product.product_files.last.id
TranscodeVideoForStreamingWorker.new.perform(product_file_id, ProductFile.name)
webhook_params = {
"Type" => "Notification",
"Message" => "{\"state\" : \"ERROR\", \"jobId\": \"#{TranscodedVideo.last.job_id}\"}"
}
described_class.new.perform(webhook_params)
expect(TranscodedVideo.last.state).to eq "error"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/expire_transcoded_videos_job_spec.rb | spec/sidekiq/expire_transcoded_videos_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ExpireTranscodedVideosJob do
describe "#perform" do
it "marks old stamped pdfs as deleted" do
$redis.set(RedisKey.transcoded_videos_recentness_limit_in_months, 3)
record_1 = create(:transcoded_video, last_accessed_at: nil)
record_2 = create(:transcoded_video, last_accessed_at: 10.days.ago)
record_3 = create(:transcoded_video, last_accessed_at: 9.months.ago)
described_class.new.perform
expect(record_1.reload.deleted?).to be(false)
expect(record_1.product_file.reload.is_transcoded_for_hls?).to be(true)
expect(record_2.reload.deleted?).to be(false)
expect(record_2.product_file.reload.is_transcoded_for_hls?).to be(true)
expect(record_3.reload.deleted?).to be(true)
expect(record_3.product_file.reload.is_transcoded_for_hls?).to be(false)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/handle_new_bank_account_worker_spec.rb | spec/sidekiq/handle_new_bank_account_worker_spec.rb | # frozen_string_literal: true
describe HandleNewBankAccountWorker do
describe "perform" do
let(:bank_account) { create(:ach_account) }
it "calls StripeMerchantAccountManager.handle_new_bank_account with the bank account object" do
expect(StripeMerchantAccountManager).to receive(:handle_new_bank_account).with(bank_account)
described_class.new.perform(bank_account.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/update_large_sellers_sales_count_job_spec.rb | spec/sidekiq/update_large_sellers_sales_count_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateLargeSellersSalesCountJob do
describe "#perform" do
let(:user1) { create(:user) }
let(:user2) { create(:user) }
let(:product1) { create(:product, user: user1) }
let(:product2) { create(:product, user: user2) }
let!(:large_seller1) { create(:large_seller, user: user1, sales_count: 1000) }
let!(:large_seller2) { create(:large_seller, user: user2, sales_count: 2000) }
before do
create_list(:purchase, 5, link: product1, purchase_state: "successful")
create_list(:purchase, 3, link: product2, purchase_state: "successful")
end
it "updates sales_count for large sellers when count has changed" do
expect(large_seller1.sales_count).to eq(1000)
expect(large_seller2.sales_count).to eq(2000)
described_class.new.perform
large_seller1.reload
large_seller2.reload
expect(large_seller1.sales_count).to eq(5)
expect(large_seller2.sales_count).to eq(3)
end
it "does not update sales_count when it hasn't changed" do
large_seller1.update!(sales_count: 5)
large_seller2.update!(sales_count: 3)
expect(large_seller1).not_to receive(:update!)
expect(large_seller2).not_to receive(:update!)
described_class.new.perform
end
it "skips large sellers without users" do
large_seller1.update!(user: nil)
expect do
described_class.new.perform
end.not_to raise_error
large_seller2.reload
expect(large_seller2.sales_count).to eq(3)
end
it "updates sales_count even when below threshold" do
user3 = create(:user)
product3 = create(:product, user: user3)
large_seller3 = create(:large_seller, user: user3, sales_count: 1500)
create_list(:purchase, 500, link: product3, seller: user3, purchase_state: "successful")
described_class.new.perform
large_seller3.reload
expect(large_seller3.sales_count).to eq(500)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/delete_wishlist_products_job_spec.rb | spec/sidekiq/delete_wishlist_products_job_spec.rb | # frozen_string_literal: true
describe DeleteWishlistProductsJob do
describe "#perform" do
let(:product) { create(:product) }
let!(:wishlist_product) { create(:wishlist_product, product:) }
let!(:unrelated_wishlist_product) { create(:wishlist_product) }
it "deletes associated wishlist products" do
product.mark_deleted!
described_class.new.perform(product.id)
expect(wishlist_product.reload).to be_deleted
expect(unrelated_wishlist_product).not_to be_deleted
end
it "does nothing if the product was not actually deleted" do
described_class.new.perform(product.id)
expect(wishlist_product.reload).not_to be_deleted
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/delete_stripe_apple_pay_domain_worker_spec.rb | spec/sidekiq/delete_stripe_apple_pay_domain_worker_spec.rb | # frozen_string_literal: true
describe DeleteStripeApplePayDomainWorker, :vcr do
describe "#perform" do
before do
@user = create(:user)
@domain = "sampleusername.gumroad.dev"
end
it "deletes StripeApplePayDomain record when record exists on Stripe" do
response = Stripe::ApplePayDomain.create(domain_name: @domain)
StripeApplePayDomain.create!(user_id: @user.id, domain: @domain, stripe_id: response.id)
described_class.new.perform(@user.id, @domain)
expect(StripeApplePayDomain.count).to eq(0)
end
it "deletes StripeApplePayDomain record when record doesn't exist on Stripe" do
StripeApplePayDomain.create!(user_id: @user.id, domain: @domain, stripe_id: "random_stripe_id")
described_class.new.perform(@user.id, @domain)
expect(StripeApplePayDomain.count).to eq(0)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/update_sales_related_products_infos_job_spec.rb | spec/sidekiq/update_sales_related_products_infos_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateSalesRelatedProductsInfosJob do
describe "#perform" do
before do
Feature.activate(:update_sales_related_products_infos)
end
let(:seller) { create(:named_seller) }
let(:product1) { create(:product, user: seller) }
let(:product2) { create(:product, user: seller) }
let!(:purchase) { create(:purchase, link: product2, email: "shared@gumroad.com") }
let(:new_purchase) { create(:purchase, link: product1, email: "shared@gumroad.com") }
context "when a SalesRelatedProductsInfo record exists" do
let!(:sales_related_products_info) { create(:sales_related_products_info, smaller_product: product2, larger_product: product1, sales_count: 2) }
context "when increment is false" do
it "decrements the sales_count" do
described_class.new.perform(new_purchase.id, false)
expect(sales_related_products_info.reload.sales_count).to eq(1)
end
end
context "when increment is true" do
it "increments the sales_count" do
described_class.new.perform(new_purchase.id)
expect(sales_related_products_info.reload.sales_count).to eq(3)
end
end
it "enqueues UpdateCachedSalesRelatedProductsInfosJob for the product and related products" do
described_class.new.perform(new_purchase.id)
expect(UpdateCachedSalesRelatedProductsInfosJob.jobs.count).to eq(2)
expect(UpdateCachedSalesRelatedProductsInfosJob).to have_enqueued_sidekiq_job(product1.id)
expect(UpdateCachedSalesRelatedProductsInfosJob).to have_enqueued_sidekiq_job(product2.id)
end
end
context "when a SalesRelatedProductsInfo record doesn't exist" do
it "creates a SalesRelatedProductsInfo record with sales_count set to 1" do
expect do
described_class.new.perform(new_purchase.id)
end.to change(SalesRelatedProductsInfo, :count).by(1)
created_sales_related_products_info = SalesRelatedProductsInfo.last
new_sales_related_products_info = SalesRelatedProductsInfo.find_or_create_info(product1.id, product2.id)
expect(new_sales_related_products_info).to eq(created_sales_related_products_info)
expect(new_sales_related_products_info.sales_count).to eq(1)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/create_india_sales_report_job_spec.rb | spec/sidekiq/create_india_sales_report_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CreateIndiaSalesReportJob do
describe "#perform" do
it "raises an ArgumentError if the year is less than 2014 or greater than 3200" do
expect do
described_class.new.perform(1, 2013)
end.to raise_error(ArgumentError)
expect do
described_class.new.perform(1, 3201)
end.to raise_error(ArgumentError)
end
it "raises an ArgumentError if the month is not within 1 and 12 inclusive" do
expect do
described_class.new.perform(0, 2023)
end.to raise_error(ArgumentError)
expect do
described_class.new.perform(13, 2023)
end.to raise_error(ArgumentError)
end
it "defaults to previous month when no parameters provided" do
travel_to(Time.zone.local(2023, 6, 15)) do
# Mock S3 to prevent real API calls
s3_bucket_double = double
s3_object_double = double
allow(Aws::S3::Resource).to receive_message_chain(:new, :bucket).and_return(s3_bucket_double)
allow(s3_bucket_double).to receive(:object).and_return(s3_object_double)
allow(s3_object_double).to receive(:upload_file)
allow(s3_object_double).to receive(:presigned_url).and_return("https://example.com/test-url")
# Mock Slack notification
allow(SlackMessageWorker).to receive(:perform_async)
# Mock database queries to prevent actual data access
purchase_double = double
allow(Purchase).to receive(:joins).and_return(purchase_double)
allow(purchase_double).to receive(:where).and_return(purchase_double)
allow(purchase_double).to receive_message_chain(:where, :not).and_return(purchase_double)
allow(purchase_double).to receive(:find_each).and_return([])
# Mock ZipTaxRate lookup
zip_tax_rate_double = double
allow(ZipTaxRate).to receive_message_chain(:where, :alive, :last).and_return(zip_tax_rate_double)
allow(zip_tax_rate_double).to receive(:combined_rate).and_return(0.18)
# Test that it defaults to previous month (May 2023)
described_class.new.perform
# Verify it processed the correct month by checking the S3 filename pattern
expect(s3_bucket_double).to have_received(:object).with(/india-sales-report-2023-05-/)
end
end
let(:s3_bucket_double) do
s3_bucket_double = double
allow(Aws::S3::Resource).to receive_message_chain(:new, :bucket).and_return(s3_bucket_double)
s3_bucket_double
end
before :context do
@s3_object = Aws::S3::Resource.new.bucket("gumroad-specs").object("specs/india-sales-report-spec-#{SecureRandom.hex(18)}.csv")
end
before do
Feature.activate(:collect_tax_in)
create(:zip_tax_rate, country: "IN", state: nil, zip_code: nil, combined_rate: 0.18, is_seller_responsible: false)
test_time = Time.zone.local(2023, 6, 15)
product = create(:product, price_cents: 1000)
travel_to(test_time) do
@india_purchase = create(:purchase,
link: product,
purchaser: product.user,
purchase_state: "in_progress",
quantity: 1,
perceived_price_cents: 1000,
country: "India",
ip_country: "India",
ip_state: "MH",
stripe_transaction_id: "txn_test123"
)
@india_purchase.mark_test_successful!
@india_purchase.update!(gumroad_tax_cents: 180)
vat_purchase = create(:purchase,
link: product,
purchaser: product.user,
purchase_state: "in_progress",
quantity: 1,
perceived_price_cents: 1000,
country: "India",
ip_country: "India",
stripe_transaction_id: "txn_test456"
)
vat_purchase.mark_test_successful!
vat_purchase.create_purchase_sales_tax_info!(business_vat_id: "GST123456789")
refunded_purchase = create(:purchase,
link: product,
purchaser: product.user,
purchase_state: "in_progress",
quantity: 1,
perceived_price_cents: 1000,
country: "India",
ip_country: "India",
stripe_transaction_id: "txn_test789"
)
refunded_purchase.mark_test_successful!
refunded_purchase.stripe_refunded = true
refunded_purchase.save!
end
end
it "generates CSV report for India sales" do
expect(s3_bucket_double).to receive(:object).and_return(@s3_object)
described_class.new.perform(6, 2023)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "India Sales Reporting", anything, "green")
temp_file = Tempfile.new("actual-file", encoding: "ascii-8bit")
@s3_object.get(response_target: temp_file)
temp_file.rewind
actual_payload = CSV.read(temp_file)
expect(actual_payload[0]).to eq([
"ID",
"Date",
"Place of Supply (State)",
"Zip Tax Rate (%) (Rate from Database)",
"Taxable Value (cents)",
"Integrated Tax Amount (cents)",
"Tax Rate (%) (Calculated From Tax Collected)",
"Expected Tax (cents, rounded)",
"Expected Tax (cents, floored)",
"Tax Difference (rounded)",
"Tax Difference (floored)"
])
expect(actual_payload.length).to eq(2)
data_row = actual_payload[1]
expect(data_row[0]).to eq(@india_purchase.external_id) # ID
expect(data_row[1]).to eq("2023-06-15") # Date
expect(data_row[2]).to eq("MH") # Place of Supply (State)
expect(data_row[3]).to eq("18") # Zip Tax Rate (%) (Rate from Database)
expect(data_row[4]).to eq("1000") # Taxable Value (cents)
expect(data_row[5]).to eq("180") # Integrated Tax Amount (cents) - gumroad_tax_cents is 180
expect(data_row[6]).to eq("18.0") # Tax Rate (%) (Calculated From Tax Collected) - (180/1000 * 100) = 18.0
expect(data_row[7]).to eq("180") # Expected Tax (cents, rounded) - (1000 * 0.18).round = 180
expect(data_row[8]).to eq("180") # Expected Tax (cents, floored) - (1000 * 0.18).floor = 180
expect(data_row[9]).to eq("0") # Tax Difference (rounded) - 180 - 180 = 0
expect(data_row[10]).to eq("0") # Tax Difference (floored) - 180 - 180 = 0
temp_file.close(true)
end
it "excludes purchases with business VAT ID" do
expect(s3_bucket_double).to receive(:object).and_return(@s3_object)
described_class.new.perform(6, 2023)
temp_file = Tempfile.new("actual-file", encoding: "ascii-8bit")
@s3_object.get(response_target: temp_file)
temp_file.rewind
actual_payload = CSV.read(temp_file)
expect(actual_payload.length).to eq(2)
temp_file.close(true)
end
it "handles invalid Indian states" do
# Create test data without time travel to avoid S3 time skew
invalid_product = create(:product, price_cents: 500)
invalid_state_purchase = create(:purchase,
link: invalid_product,
purchaser: invalid_product.user,
purchase_state: "in_progress",
quantity: 1,
perceived_price_cents: 500,
country: "India",
ip_country: "India",
ip_state: "123",
stripe_transaction_id: "txn_invalid_state",
created_at: Time.zone.local(2023, 6, 15)
)
invalid_state_purchase.mark_test_successful!
# Use a separate S3 object to avoid time skew issues
s3_object_invalid = Aws::S3::Resource.new.bucket("gumroad-specs").object("specs/india-sales-report-invalid-#{SecureRandom.hex(18)}.csv")
expect(s3_bucket_double).to receive(:object).and_return(s3_object_invalid)
described_class.new.perform(6, 2023)
temp_file = Tempfile.new("actual-file", encoding: "ascii-8bit")
s3_object_invalid.get(response_target: temp_file)
temp_file.rewind
actual_payload = CSV.read(temp_file)
invalid_state_row = actual_payload.find { |row| row[0] == invalid_state_purchase.external_id }
expect(invalid_state_row).to be_present
# Check all column values for invalid state purchase
expect(invalid_state_row[0]).to eq(invalid_state_purchase.external_id) # ID
expect(invalid_state_row[1]).to eq("2023-06-15") # Date
expect(invalid_state_row[2]).to eq("") # Place of Supply (State) - empty for invalid state
expect(invalid_state_row[3]).to eq("18") # Zip Tax Rate (%) (Rate from Database)
expect(invalid_state_row[4]).to eq("500") # Taxable Value (cents)
expect(invalid_state_row[5]).to eq("0") # Integrated Tax Amount (cents) - gumroad_tax_cents is 0 for test purchase
expect(invalid_state_row[6]).to eq("0") # Tax Rate (%) (Calculated From Tax Collected) - 0 since no tax collected
expect(invalid_state_row[7]).to eq("90") # Expected Tax (cents, rounded) - (500 * 0.18).round = 90
expect(invalid_state_row[8]).to eq("90") # Expected Tax (cents, floored) - (500 * 0.18).floor = 90
expect(invalid_state_row[9]).to eq("90") # Tax Difference (rounded) - 90 - 0 = 90
expect(invalid_state_row[10]).to eq("90") # Tax Difference (floored) - 90 - 0 = 90
temp_file.close(true)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/suspend_users_worker_spec.rb | spec/sidekiq/suspend_users_worker_spec.rb | # frozen_string_literal: true
describe SuspendUsersWorker do
describe "#perform" do
let(:admin_user) { create(:admin_user) }
let(:not_reviewed_user) { create(:user) }
let(:compliant_user) { create(:compliant_user) }
let(:already_suspended_user) { create(:user, user_risk_state: :suspended_for_fraud) }
let!(:user_not_to_suspend) { create(:user) }
let(:user_ids_to_suspend) { [not_reviewed_user.id, compliant_user.id, already_suspended_user.id] }
let(:reason) { "Violating our terms of service" }
let(:additional_notes) { "Some additional notes" }
it "suspends the users appropriately with IDs" do
described_class.new.perform(admin_user.id, user_ids_to_suspend, reason, additional_notes)
expect(not_reviewed_user.reload.suspended?).to be(true)
expect(compliant_user.reload.suspended?).to be(true)
expect(already_suspended_user.reload.suspended?).to be(true)
expect(user_not_to_suspend.reload.suspended?).to be(false)
comments = not_reviewed_user.comments
expect(comments.count).to eq(2)
expect(comments.first.content).to eq("Flagged for a policy violation by #{admin_user.name_or_username} on #{Time.current.to_fs(:formatted_date_full_month)}")
expect(comments.first.author_id).to eq(admin_user.id)
expect(comments.last.content).to eq("Suspended for a policy violation by #{admin_user.name_or_username} on #{Time.current.to_fs(:formatted_date_full_month)} as part of mass suspension. Reason: #{reason}.\nAdditional notes: #{additional_notes}")
expect(comments.last.author_id).to eq(admin_user.id)
end
it "suspends the users appropriately with external IDs" do
external_ids_to_suspend = [not_reviewed_user.external_id, compliant_user.external_id, already_suspended_user.external_id]
described_class.new.perform(admin_user.id, external_ids_to_suspend, reason, additional_notes)
expect(not_reviewed_user.reload.suspended?).to be(true)
expect(compliant_user.reload.suspended?).to be(true)
expect(already_suspended_user.reload.suspended?).to be(true)
expect(user_not_to_suspend.reload.suspended?).to be(false)
end
it "suspends the users appropriately with mixed internal and external IDs" do
mixed_ids = [not_reviewed_user.id, compliant_user.external_id, already_suspended_user.id]
described_class.new.perform(admin_user.id, mixed_ids, reason, additional_notes)
expect(not_reviewed_user.reload.suspended?).to be(true)
expect(compliant_user.reload.suspended?).to be(true)
expect(already_suspended_user.reload.suspended?).to be(true)
expect(user_not_to_suspend.reload.suspended?).to be(false)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/trigger_community_chat_recap_run_job_spec.rb | spec/sidekiq/trigger_community_chat_recap_run_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe TriggerCommunityChatRecapRunJob do
subject(:job) { described_class.new }
describe "#perform" do
context "when recap_frequency is invalid" do
it "raises ArgumentError" do
expect { job.perform("invalid") }.to raise_error(ArgumentError, "Recap frequency must be daily or weekly")
end
end
context "when recap_frequency is daily" do
let(:from_date) { Date.yesterday.beginning_of_day }
let(:to_date) { from_date.end_of_day }
context "when no messages exist" do
it "creates a daily recap run and marks it as finished" do
expect do
expect do
job.perform("daily")
end.to change(CommunityChatRecapRun, :count).by(1)
end.not_to change(CommunityChatRecap, :count)
expect(GenerateCommunityChatRecapJob.jobs).to be_empty
recap_run = CommunityChatRecapRun.last
expect(recap_run.recap_frequency_daily?).to eq(true)
expect(recap_run.from_date.iso8601).to eq(from_date.iso8601)
expect(recap_run.to_date.iso8601).to eq(to_date.iso8601)
expect(recap_run.recaps_count).to eq(0)
expect(recap_run.finished_at).to be_present
expect(recap_run.notified_at).to be_present
end
end
context "when messages exist" do
let!(:community) { create(:community) }
let!(:message) { create(:community_chat_message, community: community, created_at: from_date + 1.hour) }
it "creates a pending daily recap run" do
expect do
job.perform("daily")
end.to change(CommunityChatRecapRun, :count).by(1)
.and change(CommunityChatRecap, :count).by(1)
recap_run = CommunityChatRecapRun.last
expect(recap_run.recap_frequency_daily?).to eq(true)
expect(recap_run.from_date.iso8601).to eq(from_date.iso8601)
expect(recap_run.to_date.iso8601).to eq(to_date.iso8601)
expect(recap_run.recaps_count).to eq(1)
expect(recap_run.finished_at).to be_nil
expect(recap_run.notified_at).to be_nil
recap = CommunityChatRecap.last
expect(recap.community_id).to eq(community.id)
expect(recap.community_chat_recap_run_id).to eq(recap_run.id)
expect(recap).to be_status_pending
expect(GenerateCommunityChatRecapJob).to have_enqueued_sidekiq_job(recap.id)
end
end
context "when a recap run already exists" do
let!(:existing_run) { create(:community_chat_recap_run, from_date:, to_date:) }
it "does not create a new recap run" do
expect do
expect do
job.perform("daily")
end.not_to change(CommunityChatRecapRun, :count)
end.not_to change(CommunityChatRecap, :count)
expect(GenerateCommunityChatRecapJob.jobs).to be_empty
end
end
context "when from_date is provided" do
let(:custom_date) { 2.days.ago.to_date.to_s }
it "uses the provided date" do
expect do
job.perform("daily", custom_date)
end.to change(CommunityChatRecapRun, :count).by(1)
recap_run = CommunityChatRecapRun.last
expect(recap_run.recap_frequency_daily?).to eq(true)
expect(recap_run.from_date.iso8601).to eq(Date.parse(custom_date).beginning_of_day.iso8601)
expect(recap_run.to_date.iso8601).to eq(Date.parse(custom_date).end_of_day.iso8601)
end
end
end
context "when recap_frequency is weekly" do
let(:from_date) { (Date.yesterday - 6.days).beginning_of_day }
let(:to_date) { (from_date + 6.days).end_of_day }
context "when no messages exist" do
it "creates a weekly recap run and marks it as finished" do
expect do
expect do
job.perform("weekly")
end.to change(CommunityChatRecapRun, :count).by(1)
end.not_to change(CommunityChatRecap, :count)
expect(GenerateCommunityChatRecapJob.jobs).to be_empty
recap_run = CommunityChatRecapRun.last
expect(recap_run.recap_frequency_weekly?).to eq(true)
expect(recap_run.from_date.iso8601).to eq(from_date.iso8601)
expect(recap_run.to_date.iso8601).to eq(to_date.iso8601)
expect(recap_run.recaps_count).to eq(0)
expect(recap_run.finished_at).to be_present
expect(recap_run.notified_at).to be_present
end
end
context "when messages exist" do
let!(:community) { create(:community) }
let!(:message) { create(:community_chat_message, community: community, created_at: from_date + 1.day) }
it "creates a pending weekly recap run" do
expect do
job.perform("weekly")
end.to change(CommunityChatRecapRun, :count).by(1)
.and change(CommunityChatRecap, :count).by(1)
recap_run = CommunityChatRecapRun.last
expect(recap_run.recap_frequency_weekly?).to eq(true)
expect(recap_run.from_date.iso8601).to eq(from_date.iso8601)
expect(recap_run.to_date.iso8601).to eq(to_date.iso8601)
expect(recap_run.recaps_count).to eq(1)
expect(recap_run.finished_at).to be_nil
expect(recap_run.notified_at).to be_nil
recap = CommunityChatRecap.last
expect(recap.community_id).to eq(community.id)
expect(recap.community_chat_recap_run_id).to eq(recap_run.id)
expect(recap).to be_status_pending
expect(GenerateCommunityChatRecapJob).to have_enqueued_sidekiq_job(recap.id)
end
end
context "when a recap run already exists" do
let!(:existing_run) { create(:community_chat_recap_run, :weekly, from_date:, to_date:) }
it "does not create a new recap run" do
expect do
expect do
job.perform("weekly")
end.not_to change(CommunityChatRecapRun, :count)
end.not_to change(CommunityChatRecap, :count)
expect(GenerateCommunityChatRecapJob.jobs).to be_empty
end
end
context "when from_date is provided" do
let(:custom_date) { 14.days.ago.to_date.to_s }
it "uses the provided date" do
expect do
job.perform("weekly", custom_date)
end.to change(CommunityChatRecapRun, :count).by(1)
recap_run = CommunityChatRecapRun.last
expect(recap_run.recap_frequency_weekly?).to eq(true)
expect(recap_run.from_date.iso8601).to eq(Date.parse(custom_date).beginning_of_day.iso8601)
expect(recap_run.to_date.iso8601).to eq((Date.parse(custom_date) + 6.days).end_of_day.iso8601)
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/unsubscribe_and_fail_worker_spec.rb | spec/sidekiq/unsubscribe_and_fail_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UnsubscribeAndFailWorker, :vcr do
before do
@product = create(:subscription_product, user: create(:user))
@subscription = create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: @product)
@purchase = create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
end
it "doesn't call unsubscribe_and_fail on test_subscriptions" do
@product.user.credit_card = create(:credit_card)
@product.user.save!
subscription = create(:subscription, user: @product.user, link: @product)
subscription.is_test_subscription = true
subscription.save!
create(:test_purchase, seller: @product.user, purchaser: @product.user, link: @product, price_cents: @product.price_cents,
is_original_subscription_purchase: true, subscription:)
expect_any_instance_of(Subscription).to_not receive(:unsubscribe_and_fail!)
described_class.new.perform(subscription.id)
end
it "doesn't call unsubscribe_and_fail if last purchase was successful" do
expect_any_instance_of(Subscription).to_not receive(:charge!)
described_class.new.perform(@subscription.id)
end
it "calls unsubscribe_and_fail when the subscription is overdue for a charge" do
travel_to @subscription.end_time_of_subscription + 1.hour do
expect_any_instance_of(Subscription).to receive(:unsubscribe_and_fail!)
described_class.new.perform(@subscription.id)
end
end
it "does not call unsubscribe_and_fail when the subscription is NOT overdue for a charge" do
travel_to @subscription.end_time_of_subscription - 1.hour do
expect_any_instance_of(Subscription).not_to receive(:unsubscribe_and_fail!)
described_class.new.perform(@subscription.id)
end
end
describe "subscription is cancelled" do
before do
@product = create(:product, user: create(:user))
@subscription = create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: @product, cancelled_at: Time.current)
@purchase = create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
end
it "doesn't call unsubscribe_and_fail on subscriptions" do
expect_any_instance_of(Subscription).to_not receive(:unsubscribe_and_fail!)
described_class.new.perform(@subscription.id)
end
end
describe "subscription has failed" do
before do
@product = create(:product, user: create(:user))
@subscription = create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: @product, failed_at: Time.current)
@purchase = create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
end
it "doesn't call unsubscribe_and_fail on subscriptions" do
expect_any_instance_of(Subscription).to_not receive(:unsubscribe_and_fail!)
described_class.new.perform(@subscription.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/delete_expired_product_cached_values_worker_spec.rb | spec/sidekiq/delete_expired_product_cached_values_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DeleteExpiredProductCachedValuesWorker do
describe "#perform" do
it "deletes expired rows, except the latest one per product" do
product_1 = create(:product)
create_list(:product_cached_value, 3, :expired, product: product_1) # should delete 3 of them
create(:product_cached_value, product: product_1) # should not be deleted
product_2 = create(:product)
create_list(:product_cached_value, 2, :expired, product: product_2) # should delete 1 of them
product_3 = create(:product)
create(:product_cached_value, :expired, product: product_3) # should be deleted
create(:product_cached_value, product: product_3) # should not be deleted
create(:product_cached_value, :expired) # should not be deleted
create(:product_cached_value) # should not be deleted
records = ProductCachedValue.order(:id).to_a
stub_const("#{described_class}::QUERY_BATCH_SIZE", 2)
expect do
described_class.new.perform
end.to change { ProductCachedValue.count }.by(-5)
[0, 1, 2, 4, 6].each do |index|
expect { records[index].reload }.to raise_error(ActiveRecord::RecordNotFound)
end
[3, 5, 7, 8, 9].each do |index|
expect(records[index].reload).to be_instance_of(ProductCachedValue)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/pdf_unstampable_notifier_job_spec.rb | spec/sidekiq/pdf_unstampable_notifier_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PdfUnstampableNotifierJob do
describe "#perform" do
let!(:product) { create(:product_with_pdf_file) }
it "does not notify seller if a pdf is stampable" do
product.product_files.alive.pdf.each { |product_file| product_file.update!(pdf_stamp_enabled: true) }
expect(PdfStampingService).to receive(:can_stamp_file?).and_return(true)
expect do
described_class.new.perform(product.id)
end.not_to have_enqueued_mail(ContactingCreatorMailer, :unstampable_pdf_notification)
end
it "does nothing if no files have pdf stamping enabled" do
expect(PdfStampingService).not_to receive(:can_stamp_file?)
expect do
described_class.new.perform(product.id)
end.not_to have_enqueued_mail(ContactingCreatorMailer, :unstampable_pdf_notification)
end
it "notifies seller if a pdf can't be stamped" do
product.product_files.alive.pdf.each { |product_file| product_file.update!(pdf_stamp_enabled: true) }
expect(PdfStampingService).to receive(:can_stamp_file?).and_return(false)
expect do
described_class.new.perform(product.id)
end.to have_enqueued_mail(ContactingCreatorMailer, :unstampable_pdf_notification)
end
it "does not try to stamp a pdf that has already been marked as stampable or non-stampable" do
product.product_files.alive.pdf.each { |product_file| product_file.update!(pdf_stamp_enabled: true, stampable_pdf: false) }
create(:readable_document, link: product, pdf_stamp_enabled: true, stampable_pdf: true)
expect(PdfStampingService).not_to receive(:can_stamp_file?)
expect do
described_class.new.perform(product.id)
end.not_to have_enqueued_mail(ContactingCreatorMailer, :unstampable_pdf_notification)
end
context "with eligible sale" do
let(:purchase) { create(:purchase, link: product) }
before do
product.product_files.alive.pdf.each { |product_file| product_file.update!(pdf_stamp_enabled: true) }
purchase.create_url_redirect!
StampPdfForPurchaseJob.jobs.clear
end
it "enqueues job to generate stamped pdfs for existing sales" do
expect(PdfStampingService).to receive(:can_stamp_file?).and_return(true)
expect do
described_class.new.perform(product.id)
end.not_to have_enqueued_mail(ContactingCreatorMailer, :unstampable_pdf_notification)
expect(StampPdfForPurchaseJob.jobs.size).to eq(1)
expect(StampPdfForPurchaseJob).to have_enqueued_sidekiq_job(purchase.id)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/handle_paypal_event_worker_spec.rb | spec/sidekiq/handle_paypal_event_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe HandlePaypalEventWorker do
describe "perform" do
it "calls handle_paypal_event on HandlePaypalEventWorker" do
id = rand(10_000)
params = { id: }
expect(PaypalEventHandler).to receive(:new).with(params).and_call_original
expect_any_instance_of(PaypalEventHandler).to receive(:handle_paypal_event)
described_class.new.perform(params)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/custom_domain_verification_worker_spec.rb | spec/sidekiq/custom_domain_verification_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CustomDomainVerificationWorker do
let!(:valid_custom_domain) { create(:custom_domain) }
let!(:invalid_custom_domain) { create(:custom_domain, state: "unverified", failed_verification_attempts_count: 2) }
let!(:deleted_custom_domain) { create(:custom_domain, deleted_at: 2.days.ago) }
before do
allow(CustomDomainVerificationService)
.to receive(:new)
.with(domain: valid_custom_domain.domain)
.and_return(double(process: true))
allow(CustomDomainVerificationService)
.to receive(:new)
.with(domain: invalid_custom_domain.domain)
.and_return(double(process: false))
end
it "marks a valid custom domain as verified" do
expect do
described_class.new.perform(valid_custom_domain.id)
end.to change { valid_custom_domain.reload.verified? }.from(false).to(true)
end
it "marks an invalid custom domain as unverified" do
expect do
expect do
described_class.new.perform(invalid_custom_domain.id)
end.to_not change { invalid_custom_domain.reload.verified? }
end.to change { invalid_custom_domain.failed_verification_attempts_count }.from(2).to(3)
end
it "ignores verification of a deleted custom domain" do
expect do
described_class.new.perform(deleted_custom_domain.id)
end.to_not change { deleted_custom_domain.reload }
end
it "ignores verification of custom domain with invalid domain names" do
invalid_domain = build(:custom_domain, domain: "invalid_domain_name.test")
invalid_domain.save(validate: false)
expect do
described_class.new.perform(invalid_domain.id)
end.to_not change { invalid_domain.reload }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/update_seller_refund_eligibility_job_spec.rb | spec/sidekiq/update_seller_refund_eligibility_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateSellerRefundEligibilityJob do
let(:user) { create(:user) }
def perform
described_class.new.perform(user.id)
end
context "when refund is currently disabled" do
before { user.disable_refunds! }
it "enables refunds when balance goes above $0" do
# Current balance is -100.01
create(:balance, user: user, amount_cents: -100_01)
expect { perform }.not_to change { user.reload.refunds_disabled? }
# Current balance is -100
create(:balance, user: user, amount_cents: 1)
expect { perform }.not_to change { user.reload.refunds_disabled? }
# Current balance is 0
create(:balance, user: user, amount_cents: 100_00)
expect { perform }.not_to change { user.reload.refunds_disabled? }
# Current balance is $0.01
create(:balance, user: user, amount_cents: 1)
expect { perform }.to change { user.reload.refunds_disabled? }.from(true).to(false)
end
end
context "when refund is currently enabled" do
before { user.enable_refunds! }
it "disables refunds when balance dips below -$100" do
# Current balance is 0.01
create(:balance, user: user, amount_cents: 1)
expect { perform }.not_to change { user.reload.refunds_disabled? }
# Current balance is 0
create(:balance, user: user, amount_cents: -1)
expect { perform }.not_to change { user.reload.refunds_disabled? }
# Current balance is -100
create(:balance, user: user, amount_cents: -100_00)
expect { perform }.not_to change { user.reload.refunds_disabled? }
# Current balance is -100.01
create(:balance, user: user, amount_cents: -1)
expect { perform }.to change { user.reload.refunds_disabled? }.from(false).to(true)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/recalculate_recent_wishlist_follower_count_job_spec.rb | spec/sidekiq/recalculate_recent_wishlist_follower_count_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RecalculateRecentWishlistFollowerCountJob do
describe "#perform" do
let!(:wishlist1) { create(:wishlist) }
let!(:wishlist2) { create(:wishlist) }
before do
create_list(:wishlist_follower, 3, wishlist: wishlist1, created_at: 15.days.ago)
create_list(:wishlist_follower, 1, wishlist: wishlist2, created_at: 20.days.ago)
end
it "updates recent_follower_count for all wishlists" do
expect do
described_class.new.perform
end.to change { wishlist1.reload.recent_follower_count }.from(0).to(3)
.and change { wishlist2.reload.recent_follower_count }.from(0).to(1)
end
it "only counts followers created within the last 30 days" do
create_list(:wishlist_follower, 2, wishlist: wishlist1, created_at: 35.days.ago)
create_list(:wishlist_follower, 4, wishlist: wishlist2, created_at: 40.days.ago)
described_class.new.perform
expect(wishlist1.reload.recent_follower_count).to eq(3)
expect(wishlist2.reload.recent_follower_count).to eq(1)
end
it "handles wishlists with no recent followers" do
wishlist3 = create(:wishlist)
create_list(:wishlist_follower, 2, wishlist: wishlist3, created_at: 31.days.ago)
described_class.new.perform
expect(wishlist3.reload.recent_follower_count).to eq(0)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/charge_declined_reminder_worker_spec.rb | spec/sidekiq/charge_declined_reminder_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ChargeDeclinedReminderWorker, :vcr do
before do
@product = create(:membership_product, user: create(:user), subscription_duration: :monthly)
@subscription = create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: @product)
@purchase = create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
end
it "doesn't send email on test_subscriptions" do
@subscription.update!(is_test_subscription: true)
expect do
described_class.new.perform(@subscription.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :subscription_card_declined_warning).with(@subscription.id)
end
it "doesn't send email when the subscription is NOT overdue for a charge" do
travel_to @subscription.end_time_of_subscription - 1.hour do
expect do
described_class.new.perform(@subscription.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :subscription_card_declined_warning).with(@subscription.id)
end
end
it "sends email when the subscription is overdue for a charge" do
travel_to @subscription.end_time_of_subscription + 1.hour do
expect do
described_class.new.perform(@subscription.id)
end.to have_enqueued_mail(CustomerLowPriorityMailer, :subscription_card_declined_warning).with(@subscription.id)
end
end
describe "subscription is cancelled" do
before do
@subscription.cancel!
end
it "doesn't send email on subscriptions" do
expect do
described_class.new.perform(@subscription.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :subscription_card_declined_warning).with(@subscription.id)
end
end
describe "subscription has failed" do
before do
@subscription.unsubscribe_and_fail!
end
it "doesn't send email on subscriptions" do
expect do
described_class.new.perform(@subscription.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :subscription_card_declined_warning).with(@subscription.id)
end
end
describe "subscription has ended" do
before do
@subscription.end_subscription!
end
it "calls charge on subscriptions" do
expect do
described_class.new.perform(@subscription.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :subscription_card_declined_warning).with(@subscription.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/post_to_individual_ping_endpoint_worker_spec.rb | spec/sidekiq/post_to_individual_ping_endpoint_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PostToIndividualPingEndpointWorker do
before do
@http_double = double
allow(@http_double).to receive(:success?).and_return(true)
allow(@http_double).to receive(:code).and_return(200)
end
describe "post to individual endpoint" do
context "when the content_type is application/x-www-form-urlencoded" do
it "posts to the right endpoint using the right params" do
expect(HTTParty).to receive(:post).with("http://notification.com", timeout: 5, body: { "a" => 1 }, headers: { "Content-Type" => "application/x-www-form-urlencoded" }).and_return(@http_double)
expect do
PostToIndividualPingEndpointWorker.new.perform("http://notification.com", { "a" => 1 }, Mime[:url_encoded_form].to_s)
end.to_not raise_error
end
it "posts to the right endpoint and encodes brackets" do
expect(HTTParty).to receive(:post).with(
"http://notification.com",
timeout: 5,
body: {
"name %5Bfor field%5D %5B%5B%5D%5D!@\#$%^&" => 1,
"custom_fields" => {
"name %5Bfor field%5D %5B%5B%5D%5D!@\#$%^&" => 1
}
},
headers: { "Content-Type" => "application/x-www-form-urlencoded" }
).and_return(@http_double)
expect do
PostToIndividualPingEndpointWorker.new.perform(
"http://notification.com",
{
"name [for field] [[]]!@#$%^&" => 1,
custom_fields: {
"name [for field] [[]]!@#$%^&" => 1
}
},
Mime[:url_encoded_form].to_s
)
end.to_not raise_error
end
end
context "when the content_type is application/json" do
it "posts to the right endpoint using the right params" do
expect(HTTParty).to receive(:post).with("http://notification.com", timeout: 5, body: { "some [thing]" => 1 }.to_json, headers: { "Content-Type" => "application/json" }).and_return(@http_double)
expect do
PostToIndividualPingEndpointWorker.new.perform("http://notification.com", { "some [thing]" => 1 }, Mime[:json].to_s)
end.to_not raise_error
end
end
end
it "does not raise when it encounters an internet error" do
allow(HTTParty).to receive(:post).and_raise(SocketError.new("socket error message"))
expect(Rails.logger).to receive(:info).with("[SocketError] PostToIndividualPingEndpointWorker error=\"socket error message\" url=http://example.com content_type=#{Mime[:url_encoded_form]} params={\"q\" => 47}")
expect(HTTParty).to receive(:post).exactly(1).times
PostToIndividualPingEndpointWorker.new.perform("http://example.com", { "q" => 47 })
end
it "re-raises a non-internet error" do
allow(HTTParty).to receive(:post).and_raise(StandardError)
expect do
PostToIndividualPingEndpointWorker.new.perform("http://notification.com", { "q" => 47 })
end.to raise_error(StandardError)
end
it "retries 50x status codes the right number of times and does not raise", :sidekiq_inline do
allow(@http_double).to receive(:success?).and_return(false)
allow(@http_double).to receive(:code).and_return(500)
expect(HTTParty).to receive(:post).exactly(4).times.with("http://notification.com", kind_of(Hash)).and_return(@http_double)
PostToIndividualPingEndpointWorker.new.perform("http://notification.com", { "b" => 3 })
end
it "does not retry other status codes", :sidekiq_inline do
allow(@http_double).to receive(:success?).and_return(false)
allow(@http_double).to receive(:code).and_return(417)
expect(HTTParty).to receive(:post).exactly(1).times.with("http://notification.com", kind_of(Hash)).and_return(@http_double)
PostToIndividualPingEndpointWorker.new.perform("http://notification.com", { "c" => 17 })
end
describe "logging" do
it "logs url, response code and params" do
expect(HTTParty).to receive(:post).with("https://notification.com", timeout: 5, body: { "a" => 1 }, headers: { "Content-Type" => Mime[:url_encoded_form] }).and_return(@http_double)
expect(Rails.logger).to receive(:info).with("PostToIndividualPingEndpointWorker response=200 url=https://notification.com content_type=#{Mime[:url_encoded_form]} params={\"a\" => 1}")
PostToIndividualPingEndpointWorker.new.perform("https://notification.com", { "a" => 1 })
end
end
describe "ping failure notifications" do
let(:user) { create(:user, email: "seller@example.com") }
let(:ping_url) { "https://example.com/webhook" }
let(:params) { { "test" => "data" } }
before do
user.update!(notification_endpoint: ping_url)
allow(@http_double).to receive(:success?).and_return(false)
allow(@http_double).to receive(:code).and_return(500)
allow(HTTParty).to receive(:post).and_return(@http_double)
Feature.activate(:alert_on_ping_endpoint_failure)
end
context "when retries are exhausted" do
it "sends email notification when user_id is provided", :sidekiq_inline do
expect(ContactingCreatorMailer).to receive(:ping_endpoint_failure).with(user.id, ping_url, 500).and_call_original
expect_any_instance_of(ActionMailer::MessageDelivery).to receive(:deliver_later).with(queue: "critical")
PostToIndividualPingEndpointWorker.new.perform(ping_url, params, Mime[:url_encoded_form].to_s, user.id)
end
it "does not send email notification when user_id is nil", :sidekiq_inline do
expect(ContactingCreatorMailer).not_to receive(:ping_endpoint_failure)
PostToIndividualPingEndpointWorker.new.perform(ping_url, params, Mime[:url_encoded_form].to_s, nil)
end
it "does not send email notification when user_id is not provided", :sidekiq_inline do
expect(ContactingCreatorMailer).not_to receive(:ping_endpoint_failure)
PostToIndividualPingEndpointWorker.new.perform(ping_url, params, Mime[:url_encoded_form].to_s)
end
it "updates user's last_ping_failure_notification_at timestamp", :sidekiq_inline do
allow(ContactingCreatorMailer).to receive(:ping_endpoint_failure).and_return(double(deliver_later: true))
expect do
PostToIndividualPingEndpointWorker.new.perform(ping_url, params, Mime[:url_encoded_form].to_s, user.id)
end.to change { user.reload.last_ping_failure_notification_at }.from(nil)
end
end
context "when notification throttling is active" do
before do
user.last_ping_failure_notification_at = (PostToIndividualPingEndpointWorker::NOTIFICATION_THROTTLE_PERIOD.ago + 1.day).to_s
user.save!
end
it "does not send email notification when last notification was within throttle period", :sidekiq_inline do
expect(ContactingCreatorMailer).not_to receive(:ping_endpoint_failure)
PostToIndividualPingEndpointWorker.new.perform(ping_url, params, Mime[:url_encoded_form].to_s, user.id)
end
it "does not update last_ping_failure_notification_at when throttled", :sidekiq_inline do
expect do
PostToIndividualPingEndpointWorker.new.perform(ping_url, params, Mime[:url_encoded_form].to_s, user.id)
end.not_to change { user.reload.last_ping_failure_notification_at }
end
end
context "when notification throttling has expired" do
before do
user.last_ping_failure_notification_at = (PostToIndividualPingEndpointWorker::NOTIFICATION_THROTTLE_PERIOD.ago - 1.day).to_s
user.save!
end
it "sends email notification when throttle period has passed", :sidekiq_inline do
expect(ContactingCreatorMailer).to receive(:ping_endpoint_failure).with(user.id, ping_url, 500).and_call_original
expect_any_instance_of(ActionMailer::MessageDelivery).to receive(:deliver_later).with(queue: "critical")
PostToIndividualPingEndpointWorker.new.perform(ping_url, params, Mime[:url_encoded_form].to_s, user.id)
end
it "updates last_ping_failure_notification_at when throttle has expired", :sidekiq_inline do
allow(ContactingCreatorMailer).to receive(:ping_endpoint_failure).and_return(double(deliver_later: true))
old_timestamp = user.last_ping_failure_notification_at
expect do
PostToIndividualPingEndpointWorker.new.perform(ping_url, params, Mime[:url_encoded_form].to_s, user.id)
end.to change { user.reload.last_ping_failure_notification_at }.from(old_timestamp)
end
end
context "when request succeeds" do
before do
allow(@http_double).to receive(:success?).and_return(true)
allow(@http_double).to receive(:code).and_return(200)
end
it "does not send email notification on successful request", :sidekiq_inline do
expect(ContactingCreatorMailer).not_to receive(:ping_endpoint_failure)
PostToIndividualPingEndpointWorker.new.perform(ping_url, params, Mime[:url_encoded_form].to_s, user.id)
end
end
context "when request fails with non-retryable status code" do
before do
allow(@http_double).to receive(:success?).and_return(false)
allow(@http_double).to receive(:code).and_return(404)
end
it "sends email notification immediately for non-retryable errors", :sidekiq_inline do
expect(ContactingCreatorMailer).to receive(:ping_endpoint_failure).with(user.id, ping_url, 404).and_call_original
expect_any_instance_of(ActionMailer::MessageDelivery).to receive(:deliver_later).with(queue: "critical")
PostToIndividualPingEndpointWorker.new.perform(ping_url, params, Mime[:url_encoded_form].to_s, user.id)
end
end
context "when ping URL is not seller's notification_endpoint" do
let(:resource_subscription_url) { "https://different-app.com/webhook" }
before do
user.update!(notification_endpoint: "https://seller-endpoint.com/notifications")
allow(@http_double).to receive(:success?).and_return(false)
allow(@http_double).to receive(:code).and_return(500)
allow(HTTParty).to receive(:post).and_return(@http_double)
end
it "does not send email notification for resource subscription URL failures", :sidekiq_inline do
expect(ContactingCreatorMailer).not_to receive(:ping_endpoint_failure)
PostToIndividualPingEndpointWorker.new.perform(resource_subscription_url, params, Mime[:url_encoded_form].to_s, user.id)
end
it "does not update last_ping_failure_notification_at for resource subscription failures", :sidekiq_inline do
expect do
PostToIndividualPingEndpointWorker.new.perform(resource_subscription_url, params, Mime[:url_encoded_form].to_s, user.id)
end.not_to change { user.reload.last_ping_failure_notification_at }
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/recurring_charge_reminder_worker_spec.rb | spec/sidekiq/recurring_charge_reminder_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RecurringChargeReminderWorker, :vcr do
include ManageSubscriptionHelpers
before do
setup_subscription
travel_to @subscription.end_time_of_subscription - 6.days
allow_any_instance_of(Subscription).to receive(:send_renewal_reminders?).and_return(true)
end
it "sends a reminder email about an upcoming charge" do
expect do
RecurringChargeReminderWorker.new.perform(@subscription.id)
end.to have_enqueued_mail(CustomerLowPriorityMailer, :subscription_renewal_reminder).with(@subscription.id)
end
it "does not send a reminder if the subscription is no longer alive" do
@subscription.update!(failed_at: 1.day.ago)
expect do
RecurringChargeReminderWorker.new.perform(@subscription.id)
end.not_to have_enqueued_mail(CustomerLowPriorityMailer, :subscription_renewal_reminder).with(@subscription.id)
end
it "does not send a reminder if the subscription is pending cancellation" do
@subscription.update!(cancelled_at: 1.day.from_now)
expect do
RecurringChargeReminderWorker.new.perform(@subscription.id)
end.not_to have_enqueued_mail(CustomerLowPriorityMailer, :subscription_renewal_reminder).with(@subscription.id)
end
it "does not send a reminder for a fixed-length subscription that has had its last charge" do
@subscription.update!(charge_occurrence_count: 1)
expect do
RecurringChargeReminderWorker.new.perform(@subscription.id)
end.not_to have_enqueued_mail(CustomerLowPriorityMailer, :subscription_renewal_reminder).with(@subscription.id)
end
it "does not send a reminder if `send_renewal_reminders?` is false" do
allow_any_instance_of(Subscription).to receive(:send_renewal_reminders?).and_return(false)
expect do
RecurringChargeReminderWorker.new.perform(@subscription.id)
end.not_to have_enqueued_mail(CustomerLowPriorityMailer, :subscription_renewal_reminder).with(@subscription.id)
end
it "does not send a reminder for a subscription still in a free trial" do
@subscription.update!(free_trial_ends_at: 1.week.from_now)
expect do
RecurringChargeReminderWorker.new.perform(@subscription.id)
end.not_to have_enqueued_mail(CustomerLowPriorityMailer, :subscription_renewal_reminder).with(@subscription.id)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/reissue_ssl_certificate_for_updated_custom_domains_spec.rb | spec/sidekiq/reissue_ssl_certificate_for_updated_custom_domains_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ReissueSslCertificateForUpdatedCustomDomains do
describe "#perform" do
before do
custom_domain = create(:custom_domain)
custom_domain.set_ssl_certificate_issued_at!
end
context "when valid certificates are not found for the domain" do
before do
allow_any_instance_of(CustomDomainVerificationService).to receive(:has_valid_ssl_certificates?).and_return(false)
end
it "generates new certificates for the domain" do
expect_any_instance_of(CustomDomain).to receive(:reset_ssl_certificate_issued_at!)
expect_any_instance_of(CustomDomain).to receive(:generate_ssl_certificate)
described_class.new.perform
end
end
context "when valid certificates are found for the domain" do
before do
allow_any_instance_of(CustomDomainVerificationService).to receive(:has_valid_ssl_certificates?).and_return(true)
end
it "doesn't generate new certificates for the domain" do
expect_any_instance_of(CustomDomain).not_to receive(:reset_ssl_certificate_issued_at!)
expect_any_instance_of(CustomDomain).not_to receive(:generate_ssl_certificate)
described_class.new.perform
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/update_integrations_on_tier_change_worker_spec.rb | spec/sidekiq/update_integrations_on_tier_change_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateIntegrationsOnTierChangeWorker do
it "calls #update_on_tier_change for all integrations" do
purchase = create(:membership_purchase, purchase_sales_tax_info: PurchaseSalesTaxInfo.create(business_vat_id: 0))
subscription = purchase.subscription
new_tier = create(:variant, variant_category: purchase.link.tier_category, name: "Tier 3")
subscription.update_current_plan!(
new_variants: [new_tier],
new_price: create(:price),
perceived_price_cents: 0,
is_applying_plan_change: true,
)
[Integrations::CircleIntegrationService, Integrations::DiscordIntegrationService].each do |integration_service|
expect_any_instance_of(integration_service).to receive(:update_on_tier_change).with(subscription)
end
described_class.new.perform(subscription.id)
end
it "errors out if subscription is not found" do
expect { described_class.new.perform(1) }.to raise_error(ActiveRecord::RecordNotFound).with_message("Couldn't find Subscription with 'id'=1")
[Integrations::CircleIntegrationService, Integrations::DiscordIntegrationService].each do |integration_service|
expect_any_instance_of(integration_service).to_not receive(:update_on_tier_change)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/cancel_preorder_worker_spec.rb | spec/sidekiq/cancel_preorder_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CancelPreorderWorker, :vcr do
describe "perform" do
it "cancels the preorder if it is in authorization_successful state but does not send notification emails" do
product = create(:product)
preorder_link = create(:preorder_link, link: product)
preorder_link.update_attribute(:release_at, Time.current) # bypass validation
authorization_purchase = build(:purchase, link: product, chargeable: build(:chargeable), purchase_state: "in_progress", is_preorder_authorization: true)
preorder = preorder_link.build_preorder(authorization_purchase)
preorder.authorize!
preorder.mark_authorization_successful!
expect(preorder.reload.state).to eq "authorization_successful"
expect do
expect do
CancelPreorderWorker.new.perform(preorder.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :preorder_cancelled).with(preorder.id)
end.to_not have_enqueued_mail(ContactingCreatorMailer, :preorder_cancelled).with(preorder.id)
expect(preorder.reload.state).to eq "cancelled"
expect(preorder.authorization_purchase.purchase_state).to eq "preorder_concluded_unsuccessfully"
end
it "does not cancel the preorder if it is not in authorization_successful state" do
preorder_in_progress = create(:preorder, state: "in_progress")
CancelPreorderWorker.new.perform(preorder_in_progress.id)
expect(preorder_in_progress.reload.state).to eq "in_progress"
preorder_charge_successful = create(:preorder, state: "charge_successful")
CancelPreorderWorker.new.perform(preorder_charge_successful.id)
expect(preorder_charge_successful.reload.state).to eq "charge_successful"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/update_bundle_purchases_content_job_spec.rb | spec/sidekiq/update_bundle_purchases_content_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateBundlePurchasesContentJob do
let(:seller) { create(:named_seller) }
let(:purchaser) { create(:buyer_user) }
let(:bundle) { create(:product, user: seller, is_bundle: true, has_outdated_purchases: true) }
let(:product) { create(:product, user: seller, name: "Product", custom_fields: [create(:custom_field, name: "Key")]) }
let!(:bundle_product) { create(:bundle_product, bundle:, product:, updated_at: 2.years.ago) }
let(:versioned_product) { create(:product_with_digital_versions, user: seller, name: "Versioned product") }
let!(:versioned_bundle_product) { create(:bundle_product, bundle:, product: versioned_product, variant: versioned_product.alive_variants.first, quantity: 3, updated_at: 1.year.from_now) }
let(:purchase) { create(:purchase, link: bundle, created_at: 2.years.from_now) }
let(:outdated_purchase) { create(:purchase, link: bundle, created_at: 1.year.ago) }
before do
purchase.create_artifacts_and_send_receipt!
outdated_purchase.create_artifacts_and_send_receipt!
outdated_purchase.product_purchases.last.destroy!
end
describe "#perform" do
it "updates bundle purchase content for outdated purchases" do
expect(Purchase::UpdateBundlePurchaseContentService).to receive(:new).with(outdated_purchase).and_call_original
expect(Purchase::UpdateBundlePurchaseContentService).to_not receive(:new).with(purchase).and_call_original
expect do
described_class.new.perform(bundle.id)
end.to change { bundle.reload.has_outdated_purchases }.from(true).to(false)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/recurring_charge_worker_spec.rb | spec/sidekiq/recurring_charge_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RecurringChargeWorker, :vcr do
include ManageSubscriptionHelpers
before do
@product = create(:subscription_product, user: create(:user))
@subscription = create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: @product)
end
it "doesn't call charge on test_subscriptions" do
@product.user.credit_card = create(:credit_card)
@product.user.save!
subscription = create(:subscription, user: @product.user, link: @product)
subscription.is_test_subscription = true
subscription.save!
create(:test_purchase, seller: @product.user, purchaser: @product.user, link: @product, price_cents: @product.price_cents,
is_original_subscription_purchase: true, subscription:)
expect_any_instance_of(Subscription).to_not receive(:charge!)
described_class.new.perform(subscription.id)
end
it "doesn't call charge on free purchases" do
link = create(:product, user: create(:user), price_cents: 0, price_range: "0+")
subscription = create(:subscription, user: create(:user), link:)
create(:free_purchase, link:, price_cents: 0, is_original_subscription_purchase: true, subscription:)
expect_any_instance_of(Subscription).to_not receive(:charge!)
described_class.new.perform(subscription.id)
end
it "doesn't call charge if there was a purchase made the period for a monthly subscription" do
link = create(:product, user: create(:user), subscription_duration: "monthly")
subscription = create(:subscription, user: create(:user), link:)
create(:purchase, link:, price_cents: link.price_cents, is_original_subscription_purchase: true, subscription:)
expect_any_instance_of(Subscription).to_not receive(:charge!)
described_class.new.perform(subscription.id)
end
it "doesn't call charge if there was a purchase made the period for a yearly subscription" do
link = create(:product, user: create(:user), subscription_duration: "yearly")
subscription = create(:subscription, user: create(:user), link:)
create(:purchase, link:, price_cents: link.price_cents, is_original_subscription_purchase: true, subscription:)
expect_any_instance_of(Subscription).to_not receive(:charge!)
described_class.new.perform(subscription.id)
end
it "doesn't call `charge` when invoked one day before the subscription period end date" do
product = create(:product, user: create(:user), subscription_duration: "yearly")
subscription = create(:subscription, user: create(:user), link: product)
create(:purchase, link: product, price_cents: product.price_cents, is_original_subscription_purchase: true, subscription:)
travel_to(subscription.period.from_now - 1.day) do
expect_any_instance_of(Subscription).to_not receive(:charge!)
described_class.new.perform(subscription.id)
end
end
it "calls `charge` when invoked at the end of the subscription period" do
create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
travel_to(@subscription.period.from_now) do
expect_any_instance_of(Subscription).to receive(:charge!)
described_class.new.perform(@subscription.id)
end
end
it "doesn't call `charge` when invoked early, after refunded purchase" do
travel_to(Time.zone.local(2018, 6, 15) - @subscription.period * 2)
create(:purchase, link: @product, is_original_subscription_purchase: true, subscription: @subscription)
travel_to(Time.current + @subscription.period)
create(:purchase, link: @product, subscription: @subscription, stripe_refunded: true)
travel_to(Time.current + 5.days)
expect_any_instance_of(Subscription).not_to receive(:charge!)
described_class.new.perform(@subscription.id)
end
it "doesn't call `charge` when invoked one day after the subscription period end date but there's already a purchase in progress" do
create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
create(:purchase, link: @product, price_cents: @product.price_cents, subscription: @subscription, purchase_state: "in_progress")
travel_to(@subscription.period.from_now + 1.day) do
expect(@subscription.has_a_charge_in_progress?).to be true
expect_any_instance_of(Subscription).not_to receive(:charge!)
described_class.new.perform(@subscription.id)
end
end
it "calls `charge` when invoked one day after the subscription period end date" do
create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
travel_to(@subscription.period.from_now + 1.day) do
expect_any_instance_of(Subscription).to receive(:charge!)
described_class.new.perform(@subscription.id)
end
end
it "calls charge when invoked one year after the subscription period end date" do
create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
travel_to(@subscription.period.from_now + 1.year) do
expect_any_instance_of(Subscription).to receive(:charge!)
described_class.new.perform(@subscription.id)
end
end
it "calls `charge` for subscriptions purchased on 30th January when invoked at the end of the subscription period" do
travel_to(Time.current.change(year: 2018, month: 1, day: 30)) do
create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
end
travel_to(@subscription.period.from_now) do
expect_any_instance_of(Subscription).to receive(:charge!)
described_class.new.perform(@subscription.id)
end
end
describe "with ignore_consecutive_failures = true" do
context "when last purchase failed" do
before { create(:membership_purchase, subscription: @subscription, link: @product, purchase_state: "failed") }
it "does not call `charge`" do
allow_any_instance_of(Subscription).to receive(:seconds_overdue_for_charge).and_return(5.days - 1.minute)
travel_to(@subscription.period.from_now) do
expect_any_instance_of(Subscription).not_to receive(:charge!)
expect_any_instance_of(Subscription).not_to receive(:unsubscribe_and_fail!)
described_class.new.perform(@subscription.id, true)
end
end
it "calls `unsubscribe_and_fail!` when the subscription is at least 5 days overdue for a charge" do
allow_any_instance_of(Subscription).to receive(:seconds_overdue_for_charge).and_return(5.days + 1.minute)
travel_to(@subscription.period.from_now) do
expect_any_instance_of(Subscription).not_to receive(:charge!)
expect_any_instance_of(Subscription).to receive(:unsubscribe_and_fail!)
described_class.new.perform(@subscription.id, true)
end
end
end
end
describe "subscription is cancelled" do
before do
@product = create(:product, user: create(:user))
@subscription = create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: @product, cancelled_at: 1.hour.ago)
create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
end
it "calls charge on subscriptions" do
expect_any_instance_of(Subscription).to_not receive(:charge!)
described_class.new.perform(@subscription.id)
end
end
describe "subscription has failed" do
before do
@product = create(:product, user: create(:user))
@subscription = create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: @product, failed_at: Time.current)
create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
end
it "calls charge on subscriptions" do
expect_any_instance_of(Subscription).to_not receive(:charge!)
described_class.new.perform(@subscription.id)
end
end
describe "subscription has ended" do
before do
create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
@subscription.update_attribute(:ended_at, Time.current)
end
it "calls charge on subscriptions" do
expect_any_instance_of(Subscription).to_not receive(:charge!)
described_class.new.perform(@subscription.id)
end
end
describe "subscription has a pending plan change" do
before do
setup_subscription
@older_plan_change = create(:subscription_plan_change, subscription: @subscription, created_at: 1.day.ago)
@plan_change = create(:subscription_plan_change, subscription: @subscription, tier: @new_tier, recurrence: "monthly")
travel_to(@originally_subscribed_at + @subscription.period + 1.minute)
end
it "updates the variants and prices before charging" do
described_class.new.perform(@subscription.id)
updated_purchase = @subscription.reload.original_purchase
expect(updated_purchase.variant_attributes).to eq [@new_tier]
expect(@subscription.price).to eq @monthly_product_price
expect(updated_purchase.displayed_price_cents).to eq @new_tier_monthly_price.price_cents
end
it "marks the plan change deleted and applied, and marks older plan changes deleted" do
described_class.new.perform(@subscription.id)
@plan_change.reload
@older_plan_change.reload
expect(@plan_change).to be_deleted
expect(@plan_change).to be_applied
expect(@older_plan_change).to be_deleted
expect(@older_plan_change).not_to be_applied
end
it "charges the new price" do
expect do
described_class.new.perform(@subscription.id)
end.to change { @subscription.purchases.not_is_original_subscription_purchase.not_is_archived_original_subscription_purchase.count }.by(1)
last_purchase = @subscription.purchases.not_is_original_subscription_purchase.last
expect(last_purchase.displayed_price_cents).to eq @new_tier_monthly_price.price_cents
end
it "switches the subscription to the new flat fee" do
@subscription.update!(flat_fee_applicable: false)
expect do
described_class.new.perform(@subscription.id)
end.to change { @subscription.reload.flat_fee_applicable? }.to(true)
end
context "for a PWYW tier" do
it "sets the original purchase price to the perceived_price_cents" do
@new_tier.update!(customizable_price: true)
@plan_change.update!(perceived_price_cents: 100_00)
described_class.new.perform(@subscription.id)
updated_purchase = @subscription.reload.original_purchase
expect(updated_purchase.displayed_price_cents).to eq 100_00
end
end
context "when the price has changed" do
it "relies on the price at the time of the downgrade" do
@plan_change.update!(perceived_price_cents: 2_50)
described_class.new.perform(@subscription.id)
updated_purchase = @subscription.reload.original_purchase
expect(updated_purchase.displayed_price_cents).to eq 2_50
end
end
context "when the recurrence option has been deleted" do
it "still uses that recurrence" do
@monthly_product_price.mark_deleted!
described_class.new.perform(@subscription.id)
expect(@subscription.reload.price).to eq @monthly_product_price
end
end
context "when the tier has been deleted" do
it "still uses that tier" do
@new_tier.mark_deleted!
described_class.new.perform(@subscription.id)
updated_purchase = @subscription.reload.original_purchase
expect(updated_purchase.variant_attributes).to eq [@new_tier]
end
end
context "when the plan change is not currently applicable" do
it "does not apply the plan change" do
@plan_change.update!(for_product_price_change: true, effective_on: 1.day.from_now)
expect do
described_class.new.perform(@subscription.id)
end.not_to change { @plan_change.applied? }.from(false)
expect(@subscription.reload.original_purchase).to eq @original_purchase
end
end
describe "workflows" do
before do
workflow = create(:variant_workflow, seller: @product.user, link: @product, base_variant: @new_tier)
@installment = create(:installment, link: @product, base_variant: @new_tier, workflow:, published_at: 1.day.ago)
create(:installment_rule, installment: @installment, delayed_delivery_time: 1.day)
end
it "schedules tier workflows if tier has changed" do
described_class.new.perform(@subscription.id)
purchase_id = @subscription.reload.original_purchase.id
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@installment.id, 1, purchase_id, nil, nil)
end
it "does not schedule workflows if tier has not changed" do
@plan_change.update!(tier: @original_tier)
described_class.new.perform(@subscription.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(0)
end
end
describe "integrations" do
it "enqueues integrations update if tier has changed" do
described_class.new.perform(@subscription.id)
expect(UpdateIntegrationsOnTierChangeWorker).to have_enqueued_sidekiq_job(@subscription.id)
end
it "does not enqueue integrations update if tier has not changed" do
@plan_change.update!(tier: @original_tier)
described_class.new.perform(@subscription.id)
expect(UpdateIntegrationsOnTierChangeWorker.jobs.size).to eq(0)
end
end
end
describe "non-tiered subscription has a pending plan change" do
before do
travel_to(4.months.ago) do
product = create(:subscription_product, subscription_duration: BasePrice::Recurrence::MONTHLY, price_cents: 12_99)
@variant = create(:variant, variant_category: create(:variant_category, link: product))
@monthly_price = product.prices.find_by!(recurrence: BasePrice::Recurrence::MONTHLY)
@quarterly_price = create(:price, link: product, recurrence: BasePrice::Recurrence::QUARTERLY, price_cents: 30_00)
@subscription = create(:subscription, credit_card: create(:credit_card), link: product, price: @quarterly_price)
@original_purchase = create(:purchase, is_original_subscription_purchase: true,
link: product,
subscription: @subscription,
variant_attributes: [@variant],
credit_card: @subscription.credit_card,
price: @quarterly_price,
price_cents: @quarterly_price.price_cents,
purchase_state: "successful")
@plan_change = create(:subscription_plan_change, subscription: @subscription,
tier: nil,
recurrence: BasePrice::Recurrence::MONTHLY,
perceived_price_cents: 5_00)
end
end
it "updates the price before charging" do
described_class.new.perform(@subscription.id)
updated_purchase = @subscription.reload.original_purchase
expect(updated_purchase.variant_attributes).to eq [@variant]
expect(@subscription.price).to eq @monthly_price
expect(updated_purchase.displayed_price_cents).to eq @plan_change.perceived_price_cents
last_charge = @subscription.purchases.successful.last
expect(last_charge.id).not_to eq @original_purchase.id
expect(last_charge.displayed_price_cents).to eq @plan_change.perceived_price_cents
end
end
describe "seller is banned" do
before do
@seller = create(:user)
@product = create(:product, user: @seller)
@subscription = create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: @product)
create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
@seller.user_risk_state = "suspended_for_fraud"
@seller.save
end
describe "subscription_id provided" do
it "does not call charge on a subscription" do
expect_any_instance_of(Subscription).to_not receive(:charge!)
described_class.new.perform(@subscription.id)
end
end
end
describe "subscriber removes his credit card" do
it "calls `charge` on subscriptions" do
@product = create(:product, user: create(:user), subscription_duration: "monthly")
@subscription = create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: @product)
purchase = create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
subscriber = @subscription.user
subscriber.credit_card = nil
subscriber.save!
purchase.update(succeeded_at: 3.days.ago)
travel_to(1.month.from_now) do
described_class.new.perform(@subscription.id)
expect(Purchase.last.purchase_state).to eq "failed"
expect(Purchase.last.error_code).to eq PurchaseErrorCode::CREDIT_CARD_NOT_PROVIDED
end
end
end
describe "subscription has free trial" do
before do
product = create(:membership_product, free_trial_enabled: true, free_trial_duration_amount: 1, free_trial_duration_unit: :week)
purchase = create(:membership_purchase, link: product, purchase_state: "not_charged", is_free_trial_purchase: true, price_cents: 300)
@subscription = purchase.subscription
@subscription.update!(free_trial_ends_at: 1.week.from_now, credit_card: create(:credit_card))
end
context "free trial has ended" do
it "charges the user" do
travel_to(8.days.from_now) do
expect do
described_class.new.perform(@subscription.id)
end.to change { @subscription.purchases.successful.count }.by(1)
end
end
end
context "free trial has not yet ended" do
it "does not charge the user" do
expect_any_instance_of(Subscription).not_to receive(:charge!)
described_class.new.perform(@subscription.id)
end
end
end
context "subscription has a fixed-duration offer code that makes the product free for the first billing period" do
before do
offer_code = create(:offer_code, products: [@product], duration_in_months: 1, amount_cents: @product.price_cents)
create(:purchase, link: @product, price_cents: 0, is_original_subscription_purchase: true, subscription: @subscription, offer_code:).create_purchase_offer_code_discount(offer_code:, offer_code_amount: @product.price_cents, offer_code_is_percent: false, pre_discount_minimum_price_cents: @product.price_cents, duration_in_billing_cycles: 1)
end
it "calls charge when the offer code has elapsed" do
travel_to(@subscription.period.from_now) do
expect_any_instance_of(Subscription).to receive(:charge!)
described_class.new.perform(@subscription.id)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/invalidate_product_cache_worker_spec.rb | spec/sidekiq/invalidate_product_cache_worker_spec.rb | # frozen_string_literal: true
describe InvalidateProductCacheWorker do
describe "#perform" do
before do
@product = create(:product)
end
it "expires the product cache" do
expect_any_instance_of(Link).to receive(:invalidate_cache).once
described_class.new.perform(@product.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/push_notification_worker_spec.rb | spec/sidekiq/push_notification_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PushNotificationWorker do
before do
@user = create(:user)
@device_a = create(:device, user: @user)
@device_b = create(:android_device, user: @user)
@device_c = create(:device, user: @user)
end
it "sends the notification to each of the user's devices" do
ios_a = double("ios_a")
ios_c = double("ios_c")
android_b = double("android_b")
allow(PushNotificationService::Ios).to receive(:new).with(device_token: @device_a.token,
title: "Title",
body: "Body",
data: {},
app_type: Device::APP_TYPES[:creator],
sound: Device::NOTIFICATION_SOUNDS[:sale]).and_return(ios_a)
allow(PushNotificationService::Ios).to receive(:new).with(device_token: @device_c.token,
title: "Title",
body: "Body",
data: {},
app_type: Device::APP_TYPES[:creator],
sound: Device::NOTIFICATION_SOUNDS[:sale]).and_return(ios_c)
allow(PushNotificationService::Android).to receive(:new).with(device_token: @device_b.token,
title: "Title",
body: "Body",
data: {},
app_type: Device::APP_TYPES[:creator],
sound: Device::NOTIFICATION_SOUNDS[:sale]).and_return(android_b)
expect(ios_a).to receive(:process)
expect(ios_c).to receive(:process)
expect(android_b).to receive(:process)
PushNotificationWorker.new.perform(@user.id, Device::APP_TYPES[:creator], "Title", "Body", {}, Device::NOTIFICATION_SOUNDS[:sale])
end
it "sends the notification only to given app_type" do
ios_a = double("ios_a")
ios_d = double("ios_d")
@device_d = create(:device, user: @user, app_type: Device::APP_TYPES[:consumer])
allow(PushNotificationService::Ios).to receive(:new).with(device_token: @device_a.token,
title: "Title",
body: "Body",
data: {},
app_type: Device::APP_TYPES[:consumer],
sound: nil).and_return(ios_a)
allow(PushNotificationService::Ios).to receive(:new).with(device_token: @device_d.token,
title: "Title",
body: "Body",
data: {},
app_type: Device::APP_TYPES[:consumer],
sound: nil).and_return(ios_d)
expect(ios_a).to_not receive(:process)
expect(ios_d).to receive(:process)
PushNotificationWorker.new.perform(@user.id, Device::APP_TYPES[:consumer], "Title", "Body", {})
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_year_in_review_email_job_spec.rb | spec/sidekiq/send_year_in_review_email_job_spec.rb | # frozen_string_literal: true
describe SendYearInReviewEmailJob do
include PaymentsHelper, ProductPageViewHelpers
describe ".perform" do
context "when no payouts exist for the selected year" do
let(:date) { Date.new(2021, 2, 22) }
let!(:seller) do
create(
:user_with_compliance_info,
:with_annual_report,
year: (date.year - 1),
created_at: (date - 1.year).to_time
)
end
it "does send an email" do
travel_to(date) do
12.times { create_payment_with_purchase(seller, date - 1.year) }
end
expect do
described_class.new.perform(seller.id, date.year)
end.to change { ActionMailer::Base.deliveries.count }.by(0)
end
end
context "when payouts exist for the selected year", :vcr, :elasticsearch_wait_for_refresh do
let(:date) { Date.new(2022, 2, 22) }
let!(:seller) do
create(:user_with_compliance_info,
:with_annual_report,
name: "Seller",
year: date.year,
created_at: (date - 1.year).to_time
)
end
context "when seller made only affiliate sales" do
before do
create(:payment_completed, user: seller, amount_cents: 100_00, payout_period_end_date: date, created_at: date)
end
it "does not send an email" do
expect do
described_class.new.perform(seller.id, date.year)
end.to_not change { ActionMailer::Base.deliveries.count }
end
end
context "when seller sold only one product" do
before do
recreate_model_index(ProductPageView)
travel_to(date) do
product = create(:product, user: seller, name: "Product 1")
create_payment_with_purchase(seller, date, product:, amount_cents: 1_000_00, ip_country: "United States")
2.times { add_page_view(product, Time.current.iso8601, { country: "United States" }) }
end
allow_any_instance_of(Exports::Payouts::Annual).to receive(:perform) {
{
csv_file: Rack::Test::UploadedFile.new("#{Rails.root}/spec/support/fixtures/followers_import.csv"),
total_amount: 1_000_00
}
}
index_model_records(Purchase)
end
it "shows stats only for one product" do
expect do
described_class.new.perform(seller.id, date.year)
end.to change { ActionMailer::Base.deliveries.count }.by(1)
mail = ActionMailer::Base.deliveries.last
expect(mail.to).to eq([seller.email])
expect(mail.subject).to eq("Your 2022 in review")
expect(mail.body.sanitized).to include("Views 2")
expect(mail.body.sanitized).to include("Sales 1")
expect(mail.body.sanitized).to include("Unique customers 1")
expect(mail.body.sanitized).to include("Products sold 1")
expect(mail.body.sanitized).to include("Your top product")
expect(mail.body.sanitized).to match(/Product 1 \( \S+ \) -+ Views 2 Sales 1 Total 1K/)
expect(mail.body.sanitized).to include("You earned a total of $1,000")
expect(mail.body.sanitized).to include("You sold products in 1 country")
expect(mail.body.sanitized).to_not include("Elsewhere")
expect(mail.body.sanitized).to include("United States 2 1 $1K")
expect(mail.body.sanitized).to include(seller.financial_annual_report_url_for(year: date.year))
end
end
context "when seller is from US" do
before do
@product_permalinks = generate_data_for(seller, date, products_count: 10)
@top_product_names = seller.products.where(unique_permalink: @product_permalinks.first(5)).pluck(:name)
end
context "when seller is eligible for 1099" do
before { allow_any_instance_of(User).to receive(:eligible_for_1099?).and_return(true) }
it "sends an email with 1099 eligibility confirmation" do
expect do
described_class.new.perform(seller.id, date.year)
end.to change { ActionMailer::Base.deliveries.count }.by(1)
mail = ActionMailer::Base.deliveries.last
expect(mail.to).to eq([seller.email])
expect(mail.subject).to eq("Your 2022 in review")
expect(mail.body.sanitized).to include("Views 24")
expect(mail.body.sanitized).to include("Sales 12")
expect(mail.body.sanitized).to include("Unique customers 12")
expect(mail.body.sanitized).to include("Products sold #{@product_permalinks.size}")
@top_product_names.each do |product_name|
expect(mail.body.sanitized).to match(/#{product_name} \( \S+ \)( =)? -+ Views \d+ Sales \d+ Total \d+/)
end
expect(mail.body.sanitized).to include("You earned a total of $1,200")
expect(mail.body.sanitized).to include("You sold products in 1 country")
expect(mail.body.sanitized).to_not include("United States")
expect(mail.body.sanitized).to include("Elsewhere 24 12 $1.2K")
expect(mail.body.sanitized).to include("You'll be receiving a 1099 from us in the next few weeks.")
expect(mail.body.sanitized).to include(seller.financial_annual_report_url_for(year: date.year))
end
context "when recipient is passed as param" do
it "sends an email to recipient instead of seller" do
expect do
described_class.new.perform(seller.id, date.year, "gumbot@gumroad.com")
end.to change { ActionMailer::Base.deliveries.count }.by(1)
mail = ActionMailer::Base.deliveries.last
expect(mail.to).to eq(["gumbot@gumroad.com"])
expect(mail.subject).to eq("Your 2022 in review")
expect(mail.body.sanitized).to include("Views 24")
expect(mail.body.sanitized).to include("Sales 12")
expect(mail.body.sanitized).to include("Unique customers 12")
expect(mail.body.sanitized).to include("Products sold #{@product_permalinks.size}")
@top_product_names.each do |product_name|
expect(mail.body.sanitized).to match(/#{product_name} \( \S+ \)( =)? -+ Views \d+ Sales \d+ Total \d+/)
end
expect(mail.body.sanitized).to include("You earned a total of $1,200")
expect(mail.body.sanitized).to include("You sold products in 1 country")
expect(mail.body.sanitized).to_not include("United States")
expect(mail.body.sanitized).to include("Elsewhere 24 12 $1.2K")
expect(mail.body.sanitized).to include("You'll be receiving a 1099 from us in the next few weeks.")
expect(mail.body.sanitized).to include(seller.financial_annual_report_url_for(year: date.year))
end
end
end
context "when seller is not eligible for 1099" do
it "sends an email with 1099 non eligibility confirmation" do
expect do
described_class.new.perform(seller.id, date.year)
end.to change { ActionMailer::Base.deliveries.count }.by(1)
mail = ActionMailer::Base.deliveries.last
expect(mail.to).to eq([seller.email])
expect(mail.subject).to eq("Your 2022 in review")
expect(mail.body.sanitized).to include("Views 24")
expect(mail.body.sanitized).to include("Sales 12")
expect(mail.body.sanitized).to include("Unique customers 12")
expect(mail.body.sanitized).to include("Products sold #{@product_permalinks.size}")
@top_product_names.each do |product_name|
expect(mail.body.sanitized).to match(/#{product_name} \( \S+ \)( =)? -+ Views \d+ Sales \d+ Total \d+/)
end
expect(mail.body.sanitized).to include("You earned a total of $1,200")
expect(mail.body.sanitized).to include("You sold products in 1 country")
expect(mail.body.sanitized).to_not include("United States")
expect(mail.body.sanitized).to include("Elsewhere 24 12 $1.2K")
expect(mail.body.sanitized).to include("You do not qualify for a 1099 this year.")
expect(mail.body.sanitized).to include(seller.financial_annual_report_url_for(year: date.year))
end
end
end
context "when seller is not from US" do
let(:seller) do
create(
:singaporean_user_with_compliance_info,
:with_annual_report,
name: "Seller",
year: date.year,
created_at: (date - 1.year).to_time
)
end
before do
@product_permalinks = generate_data_for(seller, date)
top_products = seller.products.where(unique_permalink: @product_permalinks.first(5))
@top_product_names = top_products.pluck(:name)
# Mimic no product views
recreate_model_index(ProductPageView)
travel_to(date) do
create_payment_with_purchase(seller, date, product: top_products.first, amount_cents: 100_00, ip_country: "Romania")
add_page_view(top_products.first, Time.current.iso8601, { country: "Romania" })
end
index_model_records(Purchase)
end
it "sends an email without 1099 section" do
expect do
described_class.new.perform(seller.id, date.year)
end.to change { ActionMailer::Base.deliveries.count }.by(1)
mail = ActionMailer::Base.deliveries.last
expect(mail.to).to eq([seller.email])
expect(mail.subject).to eq("Your 2022 in review")
expect(mail.body.sanitized).to include("Views 1")
expect(mail.body.sanitized).to include("Sales 13")
expect(mail.body.sanitized).to include("Unique customers 13")
expect(mail.body.sanitized).to include("Products sold #{@product_permalinks.size}")
@top_product_names.each do |product_name|
expect(mail.body.sanitized).to match(/#{product_name} \( \S+ \)( =)? -+ Views \d+ Sales \d+ Total \d+/)
end
expect(mail.body.sanitized).to include("You earned a total of $1,300")
expect(mail.body.sanitized).to include("You sold products in 2 countries")
expect(mail.body.sanitized).to_not include("United States")
expect(mail.body.sanitized).to include("Romania 1 1 $100")
expect(mail.body.sanitized).to include("Elsewhere 0 12 $1.2K")
expect(mail.body.sanitized).to include(seller.financial_annual_report_url_for(year: date.year))
expect(mail.body.sanitized).to_not include("You do not qualify for a 1099 this year.")
expect(mail.body.sanitized).to_not include("You'll be receiving a 1099 from us in the next few weeks.")
end
end
end
end
private
def generate_data_for(seller, date, products_count: 8)
recreate_model_index(ProductPageView)
products = build_list(:product, products_count, user: seller) do |product, i|
product.name = "Product #{i + 1}"
product.save!
end
product_sales_for_current_year = products.to_h { |product| [product.unique_permalink, 0] }
travel_to(date - 1.year) do
12.times do
payment_data = create_payment_with_purchase(seller, date - 1.year, product: products.sample, amount_cents: 100_00)
add_page_view(payment_data[:purchase].link)
end
end
travel_to(date) do
12.times do
product = products.sample
payment_data = create_payment_with_purchase(seller, date, product:, amount_cents: 100_00)
2.times { add_page_view(product) }
product_sales_for_current_year[product.unique_permalink] += payment_data[:payment].amount_cents
end
allow_any_instance_of(Exports::Payouts::Annual).to receive(:perform) {
{
csv_file: Rack::Test::UploadedFile.new("#{Rails.root}/spec/support/fixtures/followers_import.csv"),
total_amount: 1_000_00
}
}
end
index_model_records(Purchase)
product_sales_for_current_year.filter { |_, total| total.nonzero? }
.sort_by { |key, total_sales| [-total_sales, key] }
.map(&:first)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/cache_product_data_worker_spec.rb | spec/sidekiq/cache_product_data_worker_spec.rb | # frozen_string_literal: true
describe CacheProductDataWorker do
describe "#perform" do
before do
@product = create(:product)
end
it "creates new product cache data" do
expect do
described_class.new.perform(@product.id)
end.to change { ProductCachedValue.count }.by(1)
product_cached_data = @product.reload.product_cached_values.last
expect(product_cached_data.successful_sales_count).to eq(0)
expect(product_cached_data.remaining_for_sale_count).to eq(nil)
expect(product_cached_data.monthly_recurring_revenue).to eq(0.0)
expect(product_cached_data.revenue_pending).to eq(0)
expect(product_cached_data.total_usd_cents).to eq(0)
end
context "when data is already cached" do
before do
@product_cached_value = @product.product_cached_values.create!
end
it "expires the current cache and creates a new cached record" do
expect do
described_class.new.perform(@product.id)
end.to change { @product_cached_value.reload.expired }.from(false).to(true)
.and change { ProductCachedValue.count }.by(1)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/sync_stuck_payouts_job_spec.rb | spec/sidekiq/sync_stuck_payouts_job_spec.rb | # frozen_string_literal: true
describe SyncStuckPayoutsJob do
describe "#perform" do
context "when processor type if PayPal" do
before do
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "completed", txn_id: "12345", processor_fee_cents: 0)
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "completed", txn_id: "67890", processor_fee_cents: 0)
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "failed")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "failed")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "cancelled")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "cancelled")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "returned")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "returned")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "reversed")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "reversed")
end
it "syncs all stuck PayPal payouts" do
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "creating")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "creating")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "processing")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "processing")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "processing")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "unclaimed")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "unclaimed")
expect(PaypalPayoutProcessor).to receive(:search_payment_on_paypal).exactly(7).times
described_class.new.perform(PayoutProcessorType::PAYPAL)
end
it "does not sync those payments that are not either in 'creating', 'processing', or 'unclaimed' state" do
expect(PaypalPayoutProcessor).not_to receive(:get_latest_payment_state_from_paypal)
expect(PaypalPayoutProcessor).not_to receive(:search_payment_on_paypal)
described_class.new.perform(PayoutProcessorType::PAYPAL)
end
it "does not try to sync Stripe payouts" do
create(:payment, processor: PayoutProcessorType::STRIPE, state: "creating",
stripe_transfer_id: "tr_123", stripe_connect_account_id: "acct_123")
create(:payment, processor: PayoutProcessorType::STRIPE, state: "processing",
stripe_transfer_id: "tr_456", stripe_connect_account_id: "acct_456")
create(:payment, processor: PayoutProcessorType::STRIPE, state: "unclaimed",
stripe_transfer_id: "tr_789", stripe_connect_account_id: "acct_789")
expect(PaypalPayoutProcessor).not_to receive(:get_latest_payment_state_from_paypal)
expect(PaypalPayoutProcessor).not_to receive(:search_payment_on_paypal)
described_class.new.perform(PayoutProcessorType::PAYPAL)
end
it "processes all stuck payouts even if any of them raises an error" do
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "creating")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "creating")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "processing")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "processing")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "processing")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "unclaimed")
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "unclaimed")
allow(PaypalPayoutProcessor).to receive(:search_payment_on_paypal).and_raise ActiveRecord::RecordInvalid
expect(PaypalPayoutProcessor).to receive(:search_payment_on_paypal).exactly(7).times
expect(Rails.logger).to receive(:error).with(/Error syncing PayPal payout/).exactly(7).times
described_class.new.perform(PayoutProcessorType::PAYPAL)
end
end
context "when processor type if Stripe" do
it "syncs stuck Stripe payouts" do
create(:payment, processor: PayoutProcessorType::STRIPE, state: "processing",
stripe_transfer_id: "tr_12", stripe_connect_account_id: "acct_12")
expect_any_instance_of(Payment).to receive(:sync_with_payout_processor).and_call_original
expect(PaypalPayoutProcessor).not_to receive(:search_payment_on_paypal)
described_class.new.perform(PayoutProcessorType::STRIPE)
end
it "does not sync those payments that are not either in 'creating', 'processing', or 'unclaimed' state" do
create(:payment, processor: PayoutProcessorType::STRIPE, state: "completed", txn_id: "12345", processor_fee_cents: 0,
stripe_transfer_id: "tr_12", stripe_connect_account_id: "acct_12")
create(:payment, processor: PayoutProcessorType::STRIPE, state: "failed",
stripe_transfer_id: "tr_34", stripe_connect_account_id: "acct_34")
create(:payment, processor: PayoutProcessorType::STRIPE, state: "cancelled",
stripe_transfer_id: "tr_56", stripe_connect_account_id: "acct_56")
create(:payment, processor: PayoutProcessorType::STRIPE, state: "returned",
stripe_transfer_id: "tr_78", stripe_connect_account_id: "acct_78")
create(:payment, processor: PayoutProcessorType::STRIPE, state: "reversed",
stripe_transfer_id: "tr_90", stripe_connect_account_id: "acct_90")
expect_any_instance_of(Payment).not_to receive(:sync_with_payout_processor)
described_class.new.perform(PayoutProcessorType::STRIPE)
end
it "does not try to sync PayPal payouts" do
create(:payment, processor: PayoutProcessorType::PAYPAL, state: "processing")
expect_any_instance_of(Payment).not_to receive(:sync_with_payout_processor)
described_class.new.perform(PayoutProcessorType::STRIPE)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/regenerate_sales_related_products_infos_job_spec.rb | spec/sidekiq/regenerate_sales_related_products_infos_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RegenerateSalesRelatedProductsInfosJob do
describe "#perform" do
let(:seller) { create(:named_seller) }
let(:sample_product) { create(:product, user: seller) }
let(:product1) { create(:product, name: "Product 1") }
let(:product2) { create(:product, name: "Product 2") }
let(:product3) { create(:product, name: "Product 3") }
before do
build_list(:purchase, 3, link: sample_product) do |purchase, i|
purchase.update!(email: "customer#{i}@example.com")
end
build_list(:purchase, 3, link: product1) do |purchase, i|
purchase.update!(email: "customer#{i}@example.com")
end
build_list(:purchase, 2, link: product2) do |purchase, i|
purchase.update!(email: "customer#{i}@example.com")
end
create(:purchase, link: product3, email: "customer0@example.com")
end
it "creates SalesRelatedProductsInfo records for the product" do
expect do
described_class.new.perform(sample_product.id)
end.to change { SalesRelatedProductsInfo.count }.by(3)
expect(SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product1.id).sales_count).to eq(3)
expect(SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product2.id).sales_count).to eq(2)
expect(SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product3.id).sales_count).to eq(1)
SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product1.id).delete # will be recreated
SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product2.id).update_column(:sales_count, 0) # will be updated
expect do
described_class.new.perform(sample_product.id)
end.to change { SalesRelatedProductsInfo.count }.by(1)
expect(SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product1.id).sales_count).to eq(3)
expect(SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product2.id).sales_count).to eq(2)
expect(SalesRelatedProductsInfo.find_or_create_info(sample_product.id, product3.id).sales_count).to eq(1)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_purchase_receipt_job_spec.rb | spec/sidekiq/send_purchase_receipt_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SendPurchaseReceiptJob do
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
let(:purchase) { create(:purchase, link: product, seller: seller) }
let(:mail_double) { double }
before do
allow(mail_double).to receive(:deliver_now)
end
context "when the purchase is for a product with stampable PDFs" do
before do
allow(PdfStampingService).to receive(:stamp_for_purchase!)
allow_any_instance_of(Link).to receive(:has_stampable_pdfs?).and_return(true)
end
it "stamps the PDFs and delivers the email" do
expect(CustomerMailer).to receive(:receipt).with(purchase.id).and_return(mail_double)
described_class.new.perform(purchase.id)
expect(PdfStampingService).to have_received(:stamp_for_purchase!).with(purchase)
expect(mail_double).to have_received(:deliver_now)
end
context "when stamping the PDF fails" do
before do
allow(PdfStampingService).to receive(:stamp_for_purchase!).and_raise(PdfStampingService::Error)
end
it "doesn't deliver the email and raises an error" do
expect(CustomerMailer).not_to receive(:receipt).with(purchase.id)
expect { described_class.new.perform(purchase.id) }.to raise_error(PdfStampingService::Error)
end
end
end
context "when the purchase is for a product without stampable PDFs" do
before do
allow(PdfStampingService).to receive(:stamp_for_purchase!)
allow_any_instance_of(Link).to receive(:has_stampable_pdfs?).and_return(false)
end
it "delivers the email and doesn't stamp PDFs" do
expect(CustomerMailer).to receive(:receipt).with(purchase.id).and_return(mail_double)
described_class.new.perform(purchase.id)
expect(PdfStampingService).not_to have_received(:stamp_for_purchase!)
expect(mail_double).to have_received(:deliver_now)
end
end
context "when the purchase is a bundle product purchae" do
before do
allow_any_instance_of(Purchase).to receive(:is_bundle_product_purchase?).and_return(true)
end
it "doens't deliver email" do
expect(CustomerMailer).not_to receive(:receipt).with(purchase.id)
described_class.new.perform(purchase.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/handle_stripe_autodebit_for_negative_balance_spec.rb | spec/sidekiq/handle_stripe_autodebit_for_negative_balance_spec.rb | # frozen_string_literal: true
describe HandleStripeAutodebitForNegativeBalance do
describe "#perform" do
let(:payment) { create(:payment) }
let(:stripe_payout_id) { "po_automatic" }
let(:stripe_account_id) { "stripe-account-id" }
let(:stripe_connect_account_id) { "acct_1234" }
let(:stripe_event_id) { "evt_eventid" }
let(:amount_cents) { -100_00 }
let(:stripe_payout_status) { raise "define `stripe_payout_status`" }
let(:balance_transaction_status) { raise "define `balance_transaction_status`" }
let(:stripe_payout_object) do
{
object: "payout",
id: "po_automatic",
automatic: true,
amount: amount_cents,
currency: "usd",
account: stripe_connect_account_id,
status: stripe_payout_status
}.deep_stringify_keys
end
let(:stripe_payout_object_with_balance_transaction) do
{
object: "payout",
id: "po_automatic",
automatic: true,
amount: amount_cents,
currency: "usd",
account: stripe_connect_account_id,
status: stripe_payout_status,
balance_transaction: {
status: balance_transaction_status
}
}.deep_stringify_keys
end
before do
allow(Stripe::Payout).to receive(:retrieve).with(stripe_payout_id, anything).and_return(stripe_payout_object)
allow(Stripe::Payout).to receive(:retrieve).with(hash_including({ id: stripe_payout_id }), anything).and_return(stripe_payout_object_with_balance_transaction)
end
context "payout succeeds" do
let(:stripe_payout_status) { "paid" }
let(:balance_transaction_status) { "available" }
it "calls the StripePayoutProcessor#handle_stripe_negative_balance_debit_event" do
expect(StripePayoutProcessor).to receive(:handle_stripe_negative_balance_debit_event).with(stripe_connect_account_id, stripe_payout_id)
HandleStripeAutodebitForNegativeBalance.new.perform(stripe_event_id, stripe_connect_account_id, stripe_payout_id)
end
end
context "payout fails" do
let(:stripe_payout_status) { "failed" }
let(:balance_transaction_status) { "available" }
it "does nothing and does not raise an error" do
expect(StripePayoutProcessor).not_to receive(:handle_stripe_negative_balance_debit_event)
HandleStripeAutodebitForNegativeBalance.new.perform(stripe_event_id, stripe_connect_account_id, stripe_payout_id)
end
end
context "payout isn't finalized" do
let(:stripe_payout_status) { "paid" }
let(:balance_transaction_status) { "pending" }
it "raises an error", :vcr, :sidekiq_inline do
expect do
HandleStripeAutodebitForNegativeBalance.new.perform(stripe_event_id, stripe_connect_account_id, stripe_payout_id)
end.to raise_error(RuntimeError, /Timed out waiting for payout to become finalized/)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/update_taxonomy_stats_job_spec.rb | spec/sidekiq/update_taxonomy_stats_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateTaxonomyStatsJob do
describe "#perform" do
it "updates the taxonomy stats" do
recreate_model_index(Purchase)
product_1 = create(:product, taxonomy: Taxonomy.find_by_path(["3d", "3d-modeling"]))
product_2 = create(:product, taxonomy: Taxonomy.find_by_path(["3d", "vrchat", "tools"]), user: product_1.user)
product_3 = create(:product, taxonomy: Taxonomy.find_by_path(["films", "movie", "anime"]))
product_4 = create(:product, taxonomy: Taxonomy.find_by_path(["films", "movie", "horror"]))
create(:purchase, link: product_1)
create_list(:purchase, 2, link: product_2)
create(:purchase, link: product_3)
create_list(:purchase, 3, link: product_4, created_at: 90.days.ago)
index_model_records(Purchase)
described_class.new.perform
stat_1 = TaxonomyStat.find_by(taxonomy: Taxonomy.find_by_path(["3d"]))
expect(stat_1.sales_count).to eq(3)
expect(stat_1.creators_count).to eq(1)
expect(stat_1.products_count).to eq(2)
expect(stat_1.recent_sales_count).to eq(3)
stat_2 = TaxonomyStat.find_by(taxonomy: Taxonomy.find_by_path(["films"]))
expect(stat_2.sales_count).to eq(4)
expect(stat_2.creators_count).to eq(2)
expect(stat_2.products_count).to eq(2)
expect(stat_2.recent_sales_count).to eq(1)
stat_3 = TaxonomyStat.find_by(taxonomy: Taxonomy.find_by_path(["education"]))
expect(stat_3.sales_count).to eq(0)
expect(stat_3.creators_count).to eq(0)
expect(stat_3.products_count).to eq(0)
expect(stat_3.recent_sales_count).to eq(0)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/schedule_workflow_emails_worker_spec.rb | spec/sidekiq/schedule_workflow_emails_worker_spec.rb | # frozen_string_literal: true
describe ScheduleWorkflowEmailsWorker do
before do
@product = create(:product)
@workflow = create(:workflow, seller: @product.user, link: @product)
@installment = create(:installment, link: @product, workflow: @workflow, published_at: Time.current)
create(:installment_rule, installment: @installment, delayed_delivery_time: 1.day)
@purchase = create(:purchase, link: @product, created_at: 1.week.ago, price_cents: 100)
end
describe "#perform" do
it "enqueues SendWorkflowInstallmentWorker for the installment" do
described_class.new.perform(@purchase.id)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@installment.id, 1, @purchase.id, nil, nil)
end
describe "filters" do
it "skips workflow if purchase created before" do
@workflow.created_after = Time.current
@workflow.save!
described_class.new.perform(@purchase.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(0)
end
it "skips workflow if purchase created after" do
@workflow.created_before = 1.month.ago
@workflow.save!
described_class.new.perform(@purchase.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(0)
end
it "skips workflow if purchase price is too low" do
@workflow.paid_more_than_cents = 1000
@workflow.save!
described_class.new.perform(@purchase.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(0)
end
it "skips workflow if purchase price is too high" do
@workflow.paid_less_than_cents = 99
@workflow.save!
described_class.new.perform(@purchase.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(0)
end
it "skips workflow if purchase is for different product" do
@workflow.bought_products = ["abc"]
@workflow.save!
described_class.new.perform(@purchase.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(0)
end
it "skips workflow if purchase is for different variant" do
product = create(:product)
variant = create(:variant, variant_category: create(:variant_category, link: product))
workflow = create(:seller_workflow, seller: product.user, created_at: Time.current)
workflow.bought_variants = ["xyz"]
workflow.save!
installment = create(:installment, workflow:, published_at: Time.current)
create(:installment_rule, installment:, delayed_delivery_time: 1.day)
purchase = create(:purchase, link: product, created_at: 1.week.ago, price_cents: 100)
purchase.variant_attributes << variant
described_class.new.perform(purchase.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(0)
end
it "skips workflow if purchase bought from a different country" do
@workflow.bought_from = "Canada"
@workflow.save!
described_class.new.perform(@purchase.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(0)
end
it "passes the filters and queues the installment" do
@workflow.paid_more_than_cents = 10
@workflow.created_before = Time.current
@workflow.save!
described_class.new.perform(@purchase.id)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@installment.id, 1, @purchase.id, nil, nil)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/reset_admin_action_call_counts_job_spec.rb | spec/sidekiq/reset_admin_action_call_counts_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ResetAdminActionCallCountsJob do
describe "#perform" do
it "recreates admin action call infos" do
create(:admin_action_call_info, call_count: 25)
create(:admin_action_call_info, controller_name: "NoLongerExistingController", call_count: 3)
described_class.new.perform
expect(AdminActionCallInfo.where(action_name: "index")).to be_present
expect(AdminActionCallInfo.where("call_count > 0")).to be_empty
expect(AdminActionCallInfo.where(controller_name: "NoLongerExistingController")).to be_empty
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/stripe_create_merchant_accounts_worker_spec.rb | spec/sidekiq/stripe_create_merchant_accounts_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StripeCreateMerchantAccountsWorker, :vcr do
describe "perform" do
describe "don't queue users who have merchant accounts already" do
let(:user_1) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_1) { create(:user_compliance_info, user: user_1) }
let(:tos_agreement_1) { create(:tos_agreement, user: user_1) }
let(:bank_account_1) { create(:ach_account, user: user_1) }
let(:balance_1) { create(:balance, created_at: 10.days.ago, user: user_1) }
let(:user_2) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_2) { create(:user_compliance_info, user: user_2) }
let(:tos_agreement_2) { create(:tos_agreement, user: user_2) }
let(:bank_account_2) { create(:ach_account_stripe_succeed, user: user_2) }
let(:balance_2) { create(:balance, created_at: 10.days.ago, user: user_2) }
before do
user_1
user_compliance_info_1
tos_agreement_1
bank_account_1
balance_1
user_2
user_compliance_info_2
tos_agreement_2
bank_account_2
balance_2
StripeMerchantAccountManager.create_account(user_2, passphrase: GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD"))
end
it "only queues the users that don't have merchant accounts" do
described_class.new.perform
expect(CreateStripeMerchantAccountWorker).to have_enqueued_sidekiq_job(user_1.id)
expect(CreateStripeMerchantAccountWorker).not_to have_enqueued_sidekiq_job(user_2.id)
end
describe "even if the merchant account has been marked as deleted" do
before do
user_2.reload.merchant_accounts.last.mark_deleted!
end
it "only queues the users that have never had a merchant account" do
described_class.new.perform
expect(CreateStripeMerchantAccountWorker).to have_enqueued_sidekiq_job(user_1.id)
expect(CreateStripeMerchantAccountWorker).not_to have_enqueued_sidekiq_job(user_2.id)
end
end
end
describe "don't queue users outside of our support stripe connect countries" do
let(:user_1) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_1) { create(:user_compliance_info, user: user_1) }
let(:tos_agreement_1) { create(:tos_agreement, user: user_1) }
let(:bank_account_1) { create(:ach_account, user: user_1) }
let(:balance_1) { create(:balance, created_at: 10.days.ago, user: user_1) }
let(:user_2) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_2) { create(:user_compliance_info, user: user_2, country: Compliance::Countries::CAN.common_name) }
let(:tos_agreement_2) { create(:tos_agreement, user: user_2) }
let(:bank_account_2) { create(:canadian_bank_account, user: user_2) }
let(:balance_2) { create(:balance, created_at: 10.days.ago, user: user_2) }
let(:user_3) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_3) { create(:user_compliance_info, user: user_3, country: Compliance::Countries::VEN.common_name) }
let(:tos_agreement_3) { create(:tos_agreement, user: user_3) }
let(:bank_account_3) { create(:canadian_bank_account, user: user_3) }
let(:balance_3) { create(:balance, created_at: 10.days.ago, user: user_3) }
before do
user_1
user_compliance_info_1
tos_agreement_1
bank_account_1
balance_1
user_2
user_compliance_info_2
tos_agreement_2
bank_account_2
balance_2
user_3
user_compliance_info_3
tos_agreement_3
bank_account_3
balance_3
end
it "only queues the users in the US and Canada" do
described_class.new.perform
expect(CreateStripeMerchantAccountWorker).to have_enqueued_sidekiq_job(user_1.id)
expect(CreateStripeMerchantAccountWorker).to have_enqueued_sidekiq_job(user_2.id)
expect(CreateStripeMerchantAccountWorker).not_to have_enqueued_sidekiq_job(user_3.id)
end
end
describe "queue users who have a bank account" do
let(:user_1) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_1) { create(:user_compliance_info, user: user_1) }
let(:tos_agreement_1) { create(:tos_agreement, user: user_1) }
let(:bank_account_1) { create(:ach_account, user: user_1) }
let(:balance_1) { create(:balance, created_at: 10.days.ago, user: user_1) }
let(:user_2) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_2) { create(:user_compliance_info, user: user_2) }
let(:tos_agreement_2) { create(:tos_agreement, user: user_2) }
let(:balance_2) { create(:balance, created_at: 10.days.ago, user: user_2) }
before do
user_1
user_compliance_info_1
tos_agreement_1
bank_account_1
balance_1
user_2
user_compliance_info_2
tos_agreement_2
balance_2
end
it "only queues the users with bank accounts" do
described_class.new.perform
expect(CreateStripeMerchantAccountWorker).to have_enqueued_sidekiq_job(user_1.id)
expect(CreateStripeMerchantAccountWorker).not_to have_enqueued_sidekiq_job(user_2.id)
end
end
describe "queue users who have agreed to the tos agreement" do
let(:user_1) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_1) { create(:user_compliance_info, user: user_1) }
let(:tos_agreement_1) { create(:tos_agreement, user: user_1) }
let(:bank_account_1) { create(:ach_account, user: user_1) }
let(:balance_1) { create(:balance, created_at: 10.days.ago, user: user_1) }
let(:user_2) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_2) { create(:user_compliance_info, user: user_2) }
let(:bank_account_2) { create(:ach_account, user: user_2) }
let(:balance_2) { create(:balance, created_at: 10.days.ago, user: user_2) }
before do
user_1
user_compliance_info_1
tos_agreement_1
bank_account_1
balance_1
user_2
user_compliance_info_2
bank_account_2
balance_2
end
it "only queues the users who have agreed to tos" do
described_class.new.perform
expect(CreateStripeMerchantAccountWorker).to have_enqueued_sidekiq_job(user_1.id)
expect(CreateStripeMerchantAccountWorker).not_to have_enqueued_sidekiq_job(user_2.id)
end
end
describe "queue users who have received a balance in the last 3 months" do
let(:user_1) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_1) { create(:user_compliance_info, user: user_1) }
let(:tos_agreement_1) { create(:tos_agreement, user: user_1) }
let(:bank_account_1) { create(:ach_account, user: user_1) }
let(:balance_1) { create(:balance, created_at: 10.days.ago, user: user_1) }
let(:user_2) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_2) { create(:user_compliance_info, user: user_2) }
let(:tos_agreement_2) { create(:tos_agreement, user: user_2) }
let(:bank_account_2) { create(:ach_account, user: user_2) }
let(:balance_2) { create(:balance, created_at: 4.months.ago, user: user_2) }
before do
user_1
user_compliance_info_1
tos_agreement_1
bank_account_1
balance_1
user_2
user_compliance_info_2
tos_agreement_2
bank_account_2
balance_2
end
it "only queues the users in the US" do
described_class.new.perform
expect(CreateStripeMerchantAccountWorker).to have_enqueued_sidekiq_job(user_1.id)
expect(CreateStripeMerchantAccountWorker).not_to have_enqueued_sidekiq_job(user_2.id)
end
end
describe "queue users who are compliant and not reviewed, and not other users" do
let(:user_1) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_1) { create(:user_compliance_info, user: user_1) }
let(:tos_agreement_1) { create(:tos_agreement, user: user_1) }
let(:bank_account_1) { create(:ach_account, user: user_1) }
let(:balance_1) { create(:balance, created_at: 10.days.ago, user: user_1) }
let(:user_2) { create(:user, user_risk_state: "suspended_for_fraud") }
let(:user_compliance_info_2) { create(:user_compliance_info, user: user_2) }
let(:tos_agreement_2) { create(:tos_agreement, user: user_2) }
let(:bank_account_2) { create(:ach_account, user: user_2) }
let(:balance_2) { create(:balance, created_at: 10.days.ago, user: user_2) }
let(:user_3) { create(:user, user_risk_state: "compliant") }
let(:user_compliance_info_3) { create(:user_compliance_info, user: user_3) }
let(:tos_agreement_3) { create(:tos_agreement, user: user_3) }
let(:bank_account_3) { create(:ach_account, user: user_3) }
let(:balance_3) { create(:balance, created_at: 10.days.ago, user: user_3) }
before do
user_1
user_compliance_info_1
tos_agreement_1
bank_account_1
balance_1
user_2
user_compliance_info_2
tos_agreement_2
bank_account_2
balance_2
user_3
user_compliance_info_3
tos_agreement_3
bank_account_3
balance_3
end
it "only queues the users in the US" do
described_class.new.perform
expect(CreateStripeMerchantAccountWorker).to have_enqueued_sidekiq_job(user_1.id)
expect(CreateStripeMerchantAccountWorker).not_to have_enqueued_sidekiq_job(user_2.id)
expect(CreateStripeMerchantAccountWorker).to have_enqueued_sidekiq_job(user_3.id)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/generate_subscribe_preview_job_spec.rb | spec/sidekiq/generate_subscribe_preview_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GenerateSubscribePreviewJob do
let(:user) { create(:user, username: "foo") }
describe "#perform" do
context "image generation works" do
before :each do
subscribe_preview = File.binread("#{Rails.root}/spec/support/fixtures/subscribe_preview.png")
allow(SubscribePreviewGeneratorService).to receive(:generate_pngs).and_return(subscribe_preview)
end
it "attaches the generated image to the user" do
expect(user.subscribe_preview).not_to be_attached
described_class.new.perform(user.id)
expect(user.reload.subscribe_preview).to be_attached
end
end
context "image generation does not work" do
before :each do
allow(SubscribePreviewGeneratorService).to receive(:generate_pngs).and_return([nil])
end
it "raises 'Subscribe Preview could not be generated'" do
expected_error = "Subscribe Preview could not be generated for user.id=#{user.id}"
expect { described_class.new.perform(user.id) }.to raise_error(expected_error)
end
end
context "error occurred" do
before :each do
@error = "Failure"
allow(SubscribePreviewGeneratorService).to receive(:generate_pngs).and_raise(@error)
end
it "propagates the error to Sidekiq" do
expect { described_class.new.perform(user.id) }.to raise_error(@error)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/expire_rental_purchases_worker_spec.rb | spec/sidekiq/expire_rental_purchases_worker_spec.rb | # frozen_string_literal: true
describe ExpireRentalPurchasesWorker do
describe "#perform" do
before do
@purchase_1 = create(:purchase, is_rental: true)
create(:url_redirect, purchase: @purchase_1, is_rental: true, created_at: 32.days.ago)
end
it "updates only rental purchases" do
purchase_2 = create(:purchase, is_rental: false)
create(:url_redirect, purchase: purchase_2, is_rental: true, created_at: 32.days.ago)
described_class.new.perform
expect(@purchase_1.reload.rental_expired).to eq(true)
expect(purchase_2.reload.rental_expired).to eq(nil)
end
it "updates only rental purchases with rental url redirects past expiry dates" do
purchase_2 = create(:purchase, is_rental: true)
purchase_3 = create(:purchase, is_rental: true)
purchase_4 = create(:purchase, is_rental: true)
create(:url_redirect, purchase: purchase_2, is_rental: true, created_at: 20.days.ago)
create(:url_redirect, purchase: purchase_3, is_rental: true, rental_first_viewed_at: 80.hours.ago)
create(:url_redirect, purchase: purchase_4, is_rental: true, rental_first_viewed_at: 50.hours.ago)
described_class.new.perform
expect(@purchase_1.reload.rental_expired).to eq(true)
expect(purchase_2.reload.rental_expired).to eq(false)
expect(purchase_3.reload.rental_expired).to eq(true)
expect(purchase_4.reload.rental_expired).to eq(false)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/custom_domains_verification_worker_spec.rb | spec/sidekiq/custom_domains_verification_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CustomDomainsVerificationWorker do
let!(:custom_domain_one) { create(:custom_domain) }
let!(:custom_domain_two) { create(:custom_domain, failed_verification_attempts_count: 3) }
let!(:custom_domain_three) { create(:custom_domain, state: "verified") }
let!(:custom_domain_four) { create(:custom_domain, state: "verified", deleted_at: 2.days.ago) }
let!(:custom_domain_five) { create(:custom_domain, failed_verification_attempts_count: 2) }
it "verifies every non-deleted domain in its own background job" do
described_class.new.perform
expect(CustomDomainVerificationWorker).to have_enqueued_sidekiq_job(custom_domain_one.id)
expect(CustomDomainVerificationWorker).to_not have_enqueued_sidekiq_job(custom_domain_two.id)
expect(CustomDomainVerificationWorker).to have_enqueued_sidekiq_job(custom_domain_three.id)
expect(CustomDomainVerificationWorker).to_not have_enqueued_sidekiq_job(custom_domain_four.id)
expect(CustomDomainVerificationWorker).to have_enqueued_sidekiq_job(custom_domain_five.id)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/handle_sns_mediaconvert_event_worker_spec.rb | spec/sidekiq/handle_sns_mediaconvert_event_worker_spec.rb | # frozen_string_literal: false
require "spec_helper"
describe HandleSnsMediaconvertEventWorker do
let(:notification) do
{
"Type" => "Notification",
"Message" => {
"detail" => {
"jobId" => "abcd",
"status" => "COMPLETE",
"outputGroupDetails" => [
"playlistFilePaths" => [
"s3://#{S3_BUCKET}/path/to/playlist/file.m3u8"
]
]
}
}.to_json
}
end
let(:error_notification) do
{
"Type" => "Notification",
"Message" => {
"detail" => {
"jobId" => "abcd",
"status" => "ERROR",
}
}.to_json
}
end
describe "#perform" do
context "when transcoded_video object doesn't exist" do
it "returns nil" do
expect(described_class.new.perform(notification)).to be_nil
expect(TranscodeVideoForStreamingWorker.jobs.size).to eq(0)
expect(HandleSnsTranscoderEventWorker.jobs.size).to eq(0)
end
end
context "when MediaConvert fails to transcode the video" do
before do
@transcoded_video = create(:transcoded_video, job_id: "abcd", state: "processing")
end
it "deletes the transcoded_video object" do
expect do
described_class.new.perform(error_notification)
end.to change { TranscodedVideo.count }.by(-1)
expect { @transcoded_video.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
it "enqueues a job to transcode the video using ETS" do
described_class.new.perform(error_notification)
ets_transcoder = TranscodeVideoForStreamingWorker::ETS
expect(TranscodeVideoForStreamingWorker).to have_enqueued_sidekiq_job(@transcoded_video.streamable.id, ProductFile.name, ets_transcoder)
expect(HandleSnsTranscoderEventWorker.jobs.size).to eq(0)
end
end
context "when MediaConvert successfully transcodes the video" do
before do
@transcoded_video = create(:transcoded_video, job_id: "abcd", state: "processing")
@transcoded_video_2 = create(:transcoded_video, job_id: "efgh", state: "processing", original_video_key: @transcoded_video.original_video_key)
end
it "updates the transcoded_video object" do
described_class.new.perform(notification)
@transcoded_video.reload
expect(@transcoded_video.state).to eq "completed"
expect(@transcoded_video.transcoded_video_key).to eq "path/to/playlist/file.m3u8"
@transcoded_video_2.reload
expect(@transcoded_video_2.state).to eq "completed"
expect(@transcoded_video_2.transcoded_video_key).to eq "path/to/playlist/file.m3u8"
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/deactivate_integrations_worker_spec.rb | spec/sidekiq/deactivate_integrations_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DeactivateIntegrationsWorker do
it "calls #deactivate for all integrations" do
purchase = create(:free_purchase)
[Integrations::CircleIntegrationService, Integrations::DiscordIntegrationService].each do |integration_service|
expect_any_instance_of(integration_service).to receive(:deactivate).with(purchase)
end
described_class.new.perform(purchase.id)
end
it "errors out if purchase is not found" do
expect { described_class.new.perform(1) }.to raise_error(ActiveRecord::RecordNotFound).with_message("Couldn't find Purchase with 'id'=1")
[Integrations::CircleIntegrationService, Integrations::DiscordIntegrationService].each do |integration_service|
expect_any_instance_of(integration_service).to_not receive(:deactivate)
end
end
it "deactivates integrations for other purchases on the same subscription" do
product = create(:membership_product)
discord_integration = create(:discord_integration)
product.product_integrations.create!(integration: discord_integration)
purchase = create(:membership_purchase, link: product, is_gift_sender_purchase: true)
giftee_purchase = create(:purchase,
link: product,
subscription: purchase.subscription,
is_original_subscription_purchase: false,
is_gift_receiver_purchase: true,
purchase_state: "gift_receiver_purchase_successful",
price_cents: 0)
create(:gift, gifter_purchase: purchase, giftee_purchase:)
PurchaseIntegration.create!(purchase: giftee_purchase,
integration: discord_integration,
discord_user_id: "disc-123")
circle_service_instance = instance_double(Integrations::CircleIntegrationService)
discord_service_instance = instance_double(Integrations::DiscordIntegrationService)
allow(Integrations::CircleIntegrationService).to receive(:new).and_return(circle_service_instance)
allow(Integrations::DiscordIntegrationService).to receive(:new).and_return(discord_service_instance)
expect(circle_service_instance).to receive(:deactivate).with(purchase)
expect(circle_service_instance).to receive(:deactivate).with(giftee_purchase)
expect(discord_service_instance).to receive(:deactivate).with(purchase)
expect(discord_service_instance).to receive(:deactivate).with(giftee_purchase)
described_class.new.perform(purchase.id)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/delete_product_files_worker_spec.rb | spec/sidekiq/delete_product_files_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DeleteProductFilesWorker do
before do
stub_const("PUBLIC_STORAGE_CDN_S3_PROXY_HOST", "#{AWS_S3_ENDPOINT}/#{PUBLIC_STORAGE_S3_BUCKET}")
@image1 = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "smilie.png")
@image2 = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("test.jpg"), filename: "test.jpg")
@image3 = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("test.jpeg"), filename: "test.jpeg")
@product = create(:product, description: "<img src=\"#{@image1.url}\" />")
@product_file_1 = create(:product_file, link: @product)
@product_file_2 = create(:product_file, link: @product)
create(:rich_content, entity: @product, description: [{ "type" => "image", "attrs" => { "src" => @image2.url, "link" => nil, class: nil } }])
@product.delete!
end
describe "#perform" do
it "deletes product files" do
freeze_time do
described_class.new.perform(@product.id)
end
expect([@product_file_1.reload.deleted?, @product_file_2.reload.deleted?]).to eq [true, true]
expect(@product.product_files.alive.count).to eq 0
end
context "when there are successful purchases" do
before do
create(:purchase, link: @product, seller: @product.user)
index_model_records(Purchase)
end
it "does not delete the product files" do
freeze_time do
described_class.new.perform(@product.id)
end
expect([@product_file_1.reload.deleted?, @product_file_2.reload.deleted?]).to eq [false, false]
expect(@product.product_files.alive.count).to eq 2
end
end
it "does not delete files if the product is not deleted" do
@product.mark_undeleted!
described_class.new.perform(@product.id)
expect([@product_file_1.reload.deleted?, @product_file_2.reload.deleted?]).to eq [false, false]
expect(@product.product_files.alive.count).to eq 2
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/cache_unreviewed_users_data_worker_spec.rb | spec/sidekiq/cache_unreviewed_users_data_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CacheUnreviewedUsersDataWorker do
describe "#perform" do
it "caches unreviewed users data via the service" do
user = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago)
create(:balance, user:, amount_cents: 5000)
described_class.new.perform
cached_data = Admin::UnreviewedUsersService.cached_users_data
expect(cached_data[:users].size).to eq(1)
expect(cached_data[:users].first[:id]).to eq(user.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/generate_community_chat_recap_job_spec.rb | spec/sidekiq/generate_community_chat_recap_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe GenerateCommunityChatRecapJob do
subject(:job) { described_class.new }
describe "#perform" do
let(:recap_run) { create(:community_chat_recap_run) }
let(:community) { create(:community) }
let(:recap) { create(:community_chat_recap, community:, community_chat_recap_run: recap_run) }
it "generates the recap" do
expect_any_instance_of(CommunityChatRecapGeneratorService).to receive(:process).and_call_original
expect do
job.perform(recap.id)
end.to change { recap.reload.status }.from("pending").to("finished")
end
it "marks the corresponding recap run as finished when all associated recaps are finished" do
expect_any_instance_of(CommunityChatRecapRun).to receive(:check_if_finished!).and_call_original
expect do
job.perform(recap.id)
end.to change { recap_run.reload.finished? }.from(false).to(true)
expect(recap_run.finished_at).to be_present
expect(recap_run.notified_at).to be_present
end
it "does not mark the corresponding recap run as finished when not all associated recaps are finished" do
recap2 = create(:community_chat_recap, community: create(:community), community_chat_recap_run: recap_run)
expect do
job.perform(recap.id)
end.not_to change { recap_run.reload.finished? }
expect(recap.reload).to be_status_finished
expect(recap2.reload).to be_status_pending
expect(recap_run.finished_at).to be_nil
expect(recap_run.notified_at).to be_nil
end
it "marks the corresponding recap run as finished when all associated recaps are either finished or failed" do
recap2 = create(:community_chat_recap, community: create(:community), community_chat_recap_run: recap_run, status: "failed")
expect do
job.perform(recap.id)
end.to change { recap_run.reload.finished? }.from(false).to(true)
expect(recap.reload).to be_status_finished
expect(recap2.reload).to be_status_failed
expect(recap_run.finished_at).to be_present
expect(recap_run.notified_at).to be_present
end
end
describe "sidekiq_retries_exhausted", :sidekiq_inline do
let(:recap_run) { create(:community_chat_recap_run) }
let(:community) { create(:community) }
let(:recap) { create(:community_chat_recap, community:, community_chat_recap_run: recap_run) }
let(:error_message) { "OpenAI API error" }
let(:job_info) { { "class" => "GenerateCommunityChatRecapJob", "args" => [recap.id] } }
it "updates the failing recap status to failed" do
expect_any_instance_of(CommunityChatRecapRun).to receive(:check_if_finished!).and_call_original
expect do
described_class::FailureHandler.call(job_info, StandardError.new(error_message))
end.to change { recap.reload.status }.from("pending").to("failed")
expect(recap).to be_status_failed
expect(recap.error_message).to eq(error_message)
expect(recap_run.reload).to be_finished
expect(recap_run.notified_at).to be_present
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/unblock_object_worker_spec.rb | spec/sidekiq/unblock_object_worker_spec.rb | # frozen_string_literal: true
describe UnblockObjectWorker do
describe "#perform" do
let(:email_domain) { "example.com" }
it "unblocks email domains" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], email_domain, nil)
expect(BlockedObject.active.email_domain.count).to eq(1)
described_class.new.perform(email_domain)
expect(BlockedObject.active.email_domain.count).to eq(0)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/export_payout_data_spec.rb | spec/sidekiq/export_payout_data_spec.rb | # frozen_string_literal: true
describe ExportPayoutData do
describe "#perform" do
let(:seller) { create(:named_seller) }
let(:payment1) { create(:payment, user: seller, created_at: Time.zone.now) }
let(:payment2) { create(:payment, user: seller, created_at: 7.days.ago) }
let(:payment_ids) { [payment1.id, payment2.id] }
let(:csv_data1) { "Payment1,CSV,data\n" }
let(:csv_data2) { "Payment2,CSV,data\n" }
before do
allow(Exports::Payouts::Csv).to receive(:new).with(payment_id: payment1.id).and_return(double(perform: csv_data1))
allow(Exports::Payouts::Csv).to receive(:new).with(payment_id: payment2.id).and_return(double(perform: csv_data2))
end
it "generates CSV files for each payment" do
expect(Exports::Payouts::Csv).to receive(:new).with(payment_id: payment1.id)
expect(Exports::Payouts::Csv).to receive(:new).with(payment_id: payment2.id)
ExportPayoutData.new.perform(payment_ids, seller.id)
end
it "sends an email with a zip file when multiple payments are provided" do
mail_double = instance_double(ActionMailer::MessageDelivery)
expect(mail_double).to receive(:deliver_now)
expect(ContactingCreatorMailer).to receive(:payout_data) do |filename, extension, tempfile, recipient_id|
expect(filename).to eq("Payouts.zip")
expect(extension).to eq("zip")
expect(tempfile.size).not_to eq(0)
expect(recipient_id).to eq(seller.id)
Zip::File.open(tempfile.path) do |zip|
expect(zip.entries.map(&:name)).to contain_exactly(
"Payout of #{payment1.created_at.to_date}.csv",
"Payout of #{payment2.created_at.to_date}.csv"
)
expect(zip.read("Payout of #{payment1.created_at.to_date}.csv")).to eq(csv_data1)
expect(zip.read("Payout of #{payment2.created_at.to_date}.csv")).to eq(csv_data2)
end
mail_double
end
ExportPayoutData.new.perform(payment_ids, seller.id)
end
it "sends an email with a single CSV file when only one payment is provided" do
mail_double = instance_double(ActionMailer::MessageDelivery)
expect(mail_double).to receive(:deliver_now)
expect(ContactingCreatorMailer).to receive(:payout_data) do |filename, extension, tempfile, recipient_id|
expect(filename).to eq("Payout of #{payment1.created_at.to_date}.csv")
expect(extension).to eq("csv")
expect(tempfile.size).not_to eq(0)
expect(recipient_id).to eq(seller.id)
expect(tempfile.read).to eq(csv_data1)
mail_double
end
ExportPayoutData.new.perform([payment1.id], seller.id)
end
it "handles a single ID passed as a non-array" do
mail_double = instance_double(ActionMailer::MessageDelivery)
expect(mail_double).to receive(:deliver_now)
expect(ContactingCreatorMailer).to receive(:payout_data) do |filename, extension, tempfile, recipient_id|
expect(filename).to eq("Payout of #{payment1.created_at.to_date}.csv")
expect(extension).to eq("csv")
expect(tempfile.size).not_to eq(0)
expect(recipient_id).to eq(seller.id)
mail_double
end
ExportPayoutData.new.perform(payment1.id, seller.id)
end
it "does nothing if no payments are found" do
expect(ContactingCreatorMailer).not_to receive(:payout_data)
ExportPayoutData.new.perform([999999], seller.id)
end
it "does nothing if payments are from different sellers" do
another_seller = create(:user)
payment3 = create(:payment, user: another_seller)
allow(Exports::Payouts::Csv).to receive(:new).with(payment_id: payment3.id).and_return(double(perform: "Payment3,CSV,data\n"))
expect(ContactingCreatorMailer).not_to receive(:payout_data)
ExportPayoutData.new.perform([payment1.id, payment3.id], seller.id)
end
context "with duplicate filenames" do
let(:payment1) { create(:payment, user: seller, created_at: Time.zone.now) }
let(:payment2) { create(:payment, user: seller, created_at: Time.zone.now) }
it "creates unique filenames in the zip archive" do
mail_double = instance_double(ActionMailer::MessageDelivery)
expect(mail_double).to receive(:deliver_now)
expect(ContactingCreatorMailer).to receive(:payout_data) do |filename, extension, tempfile, recipient_id|
expect(filename).to eq("Payouts.zip")
expect(extension).to eq("zip")
expect(tempfile.size).not_to eq(0)
Zip::File.open(tempfile.path) do |zip|
expect(zip.entries.map(&:name)).to contain_exactly(
"Payout of #{payment1.created_at.to_date}.csv",
"Payout of #{payment1.created_at.to_date} (1).csv",
)
end
mail_double
end
ExportPayoutData.new.perform(payment_ids, seller.id)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/compile_gumroad_daily_analytics_job_spec.rb | spec/sidekiq/compile_gumroad_daily_analytics_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CompileGumroadDailyAnalyticsJob do
it "compiles analytics for the refresh period" do
stub_const("CompileGumroadDailyAnalyticsJob::REFRESH_PERIOD", 5.days)
allow(Date).to receive(:today).and_return(Date.new(2023, 1, 15))
create :purchase, created_at: Time.utc(2023, 1, 10, 14, 0), price_cents: 3000
create :purchase, created_at: Time.utc(2023, 1, 10, 14, 30), price_cents: 3000
create :purchase, created_at: Time.utc(2023, 1, 10, 19, 0), price_cents: 2000, was_product_recommended: true
create :purchase, created_at: Time.utc(2023, 1, 10, 19, 0), price_cents: 1500, was_product_recommended: true
create :service_charge, created_at: Time.utc(2023, 1, 10, 20, 0), charge_cents: 25
create :service_charge, created_at: Time.utc(2023, 1, 10, 21, 0), charge_cents: 25
create :purchase, created_at: Time.utc(2023, 1, 14, 10, 0), price_cents: 5000
create :purchase, created_at: Time.utc(2023, 1, 14, 12, 0), price_cents: 10000, was_product_recommended: true
create :gumroad_daily_analytic, period_ended_at: Time.utc(2023, 1, 14).end_of_day, gumroad_price_cents: 999
Purchase.all.map { |p| p.update!(fee_cents: p.price_cents / 10) } # Force fee to be 10% of purchase amount
CompileGumroadDailyAnalyticsJob.new.perform
analytic_1 = GumroadDailyAnalytic.find_by(period_ended_at: Time.utc(2023, 1, 10).end_of_day)
analytic_2 = GumroadDailyAnalytic.find_by(period_ended_at: Time.utc(2023, 1, 14).end_of_day)
expect(GumroadDailyAnalytic.all.size).to eq(6) # The refresh period (5 days) + today = 6 days
expect(analytic_1.gumroad_price_cents).to eq(9500)
expect(analytic_1.gumroad_fee_cents).to eq(1000)
expect(analytic_1.creators_with_sales).to eq(4)
expect(analytic_1.gumroad_discover_price_cents).to eq(3500)
expect(analytic_2.gumroad_price_cents).to eq(15000)
expect(analytic_2.gumroad_fee_cents).to eq(1500)
expect(analytic_2.creators_with_sales).to eq(2)
expect(analytic_2.gumroad_discover_price_cents).to eq(10000)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/end_subscription_worker_spec.rb | spec/sidekiq/end_subscription_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe EndSubscriptionWorker, :vcr do
before do
@product = create(:subscription_product, user: create(:user), duration_in_months: 1)
@subscription = create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: @product, charge_occurrence_count: 1)
@purchase = create(:purchase, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription)
end
it "does not call `end_subscription!` on test_subscriptions" do
@product.user.credit_card = create(:credit_card)
@product.user.save!
subscription = create(:subscription, user: @product.user, link: @product)
subscription.is_test_subscription = true
subscription.save!
create(:test_purchase, seller: @product.user, purchaser: @product.user, link: @product, price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription:)
expect_any_instance_of(Subscription).to_not receive(:end_subscription!)
described_class.new.perform(subscription.id)
end
it "calls `end_subscription!` on subscriptions" do
expect_any_instance_of(Subscription).to receive(:end_subscription!)
described_class.new.perform(@subscription.id)
end
describe "subscription is cancelled" do
before do
@subscription.update_attribute(:cancelled_at, Time.current)
end
it "calls `end_subscription!` on subscriptions" do
expect_any_instance_of(Subscription).to_not receive(:end_subscription!)
described_class.new.perform(@subscription.id)
end
end
describe "subscription has failed" do
before do
@subscription.update_attribute(:failed_at, Time.current)
end
it "calls `end_subscription!` on subscriptions" do
expect_any_instance_of(Subscription).to_not receive(:end_subscription!)
described_class.new.perform(@subscription.id)
end
end
describe "subscription has ended" do
before do
@subscription.update_attribute(:ended_at, Time.current)
end
it "calls `end_subscription!` on subscriptions" do
expect_any_instance_of(Subscription).to_not receive(:end_subscription!)
described_class.new.perform(@subscription.id)
end
end
describe "subscription hasn't had enough successful charges" do
before do
@subscription.update_attribute(:charge_occurrence_count, 2)
end
it "calls `end_subscription!` on subscriptions" do
expect_any_instance_of(Subscription).to_not receive(:end_subscription!)
described_class.new.perform(@subscription.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_deferred_refunds_report_worker_spec.rb | spec/sidekiq/send_deferred_refunds_report_worker_spec.rb | # frozen_string_literal: true
describe SendDeferredRefundsReportWorker do
describe "perform" do
before do
@last_month = Time.current.last_month
@mailer_double = double("mailer")
allow(AccountingMailer).to receive(:deferred_refunds_report).with(@last_month.month, @last_month.year).and_return(@mailer_double)
allow(@mailer_double).to receive(:deliver_now)
allow(Rails.env).to receive(:production?).and_return(true)
end
it "enqueues AccountingMailer.deferred_refunds_report" do
expect(AccountingMailer).to receive(:deferred_refunds_report).with(@last_month.month, @last_month.year).and_return(@mailer_double)
allow(@mailer_double).to receive(:deliver_now)
SendDeferredRefundsReportWorker.new.perform
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_paypal_topup_notification_job_spec.rb | spec/sidekiq/send_paypal_topup_notification_job_spec.rb | # frozen_string_literal: true
describe SendPaypalTopupNotificationJob do
describe "#perform" do
before do
seller = create(:user, unpaid_balance_cents: 152_279_86)
seller2 = create(:user, unpaid_balance_cents: 215_145_32)
create(:payment, state: "completed", txn_id: "txn_id_1", processor_fee_cents: 1, user: seller)
create(:payment, state: "completed", txn_id: "txn_id_2", processor_fee_cents: 2, user: seller2)
allow(Rails.env).to receive(:production?).and_return(true)
allow(PaypalPayoutProcessor).to receive(:current_paypal_balance_cents).and_return(125_000_00)
end
it "sends a notification to slack with the required topup amount" do
allow(PaypalPayoutProcessor).to receive(:topup_amount_in_transit).and_return(0)
notification_msg = "PayPal balance needs to be $367,425.18 by Friday to payout all creators.\n"\
"Current PayPal balance is $125,000.\n"\
"A top-up of $242,425.18 is needed."
described_class.new.perform
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "PayPal Top-up", notification_msg, "red")
end
it "includes details of payout amount in transit in the slack notification" do
allow(PaypalPayoutProcessor).to receive(:topup_amount_in_transit).and_return(100_000)
notification_msg = "PayPal balance needs to be $367,425.18 by Friday to payout all creators.\n"\
"Current PayPal balance is $125,000.\n"\
"Top-up amount in transit is $100,000.\n"\
"A top-up of $142,425.18 is needed."
described_class.new.perform
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "PayPal Top-up", notification_msg, "red")
end
it "sends no more topup required green notification if there's sufficient amount in PayPal" do
allow(PaypalPayoutProcessor).to receive(:topup_amount_in_transit).and_return(300_000)
notification_msg = "PayPal balance needs to be $367,425.18 by Friday to payout all creators.\n"\
"Current PayPal balance is $125,000.\n"\
"Top-up amount in transit is $300,000.\n"\
"No more top-up required."
described_class.new.perform
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "PayPal Top-up", notification_msg, "green")
end
context "when notify_only_if_topup_needed is true" do
it "sends notification when topup is needed" do
allow(PaypalPayoutProcessor).to receive(:topup_amount_in_transit).and_return(0)
notification_msg = "PayPal balance needs to be $367,425.18 by Friday to payout all creators.\n"\
"Current PayPal balance is $125,000.\n"\
"A top-up of $242,425.18 is needed."
described_class.new.perform(true)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "PayPal Top-up", notification_msg, "red")
end
it "does not send notification when topup is not needed" do
allow(PaypalPayoutProcessor).to receive(:topup_amount_in_transit).and_return(300_000)
described_class.new.perform(true)
expect(SlackMessageWorker).not_to have_enqueued_sidekiq_job
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/calculate_sale_numbers_worker_spec.rb | spec/sidekiq/calculate_sale_numbers_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CalculateSaleNumbersWorker, :vcr do
describe "#perform" do
it "sets the correct values for `total_made` and `number_of_creators` in Redis" do
create(:failed_purchase, link: create(:product, price_cents: 99))
create(:refunded_purchase, link: create(:product, price_cents: 1099))
create(:free_purchase)
create(:disputed_purchase, link: create(:product, price_cents: 2099))
create(:disputed_purchase, chargeback_reversed: true, link: create(:product, price_cents: 3099))
create(:purchase, link: create(:product, price_cents: 4099))
create(:purchase, link: create(:product, price_cents: 5099))
index_model_records(Purchase)
described_class.new.perform
expected_total_made_in_usd = (3099 + 4099 + 5099) / 100
expect($redis.get(RedisKey.number_of_creators)).to eq("3")
expect($redis.get(RedisKey.total_made)).to eq(expected_total_made_in_usd.to_s)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/million_dollar_milestone_check_worker_spec.rb | spec/sidekiq/million_dollar_milestone_check_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe MillionDollarMilestoneCheckWorker do
describe "#perform" do
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
it "sends Slack notification if million dollar milestone is reached with no compliance info" do
allow_any_instance_of(User).to receive(:gross_sales_cents_total_as_seller).and_return(1_000_000_00)
allow_any_instance_of(User).to receive(:alive_user_compliance_info).and_return(nil)
create(:purchase, seller:, link: product, created_at: 15.days.ago)
described_class.new.perform
message = "<#{seller.profile_url}|#{seller.name_or_username}> has crossed $1M in earnings :tada:\n" \
"• Name: #{seller.name}\n" \
"• Username: #{seller.username}\n" \
"• Email: #{seller.email}\n"
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("awards", "Gumroad Awards", message, "hotpink")
end
it "sends Slack notification if million dollar milestone is reached with compliance info" do
allow_any_instance_of(User).to receive(:gross_sales_cents_total_as_seller).and_return(1_000_000_00)
compliance_info = instance_double(
"UserComplianceInfo",
first_name: "John",
last_name: "Doe",
street_address: "123 Main St",
city: "San Francisco",
state: "CA",
zip_code: "94105",
country: "USA"
)
allow_any_instance_of(User).to receive(:alive_user_compliance_info).and_return(compliance_info)
create(:purchase, seller:, link: product, created_at: 15.days.ago)
described_class.new.perform
message = "<#{seller.profile_url}|#{seller.name_or_username}> has crossed $1M in earnings :tada:\n" \
"• Name: #{seller.name}\n" \
"• Username: #{seller.username}\n" \
"• Email: #{seller.email}\n" \
"• First name: John\n" \
"• Last name: Doe\n" \
"• Street address: 123 Main St\n" \
"• City: San Francisco\n" \
"• State: CA\n" \
"• ZIP code: 94105\n" \
"• Country: USA"
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("awards", "Gumroad Awards", message, "hotpink")
end
it "does not send Slack notification if million dollar milestone is not reached" do
allow_any_instance_of(User).to receive(:gross_sales_cents_total_as_seller).and_return(999_999)
create(:purchase, seller:, link: product, created_at: 15.days.ago)
described_class.new.perform
expect(SlackMessageWorker).not_to have_enqueued_sidekiq_job("awards", "Gumroad Awards", anything, "hotpink")
end
it "does not send Slack notification if million dollar milestone is reached but announcement has already been " \
"sent" do
seller.update!(million_dollar_announcement_sent: true)
allow_any_instance_of(User).to receive(:gross_sales_cents_total_as_seller).and_return(1_000_000_00)
create(:purchase, seller:, link: product, created_at: 15.days.ago)
described_class.new.perform
expect(SlackMessageWorker).not_to have_enqueued_sidekiq_job("awards", "Gumroad Awards", anything, "hotpink")
end
it "does not include users who have not made a sale in the last 3 weeks" do
allow_any_instance_of(User).to receive(:gross_sales_cents_total_as_seller).and_return(1_000_000_00)
create(:purchase, seller:, link: product, created_at: 4.weeks.ago)
described_class.new.perform
expect(SlackMessageWorker).not_to have_enqueued_sidekiq_job("awards", "Gumroad Awards", anything, "hotpink")
end
it "does not include users whose purchases are within the last 2 weeks" do
allow_any_instance_of(User).to receive(:gross_sales_cents_total_as_seller).and_return(1_000_000_00)
create(:purchase, seller:, link: product, created_at: 1.weeks.ago)
described_class.new.perform
expect(SlackMessageWorker).not_to have_enqueued_sidekiq_job("awards", "Gumroad Awards", anything, "hotpink")
end
it "marks seller as announcement sent" do
allow_any_instance_of(User).to receive(:gross_sales_cents_total_as_seller).and_return(1_000_000_00)
create(:purchase, seller:, link: product, created_at: 15.days.ago)
described_class.new.perform
expect(seller.reload.million_dollar_announcement_sent).to eq(true)
end
it "sends Bugsnag notification if announcement cannot be marked as sent" do
allow_any_instance_of(User).to receive(:gross_sales_cents_total_as_seller).and_return(1_000_000_00)
allow_any_instance_of(User).to receive(:update).and_return(false)
create(:purchase, seller:, link: product, created_at: 15.days.ago)
expect(Bugsnag).to receive(:notify).with("Failed to send Slack notification for million dollar milestone", user_id: seller.id)
described_class.new.perform
end
it "carries on with other users if announcement cannot be marked as sent for a user" do
additional_seller = create(:user)
additional_product = create(:product, user: additional_seller)
create(:purchase, seller:, link: product, created_at: 15.days.ago)
create(:purchase, seller: additional_seller, link: additional_product, created_at: 15.days.ago)
allow_any_instance_of(User).to receive(:gross_sales_cents_total_as_seller).and_return(1_000_000_00)
allow_any_instance_of(User).to receive(:update).and_return(false)
expect(Bugsnag).to receive(:notify).with("Failed to send Slack notification for million dollar milestone", user_id: anything).twice
described_class.new.perform
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_post_blast_emails_job_spec.rb | spec/sidekiq/send_post_blast_emails_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SendPostBlastEmailsJob, :freeze_time do
include Rails.application.routes.url_helpers, ActionView::Helpers::SanitizeHelper
_routes.default_url_options = Rails.application.config.action_mailer.default_url_options
before do
@seller = create(:named_user)
# Since secure_external_id changes on each call, we need to mock it to get a consistent value
allow_any_instance_of(Purchase).to receive(:secure_external_id) do |purchase, scope:|
"sample-secure-id-#{scope}-#{purchase.id}"
end
end
let(:basic_post_with_audience) do
post = create(:audience_post, :published, seller: @seller)
create(:active_follower, user: @seller)
post
end
describe "#perform" do
it "ignores deleted posts" do
basic_post_with_audience.mark_deleted!
blast = create(:blast, :just_requested, post: basic_post_with_audience)
described_class.new.perform(blast.id)
expect_sent_count 0
expect(blast.reload.started_at).to be_blank
expect(blast.completed_at).to be_blank
end
it "ignores unpublished posts" do
basic_post_with_audience.update!(published_at: nil)
blast = create(:blast, :just_requested, post: basic_post_with_audience)
described_class.new.perform(blast.id)
expect_sent_count 0
expect(blast.reload.started_at).to be_blank
expect(blast.completed_at).to be_blank
end
it "ignores posts where send_emails is false" do
basic_post_with_audience.update!(published_at: nil)
blast = create(:blast, :just_requested, post: basic_post_with_audience)
described_class.new.perform(blast.id)
expect_sent_count 0
expect(blast.reload.started_at).to be_blank
expect(blast.completed_at).to be_blank
end
it "ignores completed blasts" do
blast = create(:blast, post: basic_post_with_audience, completed_at: Time.current)
described_class.new.perform(blast.id)
expect_sent_count 0
end
it "records when blast started processing" do
blast = create(:blast, :just_requested, post: basic_post_with_audience)
described_class.new.perform(blast.id)
expect(blast.reload.started_at).to be_present
end
it "does not email the same recipients twice, when the post has been published twice" do
blast = create(:blast, :just_requested, post: basic_post_with_audience)
described_class.new.perform(blast.id)
expect_sent_count 1
recipient_email = basic_post_with_audience.seller.followers.first.email
expect(PostSendgridApi.mails.keys).to eq([recipient_email])
PostSendgridApi.mails.clear
blast_2 = create(:blast, :just_requested, post: basic_post_with_audience)
described_class.new.perform(blast_2.id)
expect_sent_count 0
end
context "for different post types" do
before do
@products = []
@products << create(:product, user: @seller, name: "Product one")
@products << create(:product, user: @seller, name: "Product two")
category = create(:variant_category, link: @products[0])
@variants = create_list(:variant, 2, variant_category: category)
@products << create(:product, :is_subscription, user: @seller, name: "Product three")
@sales = []
@sales << create(:purchase, link: @products[0])
@sales << create(:purchase, link: @products[1], email: @sales[0].email)
@sales << create(:purchase, link: @products[0])
@sales << create(:purchase, link: @products[1], variant_attributes: [@variants[0]])
@sales << create(:purchase, link: @products[1], variant_attributes: [@variants[1]])
@sales << create(:membership_purchase, link: @products[2])
@followers = []
@followers << create(:active_follower, user: @seller)
@followers << create(:active_follower, user: @seller, email: @sales[0].email)
@affiliates = []
@affiliates << create(:direct_affiliate, seller: @seller, send_posts: true)
@affiliates[0].products << @products[0]
@affiliates[0].products << @products[1]
# Basic check for working recipient filtering.
# The details of it are tested in the Installment model specs.
create(:deleted_follower, user: @seller)
create(:purchase, link: @products[0], can_contact: false)
create(:direct_affiliate, seller: @seller, send_posts: false).products << @products[0]
create(:membership_purchase, email: @sales[5].email, link: @products[2], subscription: @sales[5].subscription, is_original_subscription_purchase: false)
end
it "when product_type? is true, it sends the expected emails" do
post = create(:product_post, :published, link: @products[0], bought_products: [@products[0].unique_permalink])
blast = create(:blast, :just_requested, post:)
expect do
described_class.new.perform(blast.id)
end.to change { UrlRedirect.count }.by(2)
expect_sent_count 2
expect_sent_email @sales[0].email, content_match: [
/because you've purchased.*#{post.purchase_url_redirect(@sales[0]).download_page_url}.*#{@products[0].name}/,
/#{unsubscribe_purchase_url(@sales[0].secure_external_id(scope: "unsubscribe"))}.*Unsubscribe/
]
expect_sent_email @sales[2].email, content_match: [
/because you've purchased.*#{post.purchase_url_redirect(@sales[2]).download_page_url}.*#{@products[0].name}/,
/#{unsubscribe_purchase_url(@sales[2].secure_external_id(scope: "unsubscribe"))}.*Unsubscribe/
]
end
it "when product_type? is true and not_bought_products filter is present it sends the expected emails" do
post = create(:product_post, :published, link: @products[0], not_bought_products: [@products[0].unique_permalink])
blast = create(:blast, :just_requested, post:)
expect do
described_class.new.perform(blast.id)
end.to change { UrlRedirect.count }.by(3)
expect_sent_count 3
expect_sent_email @sales[3].email, content_match: [
/because you've purchased.*#{post.purchase_url_redirect(@sales[3]).download_page_url}.*#{@products[1].name}/,
/#{unsubscribe_purchase_url(@sales[3].secure_external_id(scope: "unsubscribe"))}.*Unsubscribe/
]
expect_sent_email @sales[4].email, content_match: [
/because you've purchased.*#{post.purchase_url_redirect(@sales[4]).download_page_url}.*#{@products[1].name}/,
/#{unsubscribe_purchase_url(@sales[4].secure_external_id(scope: "unsubscribe"))}.*Unsubscribe/
]
expect_sent_email @sales[5].email, content_match: [
/because you've purchased.*#{post.purchase_url_redirect(@sales[5]).download_page_url}.*#{@products[2].name}/,
/#{unsubscribe_purchase_url(@sales[5].secure_external_id(scope: "unsubscribe"))}.*Unsubscribe/
]
end
it "when variant_type? is true, it sends the expected emails" do
post = create(:variant_post, :published, link: @products[1], base_variant: @variants[0], bought_variants: [@variants[0].external_id])
blast = create(:blast, :just_requested, post:)
expect do
described_class.new.perform(blast.id)
end.to change { UrlRedirect.count }.by(1)
expect_sent_count 1
expect_sent_email @sales[3].email, content_match: [
/because you've purchased.*#{post.purchase_url_redirect(@sales[3]).download_page_url}.*#{@products[1].name}/,
/#{unsubscribe_purchase_url(@sales[3].secure_external_id(scope: "unsubscribe"))}.*Unsubscribe/
]
end
it "when seller_type? is true, it sends the expected emails" do
post = create(:seller_post, :published, seller: @seller)
blast = create(:blast, :just_requested, post:)
described_class.new.perform(blast.id)
expect_sent_count 5
[1, 2, 3, 4, 5].each do |sale_index|
expect_sent_email @sales[sale_index].email, content_match: [
/because you've purchased a product from #{@seller.name}/,
/#{unsubscribe_purchase_url(@sales[sale_index].secure_external_id(scope: "unsubscribe"))}.*Unsubscribe/
]
end
end
it "when follower_type? is true, it sends the expected emails" do
post = create(:follower_post, :published, seller: @seller)
blast = create(:blast, :just_requested, post:)
described_class.new.perform(blast.id)
expect_sent_count 2
@followers.each do |follower|
expect_sent_email follower.email, content_match: [
/#{cancel_follow_url(follower.external_id)}.*Unsubscribe/
]
end
end
it "when affiliate_type? is true, it sends the expected emails" do
post = create(:affiliate_post, :published, seller: @seller, affiliate_products: [@products[0].unique_permalink])
blast = create(:blast, :just_requested, post:)
described_class.new.perform(blast.id)
expect_sent_count 1
expect_sent_email @affiliates[0].affiliate_user.email, content_match: [
/#{unsubscribe_posts_affiliate_url(@affiliates[0].external_id)}.*Unsubscribe/
]
end
it "when audience_type? is true, it sends the expected emails" do
post = create(:audience_post, :published, seller: @seller)
blast = create(:blast, :just_requested, post:)
described_class.new.perform(blast.id)
expect_sent_count 7
[0, 1].each do |follower_index|
expect_sent_email @followers[follower_index].email, content_match: [
/#{cancel_follow_url(@followers[follower_index].external_id)}.*Unsubscribe/
]
end
expect_sent_email @affiliates[0].affiliate_user.email, content_match: [
/#{unsubscribe_posts_affiliate_url(@affiliates[0].external_id)}.*Unsubscribe/
]
[2, 3, 4, 5].each do |sale_index|
expect_sent_email @sales[sale_index].email, content_match: [
/#{unsubscribe_purchase_url(@sales[sale_index].secure_external_id(scope: "unsubscribe"))}.*Unsubscribe/
]
end
end
end
describe "Attachments and UrlRedirect" do
before do
@followers = create_list(:active_follower, 2, user: @seller)
@purchases = []
@purchases << create(:purchase, :from_seller, seller: @seller)
@purchases << create(:membership_purchase, :from_seller, seller: @seller)
@post = create(:audience_post, :published, seller: @seller)
@blast = create(:blast, :just_requested, post: @post)
end
it "creates the UrlRedirect records and adds a download button to the email" do
@post.product_files << create(:product_file)
expect do
described_class.new.perform(@blast.id)
end.to change { UrlRedirect.count }.by(3)
expect_sent_count 4
url_redirect_for_followers = UrlRedirect.find_by!(installment_id: @post.id, purchase_id: nil)
@followers.each do |follower|
expect_sent_email follower.email, content_match: [
/#{url_redirect_for_followers.download_page_url}.*View content/,
]
end
@purchases.each do |purchase|
expect_sent_email purchase.email, content_match: [
/#{UrlRedirect.find_by!(installment_id: @post.id, purchase_id: purchase.id, subscription_id: purchase.subscription_id).download_page_url}.*View content/,
]
end
end
it "does not create the UrlRedirect records if the post has no attachments" do
expect do
described_class.new.perform(@blast.id)
end.not_to change { UrlRedirect.count }
expect_sent_count 4
PostSendgridApi.mails.each do |email, _|
expect_sent_email email, content_not_match: [
/View content/,
]
end
end
end
context "recipients slice size" do
before do
stub_const("PostSendgridApi::MAX_RECIPIENTS", 10)
@blast = create(:blast, :just_requested, post: basic_post_with_audience)
create_list(:active_follower, 10, user: @seller) # there are now 11 followers
@expected_base_args = { post: @blast.post, blast: @blast, cache: anything }
end
it "is equal to PostSendgridApi::MAX_RECIPIENTS by default" do
expect(PostSendgridApi).to receive(:process).with(recipients: satisfy { _1.size == 10 }, **@expected_base_args).once.and_call_original
expect(PostSendgridApi).to receive(:process).with(recipients: satisfy { _1.size == 1 }, **@expected_base_args).once.and_call_original
described_class.new.perform(@blast.id)
expect_sent_count 11
end
it "can be controlled by redis key" do
$redis.set(RedisKey.blast_recipients_slice_size, 4)
expect(PostSendgridApi).to receive(:process).with(recipients: satisfy { _1.size == 4 }, **@expected_base_args).twice.and_call_original
expect(PostSendgridApi).to receive(:process).with(recipients: satisfy { _1.size == 3 }, **@expected_base_args).once.and_call_original
described_class.new.perform(@blast.id)
expect_sent_count 11
end
end
end
describe "error handling" do
it "deletes sent_post_emails records if PostEmailApi.process raises an error" do
# Setup post and blast
post = create(:audience_post, :published, seller: @seller)
create(:active_follower, user: @seller)
blast = create(:blast, :just_requested, post: post)
# Mock PostEmailApi to raise an error
expect(PostEmailApi).to receive(:process).and_raise(StandardError.new("API failure"))
# Run the job and expect it to raise the error
expect do
described_class.new.perform(blast.id)
end.to raise_error(StandardError, "API failure")
# Verify that no SentPostEmail records exist
expect(SentPostEmail.where(post: post).count).to eq(0)
end
end
def expect_sent_count(count)
expect(PostSendgridApi.mails.size).to eq(count)
end
def expect_sent_email(email, content_match: nil, content_not_match: nil)
expect(PostSendgridApi.mails[email]).to be_present
Array.wrap(content_match).each { expect(PostSendgridApi.mails[email][:content]).to match(_1) }
Array.wrap(content_not_match).each { expect(PostSendgridApi.mails[email][:content]).not_to match(_1) }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/create_stripe_merchant_account_worker_spec.rb | spec/sidekiq/create_stripe_merchant_account_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CreateStripeMerchantAccountWorker do
describe "#perform" do
let(:user) do
user = create(:user)
create(:user_compliance_info, user:)
create(:tos_agreement, user:)
user
end
it "creates an account for the user" do
expect(StripeMerchantAccountManager).to receive(:create_account).with(user, passphrase: GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD"))
described_class.new.perform(user.id)
end
it "receives Stripe::InvalidRequestError" do
error_message = "Invalid account number: must contain only digits, and be at most 12 digits long"
allow(Stripe::Account).to receive(:create).and_raise(Stripe::InvalidRequestError.new(error_message, nil))
expect do
described_class.new.perform(user.id)
end.to raise_error(Stripe::InvalidRequestError)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/update_purchase_email_to_match_account_worker_spec.rb | spec/sidekiq/update_purchase_email_to_match_account_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdatePurchaseEmailToMatchAccountWorker do
before do
@user = create(:user)
@purchase_a = create(:purchase, email: "old@gmail.com", purchaser: @user)
@purchase_b = create(:purchase, email: @user.email, purchaser: @user)
end
describe "#perform" do
it "updates email address in every purchased product" do
described_class.new.perform(@user.id)
expect(@user.reload.purchases.size).to eq 2
expect(@purchase_a.reload.email).to eq @user.email
expect(@purchase_b.reload.email).to eq @user.email
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/fail_abandoned_purchase_worker_spec.rb | spec/sidekiq/fail_abandoned_purchase_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe FailAbandonedPurchaseWorker, :vcr do
include ManageSubscriptionHelpers
describe "#perform" do
let(:chargeable) { build(:chargeable, card: StripePaymentMethodHelper.success_with_sca) }
context "when purchase has succeeded" do
let!(:purchase) { create(:purchase) }
before { travel ChargeProcessor::TIME_TO_COMPLETE_SCA }
it "does nothing" do
expect(ChargeProcessor).not_to receive(:cancel_charge_intent!)
described_class.new.perform(purchase.id)
expect(FailAbandonedPurchaseWorker.jobs.size).to eq(0)
end
end
context "when purchase has failed" do
let!(:purchase) { create(:failed_purchase) }
before { travel ChargeProcessor::TIME_TO_COMPLETE_SCA }
it "does nothing" do
expect(ChargeProcessor).not_to receive(:cancel_charge_intent!)
described_class.new.perform(purchase.id)
expect(FailAbandonedPurchaseWorker.jobs.size).to eq(0)
end
end
context "when purchase is in_progress" do
describe "preorder purchase" do
let(:product) { create(:product, is_in_preorder_state: true) }
let!(:preorder_product) { create(:preorder_link, link: product) }
let(:purchase) { create(:purchase_in_progress, link: product, chargeable:, is_preorder_authorization: true) }
before do
purchase.process!(off_session: false)
travel ChargeProcessor::TIME_TO_COMPLETE_SCA
end
context "when purchase was abandoned and SCA never completed" do
it "cancels the setup intent and marks purchase as failed" do
expect(ChargeProcessor).to receive(:cancel_setup_intent!).and_call_original
described_class.new.perform(purchase.id)
expect(purchase.reload.purchase_state).to eq("preorder_authorization_failed")
end
end
context "when setup intent has been canceled in parallel" do
before do
ChargeProcessor.cancel_setup_intent!(purchase.merchant_account, purchase.processor_setup_intent_id)
end
it "handles the error gracefully and does not change the purchase state" do
described_class.new.perform(purchase.id)
expect(purchase.reload.purchase_state).to eq("in_progress")
end
end
context "when setup intent has succeeded in parallel" do
before do
# Unfortunately, Stripe does not provide a way to confirm a setup intent that's in `requires_action` state
# without the Stripe SDK (i.e. the UI), so we simulate this.
allow(ChargeProcessor).to receive(:cancel_setup_intent!).and_raise(ChargeProcessorError, "You cannot cancel this SetupIntent because it has a status of succeeded.")
allow_any_instance_of(StripeSetupIntent).to receive(:succeeded?).and_return(true)
end
it "handles the error gracefully and does not change the purchase state" do
described_class.new.perform(purchase.id)
expect(purchase.reload.purchase_state).to eq("in_progress")
end
end
context "when unexpected charge processor error occurs" do
before do
allow(ChargeProcessor).to receive(:cancel_setup_intent!).and_raise(ChargeProcessorError)
end
it "raises an error" do
expect do
described_class.new.perform(purchase.id)
end.to raise_error(ChargeProcessorError)
end
end
end
describe "classic purchase" do
let(:purchase) { create(:purchase_in_progress, chargeable:) }
before do
purchase.process!(off_session: false)
travel ChargeProcessor::TIME_TO_COMPLETE_SCA
end
context "when purchase was abandoned and SCA never completed" do
it "cancels the charge intent and marks purchase as failed" do
expect(ChargeProcessor).to receive(:cancel_payment_intent!).and_call_original
described_class.new.perform(purchase.id)
expect(purchase.reload.purchase_state).to eq("failed")
end
end
context "when payment intent has been canceled in parallel" do
before do
ChargeProcessor.cancel_payment_intent!(purchase.merchant_account, purchase.processor_payment_intent_id)
end
it "handles the error gracefully and does not change the purchase state" do
described_class.new.perform(purchase.id)
expect(purchase.reload.purchase_state).to eq("in_progress")
end
end
context "when payment intent has succeeded in parallel" do
before do
# Unfortunately, Stripe does not provide a way to confirm a payment intent that's in `requires_action` state
# without the Stripe SDK (i.e. the UI), so we simulate this.
allow(ChargeProcessor).to receive(:cancel_payment_intent!).and_raise(ChargeProcessorError, "You cannot cancel this PaymentIntent because it has a status of succeeded.")
allow_any_instance_of(StripeChargeIntent).to receive(:succeeded?).and_return(true)
allow_any_instance_of(StripeChargeIntent).to receive(:load_charge)
end
it "handles the error gracefully and does not change the purchase state" do
described_class.new.perform(purchase.id)
expect(purchase.reload.purchase_state).to eq("in_progress")
end
end
context "when unexpected charge processor error occurs" do
before do
allow(ChargeProcessor).to receive(:cancel_payment_intent!).and_raise(ChargeProcessorError)
end
it "raises an error" do
expect do
described_class.new.perform(purchase.id)
end.to raise_error(ChargeProcessorError)
end
end
end
context "membership upgrade purchase" do
let(:user) { create(:user) }
before do
setup_subscription
@indian_cc = create(:credit_card, user: user, chargeable: create(:chargeable, card: StripePaymentMethodHelper.success_indian_card_mandate))
@subscription.credit_card = @indian_cc
@subscription.save!
params = {
price_id: @quarterly_product_price.external_id,
variants: [@new_tier.external_id],
quantity: 1,
use_existing_card: true,
perceived_price_cents: @new_tier_quarterly_price.price_cents,
perceived_upgrade_price_cents: @new_tier_quarterly_price.price_cents,
}
Subscription::UpdaterService.new(
subscription: @subscription,
gumroad_guid: "abc123",
params:,
logged_in_user: user,
remote_ip: "11.22.33.44",
).perform
@membership_upgrade_purchase = @subscription.reload.purchases.in_progress.last
travel ChargeProcessor::TIME_TO_COMPLETE_SCA
end
context "when purchase was abandoned and SCA never completed" do
it "cancels the charge intent, marks purchase as failed, and cancels membership upgrade" do
expect(ChargeProcessor).to receive(:cancel_payment_intent!).and_call_original
expect_any_instance_of(Purchase::MarkFailedService).to receive(:mark_items_failed).and_call_original
expect(@membership_upgrade_purchase.reload.purchase_state).to eq("in_progress")
expect(@subscription.reload.original_purchase.variant_attributes).to eq [@new_tier]
described_class.new.perform(@membership_upgrade_purchase.id)
expect(@membership_upgrade_purchase.reload.purchase_state).to eq("failed")
expect(@subscription.reload.original_purchase.variant_attributes).to eq [@original_tier]
end
end
end
context "membership restart purchase" do
let(:user) { create(:user) }
before do
setup_subscription
@indian_cc = create(:credit_card, user: user, chargeable: create(:chargeable, card: StripePaymentMethodHelper.success_indian_card_mandate))
@subscription.credit_card = @indian_cc
@subscription.save!
@subscription.update!(cancelled_at: @originally_subscribed_at + 4.months, cancelled_by_buyer: true)
params = {
price_id: @quarterly_product_price.external_id,
variants: [@original_tier.external_id],
quantity: 1,
perceived_price_cents: @original_tier_quarterly_price.price_cents,
perceived_upgrade_price_cents: @original_tier_quarterly_price.price_cents,
}.merge(StripePaymentMethodHelper.success_indian_card_mandate.to_stripejs_params(prepare_future_payments: true))
Subscription::UpdaterService.new(
subscription: @subscription,
gumroad_guid: "abc123",
params:,
logged_in_user: user,
remote_ip: "11.22.33.44",
).perform
@membership_restart_purchase = @subscription.reload.purchases.in_progress.last
travel ChargeProcessor::TIME_TO_COMPLETE_SCA
end
context "when purchase was abandoned and SCA never completed" do
it "cancels the charge intent, marks purchase as failed, and cancels membership upgrade" do
expect(ChargeProcessor).to receive(:cancel_payment_intent!).and_call_original
expect_any_instance_of(Purchase::MarkFailedService).to receive(:mark_items_failed).and_call_original
expect(@membership_restart_purchase.reload.purchase_state).to eq("in_progress")
expect(@subscription.reload.original_purchase.variant_attributes).to eq [@original_tier]
expect(@subscription.is_resubscription_pending_confirmation?).to be true
expect(@subscription.alive?).to be true
described_class.new.perform(@membership_restart_purchase.id)
expect(@membership_restart_purchase.reload.purchase_state).to eq("failed")
expect(@subscription.reload.original_purchase.variant_attributes).to eq [@original_tier]
expect(@subscription.is_resubscription_pending_confirmation?).to be false
expect(@subscription.reload.alive?).to be false
end
end
end
context "when the job is called before time to complete SCA has expired" do
let(:purchase) { create(:purchase_in_progress, chargeable:) }
before do
purchase.process!(off_session: false)
end
it "does not cancel payment intent and reschedules the job instead" do
expect(ChargeProcessor).not_to receive(:cancel_charge_intent!)
described_class.new.perform(purchase.id)
expect(FailAbandonedPurchaseWorker).to have_enqueued_sidekiq_job(purchase.id)
end
end
context "when purchase has no processor_payment_intent_id or processor_setup_intent_id" do
let!(:purchase) { create(:purchase_in_progress) }
before { travel ChargeProcessor::TIME_TO_COMPLETE_SCA }
it "raises an error" do
expect do
expect(ChargeProcessor).not_to receive(:cancel_charge_intent!)
described_class.new.perform(purchase.id)
end.to raise_error(/Expected purchase #{purchase.id} to have either a processor_payment_intent_id or processor_setup_intent_id present/)
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/update_product_files_archive_worker_spec.rb | spec/sidekiq/update_product_files_archive_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateProductFilesArchiveWorker, :vcr do
describe "#perform" do
before do
@long_file_name = "2d04543f25c2abbea7740c6abf71d07a12abff9b6ef45f1fabab0b6efb4679643f87131f869bbc7a2a146c3730ee57c65839"
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("production"))
end
context "when rich content provider is not present" do
before do
installment = create(:installment)
installment.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/magic.mp3")
installment.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/magic.mp3")
installment.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/#{@long_file_name}.csv")
installment.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/#{@long_file_name}.csv")
installment.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/#{@long_file_name}.csv")
installment.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/#{@long_file_name}.csv")
installment.product_files << create(:streamable_video)
installment.product_files << create(:streamable_video, stream_only: true)
installment.product_files << create(:product_file, url: "https://www.gumroad.com", filetype: "link")
@product_files_archive = installment.product_files_archives.create!
@product_files_archive.product_files = installment.product_files
@product_files_archive.save!
@product_files_archive.set_url_if_not_present
@product_files_archive.save!
end
it "creates a zip archive of product files while skipping external link and stream only files" do
expect(@product_files_archive.queueing?).to be(true)
UpdateProductFilesArchiveWorker.new.perform(@product_files_archive.id)
@product_files_archive.reload
expect(@product_files_archive.ready?).to be(true)
expect(@product_files_archive.url).to match(/gumroad-specs\/attachments_zipped/)
expect(@product_files_archive.url).to end_with("zip")
temp_file = Tempfile.new
@product_files_archive.s3_object.download_file(temp_file.path)
temp_file.rewind
entries = []
Zip::File.open(temp_file.path) do |zipfile|
zipfile.each do |entry|
entries << entry.name.force_encoding("UTF-8")
end
end
temp_file.close!
expect(entries.count).to eq(7)
expect(entries).to include("magic.mp3")
# Makes sure all file names in the generated zip are unique
expect(entries).to include("magic-1.mp3")
# Truncates long file names
truncated_long_filename = @long_file_name.truncate_bytes(described_class::MAX_FILENAME_BYTESIZE, omission: nil)
expect(entries).to include("#{truncated_long_filename}.csv")
# Makes sure all file names are unique, even when filename is truncated
expect(entries).to include("#{truncated_long_filename}-1.csv")
expect(@product_files_archive.s3_object.content_type).to eq("application/zip")
end
context "when product files archive is marked as deleted" do
before do
@product_files_archive.mark_deleted!
end
it "doesn't update the archive" do
expect do
expect(described_class.new.perform(@product_files_archive.id)).to be_nil
end.not_to change { @product_files_archive.reload.product_files_archive_state }
end
end
end
context "when rich content provider is present" do
before do
@product = create(:product)
@product_file1 = create(:readable_document, display_name: "जीवन में यश एवम् समृद्धी प्राप्त करने के कहीं न बताये जाने वाले १०० उपाय")
@product_file2 = create(:readable_document, display_name: "कैसे जीवन का आनंद ले")
@product_file3 = create(:readable_document, display_name: "File 3")
@product_file4 = create(:readable_document, display_name: "आनंद और सुखी जीवन के लिए जाने कुछ रहस्य जो आपको नहीं पता होंगे और जिन्हें आपको जानना चाहिए")
@product_file5 = create(:readable_document, display_name: "File 5")
@product.product_files = [@product_file1, @product_file2, @product_file3, @product_file4, @product_file5]
@product.save!
@page1 = create(:rich_content, entity: @product, description: [
{ "type" => "fileEmbed", "attrs" => { "id" => @product_file1.external_id, "uid" => "file-1" } },
])
@page2 = create(:rich_content, entity: @product, title: "Page 2", description: [
{ "type" => "fileEmbedGroup", "attrs" => { "name" => "" }, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => @product_file2.external_id, "uid" => "0c042930-2df1-4583-82ef-a63172138683" } },
] },
{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Some text" }] },
{ "type" => "fileEmbedGroup", "attrs" => { "name" => "" }, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => @product_file3.external_id, "uid" => "0c042930-2df1-4583-82ef-a6317213868f" } },
] },
])
@folder_id = SecureRandom.uuid
@page3 = create(:rich_content, entity: @product, description: [
{ "type" => "fileEmbedGroup", "attrs" => { "name" => "आनंदमय जीवन जिने के ५ सरल उपाय", "uid": @folder_id }, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => @product_file4.external_id, "uid" => "0c042930-2df1-4583-82ef-a6317213868w" } },
{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Lorem ipsum" }] },
{ "type" => "fileEmbed", "attrs" => { "id" => @product_file5.external_id, "uid" => "0c042930-2df1-4583-82ef-a63172138681" } },
] },
])
@product_files_archive = @product.product_files_archives.create!
@product_files_archive.product_files = @product.product_files
@product_files_archive.save!
@product_files_archive.set_url_if_not_present
@product_files_archive.save!
@folder_archive = @product.product_files_archives.create!(folder_id: @folder_id)
@folder_archive.product_files = [@product_file4, @product_file5]
@folder_archive.save!
@folder_archive.set_url_if_not_present
@folder_archive.save!
end
it "creates a zip archive of embedded ungrouped files and grouped files while skipping external link and stream only files" do
UpdateProductFilesArchiveWorker.new.perform(@product_files_archive.id)
@product_files_archive.reload
expect(@product_files_archive.url).to end_with("zip")
temp_file = Tempfile.new
@product_files_archive.s3_object.download_file(temp_file.path)
temp_file.rewind
entries = []
Zip::File.open(temp_file.path) do |zipfile|
zipfile.each do |entry|
entries << entry.name.force_encoding("UTF-8")
end
end
temp_file.close!
expect(entries.count).to eq(5)
expect(entries).to match_array([
# Truncates long file name "जीवन में यश एवम् समृद्धी प्राप्त करने के कहीं न बताये जाने वाले १०० उपाय" enclosed in a folder named "Page 1" (title of the page)
"Untitled 1/जीवन में यश एवम् समृद्धी प्राप्त करने .pdf",
# Enclose the file in nested folders, "Page 2" (title of the page) and "Untitled 2" (name of the file group)
"Page 2/Untitled 1/कैसे जीवन का आनंद ले.pdf",
# Enclose the file in a folder named "Page 2" (title of the page)
"Page 2/Untitled 2/File 3.pdf",
# Truncates long file name "आनंद और सुखी जीवन के लिए जाने कुछ रहस्य जो आपको नहीं पता होंगे और जिन्हें आपको जानना चाहिए" enclosed in nested folders, "Untitled 2" (fallback title of the page) and "आनंदमय जीवन जिने के ५ सरल उपाय" (name of the file group, which gets truncated as well)
"Untitled 2/आनंदमय जीवन जिने के ५ स/आनंद और सुखी जीवन के लिए जा.pdf",
# Enclose the file in nested folders, "Untitled 2" (fallback title of the page) and "आनंदमय जीवन जिने के ५ सरल उपाय" (name of the file group)
"Untitled 2/आनंदमय जीवन जिने के ५ सरल उपाय/File 5.pdf"
])
end
it "creates a zip archive of folder files" do
UpdateProductFilesArchiveWorker.new.perform(@folder_archive.id)
@folder_archive.reload
expect(@folder_archive.url).to end_with("zip")
expect(@folder_archive.url).to include("आनंदमय_जीवन_जिने_के_५_सरल_उपाय")
temp_file = Tempfile.new
@folder_archive.s3_object.download_file(temp_file.path)
temp_file.rewind
entries = []
Zip::File.open(temp_file.path) do |zipfile|
zipfile.each do |entry|
entries << entry.name.force_encoding("UTF-8")
end
end
temp_file.close!
expect(entries.count).to eq(2)
expect(entries).to match_array(
[
"आनंद और सुखी जीवन के लिए जाने कुछ रहस्य जो आपको नहीं पता .pdf",
"File 5.pdf"
])
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_bundles_marketing_email_job_spec.rb | spec/sidekiq/send_bundles_marketing_email_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SendBundlesMarketingEmailJob do
describe "#perform" do
let(:seller) { create(:user) }
let!(:products) do
build_list(:product, 10, user: seller) do |product, i|
product.update!(price_cents: (i + 1) * 100, name: "Product #{i}")
end
end
let!(:purchases) do
build_list(:purchase, 10, seller:) do |purchase, i|
product = products[i]
purchase.update!(link: product, price_cents: product.price_cents)
end
end
let(:bundles) do
[
{
type: Product::BundlesMarketing::BEST_SELLING_BUNDLE,
price: 4000,
discounted_price: 3200,
products: products.reverse[0..4].map { |p| { id: p.external_id, name: p.name, url: p.long_url } }
},
{
type: Product::BundlesMarketing::EVERYTHING_BUNDLE,
price: 5400,
discounted_price: 4320,
products: products.reverse[0..8].map { |p| { id: p.external_id, name: p.name, url: p.long_url } }
},
{
type: Product::BundlesMarketing::YEAR_BUNDLE,
price: 500,
discounted_price: 400,
products: products[1..2].reverse.map { |p| { id: p.external_id, name: p.name, url: p.long_url } }
},
]
end
before do
products[0..2].each do |product|
product.update!(created_at: Time.current.prev_year)
end
create(:payment_completed, user: seller)
index_model_records(Purchase)
index_model_records(Link)
end
it "enqueues the mail with the correct arguments" do
expect do
described_class.new.perform
end.to have_enqueued_mail(CreatorMailer, :bundles_marketing).with(
seller_id: seller.id,
bundles:,
).once
end
context "when a bundle doesn't have at least two products" do
before do
products[..2].each { _1.update!(created_at: Time.new(2022, 1, 1)) }
end
it "excludes that bundle" do
expect do
described_class.new.perform
end.to have_enqueued_mail(CreatorMailer, :bundles_marketing).with(
seller_id: seller.id,
bundles: bundles[0..1]
)
end
end
context "no bundles" do
before do
products.each { _1.destroy! }
index_model_records(Link)
end
it "doesn't enqueue any mail" do
expect do
described_class.new.perform
end.to_not have_enqueued_mail(CreatorMailer, :bundles_marketing)
end
end
context "seller is suspended" do
before { seller.update!(user_risk_state: "suspended_for_tos_violation") }
it "doesn't enqueue any mail" do
expect do
described_class.new.perform
end.to_not have_enqueued_mail(CreatorMailer, :bundles_marketing)
end
end
context "seller is deleted" do
before { seller.update!(deleted_at: Time.current) }
it "doesn't enqueue any mail" do
expect do
described_class.new.perform
end.to_not have_enqueued_mail(CreatorMailer, :bundles_marketing)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/email_outstanding_balances_csv_worker_spec.rb | spec/sidekiq/email_outstanding_balances_csv_worker_spec.rb | # frozen_string_literal: true
describe EmailOutstandingBalancesCsvWorker do
describe "perform" do
it "enqueues AccountingMailer.email_outstanding_balances_csv" do
allow(Rails.env).to receive(:production?).and_return(true)
expect(AccountingMailer).to receive(:email_outstanding_balances_csv).and_return(@mailer_double)
allow(@mailer_double).to receive(:deliver_now)
EmailOutstandingBalancesCsvWorker.new.perform
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/update_purchasing_power_parity_factors_worker_spec.rb | spec/sidekiq/update_purchasing_power_parity_factors_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdatePurchasingPowerParityFactorsWorker, :vcr do
describe "#perform" do
before do
# The VCR cassette for PPP data is from 2025, so this prevents the worker complaining it's out of date
travel_to Date.new(2025, 1, 1)
@seller = create(:user)
@worker = described_class.new
@service = PurchasingPowerParityService.new
@worker.perform
end
context "when factor is greater than 0.8" do
it "sets PPP factor to 1" do
expect(@service.get_factor("LU", @seller)).to eq(1)
end
end
context "when factor is less than 0.8" do
it "sets PPP factor rounded to the nearest hundredth" do
expect(@service.get_factor("AE", @seller)).to eq(0.64)
end
end
context "when factor is less than 0.4" do
it "sets PPP factor to 0.4" do
expect(@service.get_factor("YE", @seller)).to eq(0.4)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/delete_old_unused_events_worker_spec.rb | spec/sidekiq/delete_old_unused_events_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DeleteOldUnusedEventsWorker do
describe "#perform" do
it "deletes targeted rows" do
stub_const("#{described_class}::DELETION_BATCH_SIZE", 1)
create(:event, event_name: "i_want_this", created_at: 2.months.ago - 1.day)
permitted = create(:purchase_event, created_at: 2.months.ago - 1.day)
kept_because_recent = create(:event, event_name: "i_want_this", created_at: 1.month.ago)
described_class.new.perform
expect(Event.all).to match_array([permitted, kept_because_recent])
described_class.new.perform(from: 1.year.ago, to: Time.current)
expect(Event.all).to match_array([permitted])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/fight_disputes_job_spec.rb | spec/sidekiq/fight_disputes_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe FightDisputesJob do
let!(:dispute_evidence) { create(:dispute_evidence, seller_contacted_at: nil) }
let!(:dispute_evidence_not_ready) { create(:dispute_evidence) }
let!(:dispute_evidence_resolved) { create(:dispute_evidence, seller_contacted_at: nil, resolved_at: Time.current, resolution: "submitted") }
describe "#perform" do
it "performs the job" do
described_class.new.perform
expect(FightDisputeJob).to have_enqueued_sidekiq_job(dispute_evidence.dispute.id)
expect(FightDisputeJob).not_to have_enqueued_sidekiq_job(dispute_evidence_not_ready.dispute.id)
expect(FightDisputeJob).not_to have_enqueued_sidekiq_job(dispute_evidence_resolved.dispute.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_finances_report_worker_spec.rb | spec/sidekiq/send_finances_report_worker_spec.rb | # frozen_string_literal: true
describe SendFinancesReportWorker do
describe "perform" do
before do
@last_month = Time.current.last_month
@mailer_double = double("mailer")
allow(AccountingMailer).to receive(:funds_received_report).with(@last_month.month, @last_month.year).and_return(@mailer_double)
allow(@mailer_double).to receive(:deliver_now)
allow(Rails.env).to receive(:production?).and_return(true)
end
it "enqueues AccountingMailer.funds_received_report" do
expect(AccountingMailer).to receive(:funds_received_report).with(@last_month.month, @last_month.year).and_return(@mailer_double)
allow(@mailer_double).to receive(:deliver_now)
SendFinancesReportWorker.new.perform
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/schedule_abandoned_cart_emails_job_spec.rb | spec/sidekiq/schedule_abandoned_cart_emails_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ScheduleAbandonedCartEmailsJob do
describe "#perform" do
let(:seller1) { create(:user) }
let!(:seller1_payment) { create(:payment_completed, user: seller1) }
let!(:seller1_product1) { create(:product, user: seller1) }
let!(:seller1_product2) { create(:product, user: seller1) }
let(:seller1_product2_variant_category) { create(:variant_category, link: seller1_product2) }
let!(:seller1_product2_variant1) { create(:variant, variant_category: seller1_product2_variant_category) }
let!(:seller1_product2_variant2) { create(:variant, variant_category: seller1_product2_variant_category) }
let!(:seller1_abandoned_cart_workflow) { create(:abandoned_cart_workflow, seller: seller1, published_at: 1.day.ago, bought_products: [seller1_product1.unique_permalink], bought_variants: [seller1_product2_variant1.external_id]) }
let(:seller2) { create(:user) }
let!(:seller2_payment) { create(:payment_completed, user: seller2) }
let!(:seller2_product1) { create(:product, user: seller2) }
let!(:seller2_product2) { create(:product, user: seller2) }
let!(:seller2_abandoned_cart_workflow) { create(:abandoned_cart_workflow, seller: seller2, published_at: 1.day.ago, bought_products: [seller2_product1.unique_permalink]) }
context "when there are no abandoned carts" do
it "does not schedule any emails" do
create(:cart)
expect { described_class.new.perform }.not_to have_enqueued_mail(CustomerMailer, :abandoned_cart)
end
end
context "when there are abandoned carts" do
context "when there are no matching abandoned cart workflows" do
it "does not schedule any emails" do
cart = create(:cart, updated_at: 2.days.ago)
create(:cart_product, cart:, product: seller1_product1)
create(:cart_product, cart:)
seller1_abandoned_cart_workflow.unpublish!
expect { described_class.new.perform }.not_to have_enqueued_mail(CustomerMailer, :abandoned_cart)
end
end
context "when there are matching abandoned cart workflows" do
let(:cart1) { create(:cart) }
let!(:cart1_product1) { create(:cart_product, cart: cart1, product: seller1_product1) }
let!(:cart1_product2) { create(:cart_product, cart: cart1, product: seller1_product2, option: seller1_product2_variant1) }
let!(:cart1_product3) { create(:cart_product, cart: cart1, product: seller2_product2) }
let(:cart2) { create(:cart) }
let!(:cart2_product1) { create(:cart_product, cart: cart2, product: seller2_product1) }
let!(:cart2_product2) { create(:cart_product, cart: cart2, product: seller1_product2, option: seller1_product2_variant2) }
let(:cart3) { create(:cart) }
let!(:cart3_product1) { create(:cart_product, cart: cart3, product: seller1_product2) }
let(:guest_cart1) { create(:cart, :guest, email: "guest1@example.com") }
let!(:guest_cart1_product1) { create(:cart_product, cart: guest_cart1, product: seller1_product1) }
let!(:guest_cart1_product2) { create(:cart_product, cart: guest_cart1, product: seller1_product2, option: seller1_product2_variant1) }
let(:guest_cart2) { create(:cart, :guest, email: "") } # ignores this guest cart due to absence of email
let!(:guest_cart2_product1) { create(:cart_product, cart: guest_cart2, product: seller2_product1) }
let(:guest_cart3) { create(:cart, :guest, email: "guest3@example.com") }
let!(:guest_cart3_product1) { create(:cart_product, cart: guest_cart3, product: seller1_product2) }
let!(:guest_cart4) { create(:cart, :guest, email: "guest4@example.com") }
before do
cart1.update!(updated_at: 2.days.ago)
cart2.update!(updated_at: 25.hours.ago)
cart3.update!(updated_at: 21.hours.ago)
guest_cart1.update!(updated_at: 2.days.ago)
guest_cart2.update!(updated_at: 25.hours.ago)
guest_cart3.update!(updated_at: 21.hours.ago)
guest_cart4.update!(updated_at: 2.days.ago)
end
it "schedules emails for the matching abandoned carts belonging to both logged-in users and guest carts" do
expect do
described_class.new.perform
end.to have_enqueued_mail(CustomerMailer, :abandoned_cart).exactly(3).times
.and have_enqueued_mail(CustomerMailer, :abandoned_cart).with(cart1.id, { seller1_abandoned_cart_workflow.id => [seller1_product1.id, seller1_product2.id] }.stringify_keys)
.and have_enqueued_mail(CustomerMailer, :abandoned_cart).with(cart2.id, { seller2_abandoned_cart_workflow.id => [seller2_product1.id] }.stringify_keys)
.and have_enqueued_mail(CustomerMailer, :abandoned_cart).with(guest_cart1.id, { seller1_abandoned_cart_workflow.id => [seller1_product1.id, seller1_product2.id] }.stringify_keys)
end
end
context "when there are multiple matching abandoned cart workflows for a cart" do
let(:cart) { create(:cart) }
let!(:cart_product1) { create(:cart_product, cart: cart, product: seller1_product1) }
let!(:cart_product2) { create(:cart_product, cart: cart, product: seller1_product2, option: seller1_product2_variant1) }
let!(:cart_product3) { create(:cart_product, cart: cart, product: seller2_product1) }
let!(:cart_product4) { create(:cart_product, cart: cart, product: seller2_product2) }
let(:guest_cart) { create(:cart, :guest, email: "guest@example.com") }
let!(:guest_cart_product1) { create(:cart_product, cart: guest_cart, product: seller1_product1) }
let!(:guest_cart_product2) { create(:cart_product, cart: guest_cart, product: seller1_product2, option: seller1_product2_variant1) }
let!(:guest_cart_product3) { create(:cart_product, cart: guest_cart, product: seller2_product1) }
let!(:guest_cart_product4) { create(:cart_product, cart: guest_cart, product: seller2_product2) }
before do
cart.update!(updated_at: 2.days.ago)
guest_cart.update!(updated_at: 2.days.ago)
end
it "schedules only one email for each of the corresponding carts" do
expect do
described_class.new.perform
end.to have_enqueued_mail(CustomerMailer, :abandoned_cart).exactly(2).times
.and have_enqueued_mail(CustomerMailer, :abandoned_cart).with(cart.id, { seller1_abandoned_cart_workflow.id => [seller1_product1.id, seller1_product2.id], seller2_abandoned_cart_workflow.id => [seller2_product1.id] }.stringify_keys)
.and have_enqueued_mail(CustomerMailer, :abandoned_cart).with(guest_cart.id, { seller1_abandoned_cart_workflow.id => [seller1_product1.id, seller1_product2.id], seller2_abandoned_cart_workflow.id => [seller2_product1.id] }.stringify_keys)
end
end
end
context "when seller is not eligible for abandoned cart workflows" do
let(:cart) { create(:cart) }
let!(:cart_product) { create(:cart_product, cart: cart, product: seller1_product1) }
let(:guest_cart) { create(:cart, :guest, email: "guest@example.com") }
let!(:guest_cart_product) { create(:cart_product, cart: guest_cart, product: seller1_product1) }
before do
cart.update!(updated_at: 2.days.ago)
guest_cart.update!(updated_at: 2.days.ago)
allow_any_instance_of(User).to receive(:eligible_for_abandoned_cart_workflows?).and_return(false)
end
it "does not schedule any abandoned cart emails" do
expect do
described_class.new.perform
end.not_to have_enqueued_mail(CustomerMailer, :abandoned_cart)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/block_email_domains_worker_spec.rb | spec/sidekiq/block_email_domains_worker_spec.rb | # frozen_string_literal: true
describe BlockEmailDomainsWorker do
describe "#perform" do
let(:admin_user) { create(:admin_user) }
let(:email_domains) { ["example.com", "example.org"] }
it "blocks email domains without expiration" do
expect(BlockedObject.email_domain.count).to eq(0)
described_class.new.perform(admin_user.id, email_domains)
expect(BlockedObject.email_domain.count).to eq(2)
blocked_object = BlockedObject.active.find_by(object_value: "example.com")
expect(blocked_object.blocked_by).to eq(admin_user.id)
expect(blocked_object.expires_at).to be_nil
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/refresh_sitemap_daily_worker_spec.rb | spec/sidekiq/refresh_sitemap_daily_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RefreshSitemapDailyWorker do
describe "#perform" do
before do
@product = create(:product, created_at: Time.current)
end
it "generates the sitemap" do
date = @product.created_at
sitemap_file_path = "#{Rails.public_path}/sitemap/products/monthly/#{date.year}/#{date.month}/sitemap.xml.gz"
described_class.new.perform
expect(File.exist?(sitemap_file_path)).to be true
end
it "invokes SitemapService" do
expect_any_instance_of(SitemapService).to receive(:generate)
described_class.new.perform
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/generate_financial_reports_for_previous_quarter_job_spec.rb | spec/sidekiq/generate_financial_reports_for_previous_quarter_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GenerateFinancialReportsForPreviousQuarterJob do
describe ".perform" do
it "does not generate any reports when the Rails environment is not production" do
described_class.new.perform
expect(CreateVatReportJob.jobs.size).to eq(0)
expect(GenerateSalesReportJob.jobs.size).to eq(0)
end
it "generates reports when the Rails environment is production" do
allow(Rails.env).to receive(:production?).and_return(true)
described_class.new.perform
expect(CreateVatReportJob).to have_enqueued_sidekiq_job(an_instance_of(Integer), an_instance_of(Integer))
expect(GenerateSalesReportJob).to have_enqueued_sidekiq_job("GB", an_instance_of(String), an_instance_of(String), GenerateSalesReportJob::ALL_SALES)
expect(GenerateSalesReportJob).to have_enqueued_sidekiq_job("AU", an_instance_of(String), an_instance_of(String), GenerateSalesReportJob::ALL_SALES)
expect(GenerateSalesReportJob).to have_enqueued_sidekiq_job("SG", an_instance_of(String), an_instance_of(String), GenerateSalesReportJob::ALL_SALES)
expect(GenerateSalesReportJob).to have_enqueued_sidekiq_job("NO", an_instance_of(String), an_instance_of(String), GenerateSalesReportJob::ALL_SALES)
end
[[2017, 1, 2016, 4],
[2017, 2, 2016, 4],
[2017, 3, 2016, 4],
[2017, 4, 2017, 1],
[2017, 5, 2017, 1],
[2017, 6, 2017, 1],
[2017, 7, 2017, 2],
[2017, 10, 2017, 3]].each do |current_year, current_month, expected_year, expected_quarter|
it "sets the quarter and year correctly for year #{current_year} and month #{current_month}" do
allow(Rails.env).to receive(:production?).and_return(true)
travel_to(Time.current.change(year: current_year, month: current_month, day: 2)) do
described_class.new.perform
end
expect(CreateVatReportJob).to have_enqueued_sidekiq_job(expected_quarter, expected_year)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/reindex_recommendable_products_worker_spec.rb | spec/sidekiq/reindex_recommendable_products_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ReindexRecommendableProductsWorker do
it "updates time-dependent fields" do
freeze_time
products = create_list(:product, 5)
allow(products[0]).to receive(:recommendable?).and_return(true)
create(:purchase, link: products[0])
allow(products[1]).to receive(:recommendable?).and_return(false)
allow(products[1]).to receive(:created_at).and_return(1.second.from_now)
create(:purchase, link: products[1])
allow(products[2]).to receive(:recommendable?).and_return(true)
allow(products[2]).to receive(:created_at).and_return(2.seconds.from_now)
create(:purchase, link: products[2])
allow(products[3]).to receive(:recommendable?).and_return(true)
allow(products[3]).to receive(:created_at).and_return(3.seconds.from_now)
create(:purchase, link: products[3])
allow(products[4]).to receive(:recommendable?).and_return(true)
allow(products[4]).to receive(:created_at).and_return(4.seconds.from_now)
create(:purchase, link: products[4], created_at: Product::Searchable::DEFAULT_SALES_VOLUME_RECENTNESS.ago - 1.day)
Link.__elasticsearch__.create_index!(force: true)
products.each { |product| product.__elasticsearch__.index_document }
Link.__elasticsearch__.refresh_index!
stub_const("#{described_class}::SCROLL_SIZE", 2)
stub_const("#{described_class}::SCROLL_SORT", ["created_at"])
expect(Sidekiq::Client).to receive(:push_bulk).with(
"class" => SendToElasticsearchWorker,
"args" => [
[products[0].id, "update", ["sales_volume", "total_fee_cents", "past_year_fee_cents"]],
[products[2].id, "update", ["sales_volume", "total_fee_cents", "past_year_fee_cents"]]
],
"queue" => "low",
"at" => Time.current.to_i
)
expect(Sidekiq::Client).to receive(:push_bulk).with(
"class" => SendToElasticsearchWorker,
"args" => [
[products[3].id, "update", ["sales_volume", "total_fee_cents", "past_year_fee_cents"]]
],
"queue" => "low",
"at" => 1.minute.from_now.to_i
)
described_class.new.perform
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_charge_receipt_job_spec.rb | spec/sidekiq/send_charge_receipt_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SendChargeReceiptJob do
let(:seller) { create(:named_seller) }
let(:product_one) { create(:product, user: seller, name: "Product One") }
let(:purchase_one) { create(:purchase, link: product_one, seller: seller) }
let(:product_two) { create(:product, user: seller, name: "Product Two") }
let(:purchase_two) { create(:purchase, link: product_two, seller: seller) }
let(:charge) { create(:charge, purchases: [purchase_one, purchase_two], seller: seller) }
let(:order) { charge.order }
before do
charge.order.purchases << purchase_one
charge.order.purchases << purchase_two
allow(PdfStampingService).to receive(:stamp_for_purchase!)
allow(CustomerMailer).to receive_message_chain(:receipt, :deliver_now)
end
context "with all purchases ready" do
it "delivers the email and updates the charge without stamping" do
described_class.new.perform(charge.id)
expect(PdfStampingService).not_to have_received(:stamp_for_purchase!)
expect(CustomerMailer).to have_received(:receipt).with(nil, charge.id)
expect(charge.reload.receipt_sent?).to be(true)
end
end
context "when the charge receipt has already been sent" do
before do
charge.update!(receipt_sent: true)
end
it "does nothing" do
described_class.new.perform(charge.id)
expect(PdfStampingService).not_to have_received(:stamp_for_purchase!)
expect(CustomerMailer).not_to have_received(:receipt)
end
end
context "when a purchase requires stamping" do
before do
allow_any_instance_of(Charge).to receive(:purchases_requiring_stamping).and_return([purchase_one])
end
it "stamps the PDFs and delivers the email" do
described_class.new.perform(charge.id)
expect(PdfStampingService).to have_received(:stamp_for_purchase!).exactly(:once)
expect(PdfStampingService).to have_received(:stamp_for_purchase!).with(purchase_one)
expect(CustomerMailer).to have_received(:receipt).with(nil, charge.id)
expect(charge.reload.receipt_sent?).to be(true)
end
context "when stamping fails" do
before do
allow(PdfStampingService).to receive(:stamp_for_purchase!).and_raise(PdfStampingService::Error)
end
it "doesn't deliver the email and raises an error" do
expect(CustomerMailer).not_to receive(:receipt)
expect { described_class.new.perform(charge.id) }.to raise_error(PdfStampingService::Error)
expect(charge.reload.receipt_sent?).to be(false)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/update_tax_rates_job_spec.rb | spec/sidekiq/update_tax_rates_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateTaxRatesJob, :vcr do
describe "#perform" do
it "creates rates for countries if they don't exist" do
zero_rate_state_codes = ["DE", "MT", "NH", "OR"]
expect { described_class.new.perform }.to change(ZipTaxRate, :count).from(0).to(Compliance::Countries::EU_VAT_APPLICABLE_COUNTRY_CODES.size + Compliance::Countries::TAXABLE_US_STATE_CODES.reject { |taxable_state_code| zero_rate_state_codes.include?(taxable_state_code) }.size + Compliance::Countries::CAN.subdivisions.size)
end
it "updates VAT rates for countries if there are any new updates" do
epublication_zip_tax_rate = create(:zip_tax_rate, country: "AT", combined_rate: 0.10, is_epublication_rate: true)
described_class.new.perform
zip_tax_rate = ZipTaxRate.not_is_epublication_rate.find_by(country: "AT")
zip_tax_rate.update(combined_rate: 0)
described_class.new.perform
expect(zip_tax_rate.reload.combined_rate).to eq(0.20)
# just ensure epublication rates aren't impacted by the periodic job
expect(epublication_zip_tax_rate.combined_rate).to eq(0.10)
end
it "makes sure updated VAT is alive" do
described_class.new.perform
ZipTaxRate.last.mark_deleted!
described_class.new.perform
expect(ZipTaxRate.last).to be_alive
end
it "updates rates for US states if there are any new updates" do
zip_tax_rate = create(:zip_tax_rate, country: "US", state: "CA", zip_code: nil, combined_rate: 0.01, is_seller_responsible: true)
described_class.new.perform
expect(zip_tax_rate.reload.combined_rate).to eq(0.01)
end
it "updates rates for Canada provinces if there are any new updates" do
zip_tax_rate = create(:zip_tax_rate, country: "CA", state: "QC", combined_rate: 0.01)
described_class.new.perform
expect(zip_tax_rate.reload.combined_rate).to eq(0.1498)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/block_stripe_suspected_fraudulent_payments_worker_spec.rb | spec/sidekiq/block_stripe_suspected_fraudulent_payments_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BlockStripeSuspectedFraudulentPaymentsWorker do
describe "#perform" do
before do
@payload = JSON.parse(file_fixture("helper_conversation_created.json").read)["payload"]
admin = create(:admin_user)
stub_const("GUMROAD_ADMIN_ID", admin.id)
end
it "parses payment records from Stripe emails" do
records = described_class.new.send(:parse_payment_records_from_body, @payload["body"])
expect(records.length).to eq(20)
expect(records.first).to eq("ch_2LBu5J9e1RjUNIyY1Q3Kw06Q")
expect(records.last).to eq("ch_2LBu5X9e1RjUNIyY1PerqPRf")
end
it "blocks the listed purchases, adds a note, and closes the ticket" do
purchases = []
charge_ids = ["ch_2LBu5J9e1RjUNIyY1Q3Kw06Q", "ch_2LBu5X9e1RjUNIyY1PerqPRf"]
charge_ids.each do |charge_id|
purchases << create(:purchase, stripe_transaction_id: charge_id, stripe_fingerprint: SecureRandom.hex, purchaser: create(:user))
expect(purchases.last.buyer_blocked?).to eq(false)
allow(ChargeProcessor).to receive(:refund!)
.with(StripeChargeProcessor.charge_processor_id, charge_id, hash_including(is_for_fraud: true))
.and_return(create(:refund, purchase: purchases.last))
end
expect_any_instance_of(Helper::Client).to receive(:add_note).with(conversation_id: @payload["conversation_id"], message: described_class::HELPER_NOTE_CONTENT)
expect_any_instance_of(Helper::Client).to receive(:close_conversation).with(conversation_id: @payload["conversation_id"])
described_class.new.perform(@payload["conversation_id"], @payload["email_from"], @payload["body"])
purchases.each do |purchase|
purchase.reload
expect(purchase.buyer_blocked?).to eq(true)
expect(purchase.is_buyer_blocked_by_admin?).to eq(true)
expect(purchase.comments.where(content: "Buyer blocked by Helper webhook").count).to eq(1)
expect(purchase.purchaser.comments.where(content: "Buyer blocked by Helper webhook").count).to eq(1)
end
end
context "when email is not from Stripe" do
it "does not trigger any processing" do
expect_any_instance_of(Helper::Client).not_to receive(:add_note)
expect_any_instance_of(Helper::Client).not_to receive(:close_conversation)
described_class.new.perform(@payload["conversation_id"], "not_stripe@example.com", @payload["body"])
end
end
context "when email body does not contain any transaction IDs" do
it "does not trigger any processing" do
expect_any_instance_of(Helper::Client).not_to receive(:add_note)
expect_any_instance_of(Helper::Client).not_to receive(:close_conversation)
described_class.new.perform(@payload["conversation_id"], @payload["email_from"], "Some body")
end
end
context "when there is an error" do
it "notifies Bugsnag" do
expect(Bugsnag).to receive(:notify).exactly(:once)
described_class.new.perform(@payload["conversation_id"], @payload["email_from"], nil)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/delete_old_versions_records_worker_spec.rb | spec/sidekiq/delete_old_versions_records_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DeleteOldVersionsRecordsWorker, :versioning do
describe "#perform" do
it "deletes targeted rows" do
stub_const("#{described_class}::MAX_ALLOWED_ROWS", 8)
stub_const("#{described_class}::DELETION_BATCH_SIZE", 1)
create_list(:user, 10)
# Deletes 10 versions for the users and 10 versions for the refund policies
expect(PaperTrail::Version.count).to eq(20)
described_class.new.perform
expect(PaperTrail::Version.count).to eq(8)
end
it "does not fail when there are no version records" do
expect(described_class.new.perform).to eq(nil)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_workflow_post_emails_job_spec.rb | spec/sidekiq/send_workflow_post_emails_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SendWorkflowPostEmailsJob, :freeze_time do
before do
@seller = create(:named_user)
@workflow = create(:audience_workflow, seller: @seller)
@post = create(:audience_post, :published, workflow: @workflow, seller: @seller)
@post_rule = create(:post_rule, installment: @post, delayed_delivery_time: 1.day)
end
describe "#perform with a follower" do
before do
@basic_follower = create(:active_follower, user: @seller, created_at: 2.day.ago)
end
it "ignores deleted workflows" do
@workflow.mark_deleted!
described_class.new.perform(@post.id)
expect(SendWorkflowInstallmentWorker.jobs).to be_empty
end
it "ignores deleted posts" do
@post.mark_deleted!
described_class.new.perform(@post.id)
expect(SendWorkflowInstallmentWorker.jobs).to be_empty
end
it "ignores unpublished posts" do
@post.update!(published_at: nil)
described_class.new.perform(@post.id)
expect(SendWorkflowInstallmentWorker.jobs).to be_empty
end
it "only considers audience members created after the earliest_valid_time" do
described_class.new.perform(@post.id, 1.day.ago.iso8601)
expect(SendWorkflowInstallmentWorker.jobs).to be_empty
described_class.new.perform(@post.id, 3.days.ago.iso8601)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, nil, @basic_follower.id, nil)
# does not limit when earliest_valid_time is nil
SendWorkflowInstallmentWorker.jobs.clear
described_class.new.perform(@post.id, nil)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, nil, @basic_follower.id, nil)
end
end
describe "#perform" do
context "for different post types" do
before do
@products = []
@products << create(:product, user: @seller, name: "Product one")
@products << create(:product, user: @seller, name: "Product two")
category = create(:variant_category, link: @products[0])
@variants = create_list(:variant, 2, variant_category: category)
@products << create(:product, :is_subscription, user: @seller, name: "Product three")
@sales = []
@sales << create(:purchase, link: @products[0], created_at: 7.days.ago)
@sales << create(:purchase, link: @products[1], email: @sales[0].email, created_at: 6.days.ago)
@sales << create(:purchase, link: @products[0], created_at: 5.days.ago)
@sales << create(:purchase, link: @products[1], variant_attributes: [@variants[0]], created_at: 4.days.ago)
@sales << create(:purchase, link: @products[1], variant_attributes: [@variants[1]], created_at: 3.days.ago)
@sales << create(:membership_purchase, link: @products[2], created_at: 6.hours.ago)
@followers = []
@followers << create(:active_follower, user: @seller, created_at: 5.days.ago)
@followers << create(:active_follower, user: @seller, email: @sales[0].email, created_at: 5.hours.ago)
@affiliates = []
@affiliates << create(:direct_affiliate, seller: @seller, send_posts: true, created_at: 4.hours.ago)
@affiliates[0].products << @products[0]
@affiliates[0].products << @products[1]
# Basic check for working recipient filtering.
# The details of it are tested in the Installment model specs.
create(:deleted_follower, user: @seller)
create(:purchase, link: @products[0], can_contact: false)
create(:direct_affiliate, seller: @seller, send_posts: false).products << @products[0]
create(:membership_purchase, email: @sales[5].email, link: @products[2], subscription: @sales[5].subscription, is_original_subscription_purchase: false)
end
it "when product_type? is true, it enqueues the expected emails at the right times" do
@post.update!(installment_type: Installment::PRODUCT_TYPE, link: @products[0], bought_products: [@products[0].unique_permalink])
described_class.new.perform(@post.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(2)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, @sales[0].id, nil, nil).immediately
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, @sales[2].id, nil, nil).immediately
SendWorkflowInstallmentWorker.jobs.clear
@post.update!(installment_type: Installment::PRODUCT_TYPE, link: @products[2], bought_products: [@products[2].unique_permalink])
described_class.new.perform(@post.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(1)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, @sales[5].id, nil, nil).at(18.hours.from_now)
end
it "when variant_type? is true, it sends the expected emails at the right times" do
@post.update!(installment_type: Installment::VARIANT_TYPE, link: @products[1], base_variant: @variants[0], bought_variants: [@variants[0].external_id])
described_class.new.perform(@post.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(1)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, @sales[3].id, nil, nil).immediately
end
it "when seller_type? is true, it sends the expected emails at the right times" do
@post.update!(installment_type: Installment::SELLER_TYPE)
described_class.new.perform(@post.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(5)
[1, 2, 3, 4].each do |sale_index|
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, @sales[sale_index].id, nil, nil).immediately
end
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, @sales[5].id, nil, nil).at(18.hours.from_now)
end
it "when follower_type? is true, it sends the expected emails at the right times" do
@post.update!(installment_type: Installment::FOLLOWER_TYPE)
described_class.new.perform(@post.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(2)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, nil, @followers[0].id, nil).immediately
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, nil, @followers[1].id, nil).at(19.hours.from_now)
end
it "when affiliate_type? is true, it sends the expected emails at the right times" do
@post.update!(installment_type: Installment::AFFILIATE_TYPE, affiliate_products: [@products[0].unique_permalink])
described_class.new.perform(@post.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(1)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, nil, nil, @affiliates[0].id).at(20.hours.from_now)
end
it "when audience_type? is true, it sends the expected emails at the right times" do
described_class.new.perform(@post.id)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(7)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, nil, @followers[0].id, nil).immediately
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, nil, @followers[1].id, nil).at(19.hours.from_now)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, nil, nil, @affiliates[0].id).at(20.hours.from_now)
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, @sales[2].id, nil, nil).immediately
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, @sales[3].id, nil, nil).immediately
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, @sales[4].id, nil, nil).immediately
expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@post.id, @post_rule.version, @sales[5].id, nil, nil).at(18.hours.from_now)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/charge_successful_preorders_worker_spec.rb | spec/sidekiq/charge_successful_preorders_worker_spec.rb | # frozen_string_literal: true
describe ChargeSuccessfulPreordersWorker do
describe "#perform" do
before do
@product = create(:product, price_cents: 600, is_in_preorder_state: true)
@preorder_product = create(:preorder_product_with_content, link: @product)
@preorder_product.update_attribute(:release_at, Time.current) # bypass validation
@preorder_1 = create(:preorder, preorder_link: @preorder_product, state: "authorization_failed")
@preorder_2 = create(:preorder, preorder_link: @preorder_product, state: "authorization_successful")
@preorder_3 = create(:preorder, preorder_link: @preorder_product, state: "charge_successful")
end
it "enqueues the proper preorders to be charged" do
described_class.new.perform(@preorder_product.id)
expect(ChargePreorderWorker).to have_enqueued_sidekiq_job(@preorder_2.id)
end
it "schedules a Sidekiq job to send preorder seller summary" do
described_class.new.perform(@preorder_product.id)
expect(SendPreorderSellerSummaryWorker).to have_enqueued_sidekiq_job(@preorder_product.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/expiring_credit_card_message_worker_spec.rb | spec/sidekiq/expiring_credit_card_message_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ExpiringCreditCardMessageWorker, :vcr do
let(:cutoff_date) { Date.today.at_beginning_of_month.next_month }
let(:expiring_cc_user) { create(:user, credit_card: create(:credit_card, expiry_month: cutoff_date.month, expiry_year: cutoff_date.year)) }
let(:valid_cc_user) { create(:user, credit_card: create(:credit_card, expiry_month: cutoff_date.month, expiry_year: cutoff_date.year + 1)) }
context "with subscription" do
let!(:subscription) { create(:subscription, user: expiring_cc_user, credit_card_id: expiring_cc_user.credit_card_id) }
it "does enqueue the correct users for expiring credit card messages" do
expect do
ExpiringCreditCardMessageWorker.new.perform
end.to have_enqueued_mail(CustomerLowPriorityMailer, :credit_card_expiring_membership).with(subscription.id)
end
it "does not enqueue users with blank emails" do
expect_any_instance_of(User).to receive(:form_email).at_least(1).times.and_return(nil)
expect do
ExpiringCreditCardMessageWorker.new.perform
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :credit_card_expiring_membership).with(subscription.id)
end
it "does enqueue twice the expiring credit card messages with multiple subscriptions" do
create(:subscription, user: expiring_cc_user, credit_card_id: expiring_cc_user.credit_card_id)
expect do
ExpiringCreditCardMessageWorker.new.perform
end.to have_enqueued_mail(CustomerLowPriorityMailer, :credit_card_expiring_membership).twice
end
context "when subscription is lapsed" do
it "does not enqueue membership emails" do
subscription = create(:subscription, user: expiring_cc_user, credit_card_id: expiring_cc_user.credit_card_id, cancelled_at: 1.day.ago)
expect do
ExpiringCreditCardMessageWorker.new.perform
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :credit_card_expiring_membership).with(subscription.id)
end
end
context "when subscription is pending cancellation" do
it "does not enqueue membership emails" do
subscription = create(:subscription, user: expiring_cc_user, credit_card_id: expiring_cc_user.credit_card_id, cancelled_at: 1.day.from_now)
expect do
ExpiringCreditCardMessageWorker.new.perform
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :credit_card_expiring_membership).with(subscription.id)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/rename_product_file_worker_spec.rb | spec/sidekiq/rename_product_file_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RenameProductFileWorker do
before do
@product_file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png")
end
describe "#perform" do
context "when file is present in CDN" do
it "renames the file" do
expect_any_instance_of(ProductFile).to receive(:rename_in_storage)
described_class.new.perform(@product_file.id)
end
end
context "when file is deleted from CDN" do
it "doesn't rename the file" do
@product_file.mark_deleted_from_cdn
expect_any_instance_of(ProductFile).not_to receive(:rename_in_storage)
described_class.new.perform(@product_file.id)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/mass_refund_for_fraud_job_spec.rb | spec/sidekiq/mass_refund_for_fraud_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe MassRefundForFraudJob do
let(:admin_user) { create(:admin_user) }
let(:product) { create(:product) }
describe "#perform" do
let(:purchase1) { instance_double(Purchase, external_id: "ext-1", link_id: product.id) }
let(:purchase2) { instance_double(Purchase, external_id: "ext-2", link_id: product.id) }
let(:external_ids) { [purchase1.external_id, purchase2.external_id] }
before do
allow(Purchase).to receive(:find_by_external_id).with(purchase1.external_id).and_return(purchase1)
allow(Purchase).to receive(:find_by_external_id).with(purchase2.external_id).and_return(purchase2)
end
it "processes each purchase and logs results" do
expect(purchase1).to receive(:refund_for_fraud_and_block_buyer!).with(admin_user.id)
expect(purchase2).to receive(:refund_for_fraud_and_block_buyer!).with(admin_user.id)
expect(Rails.logger).to receive(:info).with(/Mass fraud refund completed for product #{product.id}: 2 succeeded, 0 failed/)
described_class.new.perform(product.id, external_ids, admin_user.id)
end
it "handles missing purchases gracefully" do
missing_external_id = "nonexistent"
external_ids_with_missing = [purchase1.external_id, missing_external_id]
expect(purchase1).to receive(:refund_for_fraud_and_block_buyer!).with(admin_user.id)
allow(Purchase).to receive(:find_by_external_id).with(missing_external_id).and_return(nil)
expect(Rails.logger).to receive(:info).with(/Mass fraud refund completed for product #{product.id}: 1 succeeded, 1 failed/)
described_class.new.perform(product.id, external_ids_with_missing, admin_user.id)
end
it "handles refund errors and continues processing" do
expect(purchase1).to receive(:refund_for_fraud_and_block_buyer!).with(admin_user.id).and_raise(StandardError.new("Refund failed"))
expect(purchase2).to receive(:refund_for_fraud_and_block_buyer!).with(admin_user.id)
expect(Bugsnag).to receive(:notify).with(instance_of(StandardError))
expect(Rails.logger).to receive(:info).with(/Mass fraud refund completed for product #{product.id}: 1 succeeded, 1 failed/)
described_class.new.perform(product.id, external_ids, admin_user.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/log_sendgrid_event_worker_spec.rb | spec/sidekiq/log_sendgrid_event_worker_spec.rb | # frozen_string_literal: true
describe LogSendgridEventWorker do
describe "#perform" do
let(:email) { "example@example.com" }
let(:email_digest) { Digest::SHA1.hexdigest(email).first(12) }
let(:event_timestamp) { 5.minutes.from_now }
before do
Feature.activate(:log_email_events)
EmailEvent.log_send_events(email, Time.current)
end
it "logs open event" do
params = { "_json" => [{ "event" => "open", "email" => email, "timestamp" => event_timestamp }] }
described_class.new.perform(params)
record = EmailEvent.find_by(email_digest:)
expect(record.open_count).to eq 1
expect(record.unopened_emails_count).to eq 0
expect(record.first_unopened_email_sent_at).to be_nil
expect(record.last_opened_at.to_i).to eq event_timestamp.to_i
end
it "logs click event" do
params = { "_json" => [{ "event" => "click", "email" => email, "timestamp" => event_timestamp }] }
described_class.new.perform(params)
record = EmailEvent.find_by(email_digest:)
expect(record.click_count).to eq 1
expect(record.last_clicked_at.to_i).to eq event_timestamp.to_i
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/analyze_file_worker_spec.rb | spec/sidekiq/analyze_file_worker_spec.rb | # frozen_string_literal: true
describe AnalyzeFileWorker do
describe "#perform" do
before do
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("staging"))
end
it "calls analyze for product file when no class name is provided" do
product_file = create(:product_file)
expect_any_instance_of(ProductFile).to receive(:analyze)
AnalyzeFileWorker.new.perform(product_file.id)
end
it "calls analyze for video files" do
video_file = create(:video_file)
expect_any_instance_of(VideoFile).to receive(:analyze)
AnalyzeFileWorker.new.perform(video_file.id, VideoFile.name)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/transcode_video_for_streaming_worker_spec.rb | spec/sidekiq/transcode_video_for_streaming_worker_spec.rb | # frozen_string_literal: true
describe TranscodeVideoForStreamingWorker do
describe "#perform" do
let(:product) { create(:product_with_video_file) }
context "when the product file is not transcodable" do
let(:product_file) { product.product_files.first }
it "notifies the creator and does not create a transcoding job" do
expect(product_file.transcodable?).to be(false)
expect do
described_class.new.perform(product_file.id)
end
.to change { TranscodedVideo.count }.by(0)
.and have_enqueued_mail(ContactingCreatorMailer, :video_transcode_failed).with(product_file.id)
end
it "does nothing if `#attempt_to_transcode?` returns `false`" do
create(:transcoded_video, streamable: product_file, original_video_key: product_file.s3_key, state: "completed")
expect(ContactingCreatorMailer).to_not receive(:video_transcode_failed)
expect(product_file.transcodable?).to be(false)
expect(product_file.attempt_to_transcode?).to be(false)
expect do
described_class.new.perform(product_file.id)
end.to_not change { TranscodedVideo.count }
end
end
context "when the product file is transcodable" do
let(:product_file) do
product_file = product.product_files.first
product_file.update!(width: 854, height: 480)
product_file
end
before do
expect(product_file.transcodable?).to be(true)
mediaconvert_client_double = double("mediaconvert_client")
allow(mediaconvert_client_double).to receive(:job).and_return(OpenStruct.new({ id: "abc-123" }))
allow_any_instance_of(Aws::MediaConvert::Client).to receive(:create_job).and_return(mediaconvert_client_double)
end
it "does nothing when the product file is deleted" do
product_file.delete!
expect do
described_class.new.perform(product_file.id)
end.to_not change { TranscodedVideo.count }
end
it "creates a transcoded_video record and marks it as completed if there's already another duplicate completed one" do
completed_transcode = create(:transcoded_video, original_video_key: product_file.s3_key, transcoded_video_key: product_file.s3_key + ".transcoded", state: "completed")
expect_any_instance_of(Aws::MediaConvert::Client).not_to receive(:create_job)
expect do
described_class.new.perform(product_file.id)
end.to change { TranscodedVideo.count }.by(1)
transcoded_video = TranscodedVideo.last!
expect(transcoded_video.original_video_key).to eq(completed_transcode.original_video_key)
expect(transcoded_video.transcoded_video_key).to eq(completed_transcode.transcoded_video_key)
end
it "creates a transcoded_video but doesn't process it if there's already another duplicate processing one" do
processing_transcode = create(:transcoded_video, original_video_key: product_file.s3_key, transcoded_video_key: product_file.s3_key + ".transcoded", state: "processing")
expect_any_instance_of(Aws::MediaConvert::Client).not_to receive(:create_job)
expect do
described_class.new.perform(product_file.id)
end.to change { TranscodedVideo.count }.by(1)
transcoded_video = TranscodedVideo.last!
expect(transcoded_video.original_video_key).to eq(processing_transcode.original_video_key)
expect(transcoded_video.streamable).to eq(product_file)
end
it "transcodes the video and does not send the transcoding error email", :vcr do
expect(ContactingCreatorMailer).to_not receive(:video_transcode_failed)
expect do
described_class.new.perform(product_file.id)
end.to change { TranscodedVideo.count }.by(1)
end
it "does nothing if `#attempt_to_transcode?` returns `false`" do
create(:transcoded_video, streamable: product_file, original_video_key: product_file.s3_key, state: "completed")
expect(ContactingCreatorMailer).to_not receive(:video_transcode_failed)
expect(product_file.attempt_to_transcode?).to be(false)
expect do
described_class.new.perform(product_file.id)
end.to_not change { TranscodedVideo.count }
end
it "marks the existing transcoded video still processing as failed, when `allowed_when_processing` is true" do
transcoded_video = create(:transcoded_video, streamable: product_file, original_video_key: product_file.s3_key, state: "processing")
expect_any_instance_of(Aws::MediaConvert::Client).to receive(:create_job)
expect do
described_class.new.perform(product_file.id, ProductFile.name, "mediaconvert", true)
end.to change { TranscodedVideo.count }
expect(transcoded_video.reload.state).to eq("error")
end
it "does not mark the existing transcoded video still processing as failed, when `allowed_when_processing` is false" do
transcoded_video = create(:transcoded_video, streamable: product_file, original_video_key: product_file.s3_key, state: "processing")
expect do
described_class.new.perform(product_file.id)
end.to_not change { TranscodedVideo.count }
expect(transcoded_video.reload.state).to eq("processing")
end
it "transcodes the video when input video key is more than 255 bytes long", :vcr do
product_file.update!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/Identify+Relevant+important+FB+Groups+(Not+just+your+FB+Page)+of+your+geographical+location+area+and+post+OFFERS%2C+social+media+posts+there+also+to+get+Branding+%26+Visibility+%2B+more+likes+on+FB+Page+and+to+get+some+more+traction+from+your+audience+without+much+of+a+hassle.mov")
expect do
expect do
described_class.new.perform(product_file.id)
end.to_not raise_error
end.to change { TranscodedVideo.count }.by(1)
expect(TranscodedVideo.last.original_video_key).to eq(product_file.s3_key)
expect(TranscodedVideo.last.transcoded_video_key).to eq("specs/Identify+Relevant+important+FB+Groups+(Not+just+your+FB+Page)+of+your+geographical+location+area+and+post+OFFERS%2C+social+media+posts+there+also+to+get+Branding+%26+Visibility+%2B+more+likes+on+FB+Page+and+to+get+some+more+traction+from+your+audience+without+much+of+a+hassle/hls/")
end
describe "transcode using MediaConvert" do
before do
product_file.update!(height: 1080)
@mediaconvert_job_params = {
queue: MEDIACONVERT_QUEUE,
role: MEDIACONVERT_ROLE,
settings: {
output_groups: [
{
name: "Apple HLS",
output_group_settings: {
type: "HLS_GROUP_SETTINGS",
hls_group_settings: {
segment_length: 10,
min_segment_length: 0,
destination: "s3://#{S3_BUCKET}/specs/ScreenRecording/hls/index",
destination_settings: {
s3_settings: {
access_control: {
canned_acl: "PUBLIC_READ"
}
}
}
}
},
outputs: [
{
preset: "hls_480p",
name_modifier: "_480p"
},
{
preset: "hls_1080p",
name_modifier: "_1080p"
}
]
}
],
inputs: [
{
audio_selectors: {
"Audio Selector 1": {
default_selection: "DEFAULT"
}
},
video_selector: {
rotate: "AUTO"
},
file_input: "s3://#{S3_BUCKET}/specs/ScreenRecording.mov"
}
]
},
acceleration_settings: {
mode: "DISABLED"
}
}
end
it "creates MediaConvert job and a TranscodedVideo object" do
expect_any_instance_of(Aws::MediaConvert::Client).to receive(:create_job).with(@mediaconvert_job_params)
expect do
described_class.new.perform(product_file.id)
end.to change { TranscodedVideo.count }.by(1)
expect(TranscodedVideo.last.job_id).to eq "abc-123"
expect(TranscodedVideo.last.transcoded_video_key).to eq "specs/ScreenRecording/hls/"
end
context "with GRMC", :freeze_time do
before do
allow(GlobalConfig).to receive(:get).with("GRMC_API_KEY").and_return("test_api_key")
end
context "when request to GRMC is successful" do
before do
stub_request(:post, described_class::GRMC_ENDPOINT)
.to_return(status: 200, body: { job_id: "grmc-123" }.to_json, headers: { "Content-Type" => "application/json" })
end
it "creates a GRMC job, a TranscodedVideo object, and schedules a retry with AWS MediaConvert" do
expect_any_instance_of(Aws::MediaConvert::Client).not_to receive(:create_job)
expect do
described_class.new.perform(product_file.id)
end.to change { TranscodedVideo.count }.by(1)
transcoded_video = TranscodedVideo.last!
expect(transcoded_video.job_id).to eq "grmc-123"
expect(transcoded_video.transcoded_video_key).to eq "specs/ScreenRecording/hls/"
expect(transcoded_video.via_grmc).to be(true)
expect(transcoded_video.streamable).to eq(product_file)
expect(described_class).to have_enqueued_sidekiq_job(product_file.id, ProductFile.name, described_class::MEDIACONVERT, true).in(24.hours)
end
end
context "when request to GRMC is not successful" do
before do
stub_request(:post, described_class::GRMC_ENDPOINT)
.to_return(status: 429)
end
it "creates MediaConvert job and a TranscodedVideo object" do
expect_any_instance_of(Aws::MediaConvert::Client).to receive(:create_job).with(@mediaconvert_job_params)
expect do
described_class.new.perform(product_file.id)
end.to change { TranscodedVideo.count }.by(1)
transcoded_video = TranscodedVideo.last!
expect(transcoded_video.job_id).to eq "abc-123"
expect(transcoded_video.transcoded_video_key).to eq "specs/ScreenRecording/hls/"
expect(transcoded_video.via_grmc).to be(false)
expect(transcoded_video.streamable).to eq(product_file)
end
end
end
it "transcodes the video and does not send the transcoding error email", :vcr do
expect(ContactingCreatorMailer).to_not receive(:video_transcode_failed)
expect do
described_class.new.perform(product_file.id)
end.to change { TranscodedVideo.count }.by(1)
end
it "does nothing if `#attempt_to_transcode?` returns `false`" do
create(:transcoded_video, streamable: product_file, original_video_key: product_file.s3_key, state: "completed")
expect(ContactingCreatorMailer).to_not receive(:video_transcode_failed)
expect(product_file.attempt_to_transcode?).to be(false)
expect do
described_class.new.perform(product_file.id)
end.to_not change { TranscodedVideo.count }
end
context "when transcoder param is set to ets" do
before do
ets_client_double = double("ets_client")
allow(ets_client_double).to receive(:data).and_return(OpenStruct.new({ job: { id: 1 } }))
allow_any_instance_of(Aws::ElasticTranscoder::Client).to receive(:create_job).and_return(ets_client_double)
end
it "transcodes the video using ETS" do
expect_any_instance_of(Aws::ElasticTranscoder::Client).to receive(:create_job)
ets_transcoder = described_class::ETS
described_class.new.perform(product_file.id, ProductFile.name, ets_transcoder)
end
end
context "when transcoder param is set to MediaConvert" do
it "transcodes the video using MediaConvert" do
expect_any_instance_of(Aws::MediaConvert::Client).to receive(:create_job)
mediaconvert = described_class::MEDIACONVERT
described_class.new.perform(product_file.id, ProductFile.name, mediaconvert)
end
end
end
end
describe "transcode using ETS" do
let(:product_file) { product.product_files.first }
describe "output_key_prefix" do
before do
ets_client_double = double("ets_client")
allow(ets_client_double).to receive(:data).and_return(OpenStruct.new({ job: { id: 1 } }))
allow_any_instance_of(Aws::ElasticTranscoder::Client).to receive(:create_job).and_return(ets_client_double)
@ets_transcoder = described_class::ETS
end
context "when repeated occurrences of extension is present in the filename" do
it "generates the correct output_key_prefix" do
original_video_key = "prefix/original/Ep 1.mp4 1-6 slides test.mp4 1-6 slides test.mp4 1-6 slides test.mp4"
output_prefix_key = "prefix/original/Ep 1.mp4 1-6 slides test.mp4 1-6 slides test.mp4 1-6 slides test/hls/"
expect_any_instance_of(Aws::ElasticTranscoder::Client).to receive(:create_job).with(hash_including({ output_key_prefix: output_prefix_key }))
described_class.new.create_hls_transcode_job(product_file, original_video_key, 1080, @ets_transcoder)
end
it "generates the correct output_key_prefix when filename contains multiple lines" do
original_video_key = "prefix/original/Ep 1.mp4 1-6 slides test.mp4\n 1-6 slides test.mp4\n 1-6 slides test.mp4"
output_prefix_key = "prefix/original/Ep 1.mp4 1-6 slides test.mp4\n 1-6 slides test.mp4\n 1-6 slides test/hls/"
expect_any_instance_of(Aws::ElasticTranscoder::Client).to receive(:create_job).with(hash_including({ output_key_prefix: output_prefix_key }))
described_class.new.create_hls_transcode_job(product_file, original_video_key, 1080, @ets_transcoder)
end
end
context "when repeated occurrences of extension is not present in the filename" do
it "generates the correct output_key_prefix" do
original_video_key = "prefix/original/test.mp4"
output_prefix_key = "prefix/original/test/hls/"
expect_any_instance_of(Aws::ElasticTranscoder::Client).to receive(:create_job).with(hash_including({ output_key_prefix: output_prefix_key }))
described_class.new.create_hls_transcode_job(product_file, original_video_key, 1080, @ets_transcoder)
end
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_workflow_installment_worker_spec.rb | spec/sidekiq/send_workflow_installment_worker_spec.rb | # frozen_string_literal: true
describe SendWorkflowInstallmentWorker do
before do
@product = create(:product)
end
describe "purchase_installment" do
before do
@workflow = create(:workflow, seller: @product.user, link: @product, created_at: Time.current)
@installment = create(:installment, link: @product, workflow: @workflow, published_at: Time.current)
@installment_rule = create(:installment_rule, installment: @installment, delayed_delivery_time: 1.day)
@purchase = create(:purchase, link: @product, created_at: 1.week.ago, price_cents: 100)
end
it "calls purchase mailer if same version" do
expect(PostSendgridApi).to receive(:process).with(
post: @installment,
recipients: [{ email: @purchase.email, purchase: @purchase }],
cache: {}
)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, @purchase.id, nil, nil)
end
it "does not call mailer if different version" do
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version + 1, @purchase.id, nil, nil)
end
it "does not call mailer if deleted installment" do
@installment.update_attribute(:deleted_at, Time.current)
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, @purchase.id, nil, nil)
end
it "does not call mailer if workflow is deleted" do
@workflow.update_attribute(:deleted_at, Time.current)
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, @purchase.id, nil, nil)
end
it "does not call mailer if installment is not published" do
@installment.update_attribute(:published_at, nil)
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, @purchase.id, nil, nil)
end
it "does not call mailer if installment is not found" do
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform("non-existing-installment-id", @installment_rule.version, @purchase.id, nil, nil)
end
it "does not call mailer if seller is suspended" do
admin_user = create(:admin_user)
@product.user.flag_for_fraud!(author_id: admin_user.id)
@product.user.suspend_for_fraud!(author_id: admin_user.id)
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, @purchase.id, nil, nil)
end
it "does not call any mailer if both purchase_id and follower_id are passed" do
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, @purchase.id, @purchase.id, nil)
end
it "does not call any mailer if both purchase_id and affiliate_user_id are passed" do
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, @purchase.id, nil, @purchase.id)
end
it "does not call any mailer if both follower_id and affiliate_user_id are passed" do
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, nil, @purchase.id, @purchase.id)
end
it "does not call any mailer if purchase_id, follower_id and affiliate_user_id are passed" do
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, @purchase.id, @purchase.id, @purchase.id)
end
it "does not call any mailer if neither purchase_id nor follower_id nor affiliate_user_id are passed" do
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, nil, nil, nil)
end
end
describe "follower_installment" do
before do
@user = create(:user)
@workflow = create(:workflow, seller: @user, link: nil, created_at: Time.current, workflow_type: Workflow::AUDIENCE_TYPE)
@installment = create(:follower_installment, seller: @user, workflow: @workflow, published_at: Time.current)
@installment_rule = create(:installment_rule, installment: @installment, delayed_delivery_time: 1.day)
@follower = create(:active_follower, followed_id: @user.id, email: "some@email.com")
end
it "calls follower mailer if same version" do
allow(PostSendgridApi).to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, nil, @follower.id, nil)
expect(PostSendgridApi).to have_received(:process).with(
post: @installment,
recipients: [{ email: @follower.email, follower: @follower, url_redirect: UrlRedirect.find_by(installment: @installment) }],
cache: {}
)
end
it "does not call mailer if different version" do
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version + 1, nil, @follower.id, nil)
end
it "does not call mailer if deleted installment" do
@installment.update_attribute(:deleted_at, Time.current)
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, nil, @follower.id, nil)
end
it "does not call mailer if workflow is deleted" do
@workflow.update_attribute(:deleted_at, Time.current)
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, nil, @follower.id, nil)
end
it "does not call mailer if installment is not published" do
@installment.update_attribute(:published_at, nil)
expect(PostSendgridApi).not_to receive(:process)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, nil, @follower.id, nil)
end
end
describe "member_cancellation_installment" do
before do
@creator = create(:user)
@product = create(:subscription_product, user: @creator)
@subscription = create(:subscription, link: @product, cancelled_by_buyer: true, cancelled_at: 2.days.ago, deactivated_at: 1.day.ago)
@workflow = create(:workflow, seller: @creator, link: @product, workflow_trigger: "member_cancellation")
@installment = create(:published_installment, link: @product, workflow: @workflow, workflow_trigger: "member_cancellation")
@installment_rule = create(:installment_rule, installment: @installment, delayed_delivery_time: 1.day)
@sale = create(:purchase, is_original_subscription_purchase: true, link: @product, subscription: @subscription, email: "test@gmail.com", created_at: 1.week.ago, price_cents: 100)
end
it "calls cancellation mailer if given subscription id" do
expect(PostSendgridApi).to receive(:process).with(
post: @installment,
recipients: [{ email: @sale.email, purchase: @sale, subscription: @subscription }],
cache: {}
)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, nil, nil, nil, @subscription.id)
end
end
it "caches template rendering" do
@workflow = create(:workflow, seller: @product.user, link: @product, created_at: Time.current)
@installment = create(:installment, link: @product, workflow: @workflow, published_at: Time.current)
@installment_rule = create(:installment_rule, installment: @installment, delayed_delivery_time: 1.day)
@purchase_1 = create(:purchase, link: @product, created_at: 1.week.ago)
@purchase_2 = create(:purchase, link: @product, created_at: 1.week.ago)
expect(PostSendgridApi).to receive(:process).with(
post: @installment,
recipients: [{ email: @purchase_1.email, purchase: @purchase_1 }],
cache: {}
).and_call_original
expect(PostSendgridApi).to receive(:process).with(
post: @installment,
recipients: [{ email: @purchase_2.email, purchase: @purchase_2 }],
cache: { @installment => anything }
).and_call_original
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, @purchase_1.id, nil, nil)
SendWorkflowInstallmentWorker.new.perform(@installment.id, @installment_rule.version, @purchase_2.id, nil, nil)
expect(PostSendgridApi.mails.size).to eq(2)
expect(PostSendgridApi.mails[@purchase_1.email]).to be_present
expect(PostSendgridApi.mails[@purchase_2.email]).to be_present
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/handle_helper_event_worker_spec.rb | spec/sidekiq/handle_helper_event_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe HandleHelperEventWorker do
include Rails.application.routes.url_helpers
let!(:params) do
{
"event": "conversation.created",
"payload": {
"conversation_id": "6d389b441fcb17378effbdc4192ee69d",
"email_id": "123",
"email_from": "user@example.com",
"subject": "Some subject",
"body": "Some body"
},
}
end
before do
@event = params[:event]
@payload = params[:payload].as_json
end
describe "#perform" do
it "triggers UnblockEmailService" do
allow_any_instance_of(HelperUserInfoService).to receive(:user_info).and_return({
user: nil,
account_infos: [],
purchase_infos: [],
recent_purchase: nil,
})
expect_any_instance_of(Helper::UnblockEmailService).to receive(:process)
expect_any_instance_of(Helper::UnblockEmailService).to receive(:replied?)
described_class.new.perform(@event, @payload)
end
context "when event is invalid" do
it "does not trigger UnblockEmailService" do
expect_any_instance_of(Helper::UnblockEmailService).not_to receive(:process)
@event = "invalid_event"
described_class.new.perform(@event, @payload)
end
end
context "when there is no email" do
it "does not trigger UnblockEmailService" do
expect_any_instance_of(Helper::UnblockEmailService).not_to receive(:process)
@payload["email_from"] = nil
described_class.new.perform(@event, @payload)
end
end
context "when the event is for a new Stripe fraud email" do
it "triggers BlockStripeSuspectedFraudulentPaymentsWorker and skips UnblockEmailService" do
@payload["email_from"] = BlockStripeSuspectedFraudulentPaymentsWorker::STRIPE_EMAIL_SENDER
@payload["subject"] = BlockStripeSuspectedFraudulentPaymentsWorker::POSSIBLE_CONVERSATION_SUBJECTS.sample
expect_any_instance_of(BlockStripeSuspectedFraudulentPaymentsWorker).to receive(:perform).with(
@payload["conversation_id"],
@payload["email_from"],
@payload["body"]
)
expect_any_instance_of(Helper::UnblockEmailService).not_to receive(:process)
described_class.new.perform(@event, @payload)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/build_tax_rate_cache_worker_spec.rb | spec/sidekiq/build_tax_rate_cache_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BuildTaxRateCacheWorker do
describe ".perform" do
it "caches the maximum tax rate per state to be used in the product edit flow" do
create(:zip_tax_rate, combined_rate: 0.09, state: "CA")
create(:zip_tax_rate, combined_rate: 0.095, state: "CA")
create(:zip_tax_rate, combined_rate: 0.1, state: "CA")
create(:zip_tax_rate, combined_rate: 0.08, state: "TX")
# Show it does not fail for nil states (VAT rates)
create(:zip_tax_rate, combined_rate: 0.08, state: nil, zip_code: nil, country: "DE")
create(:zip_tax_rate, combined_rate: 0.08, state: nil, zip_code: nil, country: "GB")
described_class.new.perform
expect(ZipTaxRate.where(state: "WA").first).to be_nil
us_tax_cache_namespace = Redis::Namespace.new(:max_tax_rate_per_state_cache_us, redis: $redis)
expect(us_tax_cache_namespace.get("US_CA")).to eq("0.1")
expect(us_tax_cache_namespace.get("US_TX")).to eq("0.08")
expect(us_tax_cache_namespace.get("US_WA")).to eq(nil)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/delete_product_rich_content_worker_spec.rb | spec/sidekiq/delete_product_rich_content_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DeleteProductRichContentWorker do
describe "#perform", :sidekiq_inline, :elasticsearch_wait_for_refresh do
context "without versions" do
before do
@product_rich_content = create(:product_rich_content, entity: product, description: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Hello" }] }])
end
context "when product is deleted" do
let(:product) { create(:product, deleted_at: 1.minute.ago) }
it "deletes the product's rich content" do
expect do
described_class.new.perform(product.id)
end.to change { product.alive_rich_contents.count }.by(-1)
end
end
context "when product is alive" do
let(:product) { create(:product) }
it "does not delete any rich content objects" do
expect do
described_class.new.perform(product.id)
end.to_not change { product.alive_rich_contents.count }
end
end
end
context "with versions" do
let(:product) { create(:product) }
let(:variant_category) { create(:variant_category, link: product) }
context "when versions are deleted" do
before do
@version_1 = create(:variant, variant_category:, name: "Version 1", deleted_at: 1.minute.ago)
@version_2 = create(:variant, variant_category:, name: "Version 2", deleted_at: 1.minute.ago)
@version_3 = create(:variant, variant_category:, name: "Version 3")
create(:rich_content, entity: @version_1, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is Version 1 content", "type" => "text" }] }])
create(:rich_content, entity: @version_2, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is Version 2 content", "type" => "text" }] }])
create(:rich_content, entity: @version_3, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is Version 3 content", "type" => "text" }] }])
create(:purchase, link: product, variant_attributes: [@version_1])
end
it "soft-deletes rich content from variants" do
freeze_time do
expect do
described_class.new.perform(product.id)
end.to change { RichContent.count }.by(0)
.and change { RichContent.alive.count }.by(-2)
expect(@version_1.rich_contents.count).to eq(1)
expect(@version_1.alive_rich_contents.count).to eq(0)
expect(@version_2.rich_contents.count).to eq(1)
expect(@version_2.alive_rich_contents.count).to eq(0)
expect(@version_3.rich_contents.count).to eq(1)
expect(@version_3.alive_rich_contents.count).to eq(1)
end
end
end
context "when versions are alive" do
before do
@version = create(:variant, variant_category:, name: "Version")
create(:rich_content, entity: @version, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is Version content", "type" => "text" }] }])
end
it "does not delete any rich content objects" do
expect do
described_class.new.perform(product.id)
end.to change { RichContent.count }.by(0)
.and change { @version.alive_rich_contents.count }.by(0)
end
end
end
context "for tiered memberships" do
let(:product) { create(:membership_product) }
let(:variant_category) { product.tier_category }
context "when tiers are deleted" do
before do
@version_1 = variant_category.variants.first
@version_1.update!(deleted_at: 1.minute.ago)
@version_2 = create(:variant, variant_category:, name: "Tier 2", deleted_at: 1.minute.ago)
@version_3 = create(:variant, variant_category:, name: "Version 3")
@rich_content = create(:rich_content, entity: @version_1, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is Tier 1 content", "type" => "text" }] }])
create(:rich_content, entity: @version_2, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is Tier 2 content", "type" => "text" }] }])
create(:rich_content, entity: @version_3, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is Tier 3 content", "type" => "text" }] }])
create(:purchase, link: product, variant_attributes: [@version_1])
end
it "soft-deletes rich content from tiers" do
freeze_time do
expect do
described_class.new.perform(product.id)
end.to change { RichContent.count }.by(0)
.and change { RichContent.alive.count }.by(-2)
expect(@rich_content.reload.deleted_at).to eq(Time.current)
expect(@version_1.rich_contents.count).to eq(1)
expect(@version_1.alive_rich_contents.count).to eq(0)
expect(@version_2.rich_contents.count).to eq(1)
expect(@version_2.alive_rich_contents.count).to eq(0)
expect(@version_3.rich_contents.count).to eq(1)
expect(@version_3.alive_rich_contents.count).to eq(1)
end
end
end
context "when versions are alive" do
before do
@version_1 = create(:variant, variant_category:, name: "Version 1")
@version_2 = create(:variant, variant_category:, name: "Version 2")
create(:rich_content, entity: @version_1, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is Version 1 content", "type" => "text" }] }])
create(:rich_content, entity: @version_2, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is Version 2 content", "type" => "text" }] }])
end
it "does not delete any rich content objects" do
expect do
described_class.new.perform(product.id)
end.to_not change { RichContent.count }
expect(@version_1.alive_rich_contents.count).to eq(1)
expect(@version_2.alive_rich_contents.count).to eq(1)
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/low_balance_fraud_check_worker_spec.rb | spec/sidekiq/low_balance_fraud_check_worker_spec.rb | # frozen_string_literal: true
describe LowBalanceFraudCheckWorker do
describe "#perform" do
before do
@purchase = create(:purchase)
end
it "invokes .check_for_low_balance_and_probate for the seller" do
expect_any_instance_of(User).to receive(:check_for_low_balance_and_probate)
described_class.new.perform(@purchase.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/process_payment_worker_spec.rb | spec/sidekiq/process_payment_worker_spec.rb | # frozen_string_literal: true
describe ProcessPaymentWorker do
describe "#perform" do
it "does nothing if the payment is not in processing state" do
expect(StripePayoutProcessor).not_to receive(:process_payments)
ProcessPaymentWorker.new.perform(create(:payment, state: "creating").id)
ProcessPaymentWorker.new.perform(create(:payment, state: "unclaimed").id)
ProcessPaymentWorker.new.perform(create(:payment, state: "failed").id)
ProcessPaymentWorker.new.perform(create(:payment, state: "completed", txn_id: "dummy", processor_fee_cents: 1).id)
ProcessPaymentWorker.new.perform(create(:payment, state: "reversed").id)
ProcessPaymentWorker.new.perform(create(:payment, state: "returned").id)
ProcessPaymentWorker.new.perform(create(:payment, state: "cancelled").id)
end
it "processes the payment if it is in processing state" do
payment = create(:payment, processor: "STRIPE", state: "processing")
expect(StripePayoutProcessor).to receive(:process_payments).with([payment])
ProcessPaymentWorker.new.perform(payment.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/review_reminder_job_spec.rb | spec/sidekiq/review_reminder_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ReviewReminderJob do
let(:purchase) { create(:purchase) }
it "sends an email" do
expect do
described_class.new.perform(purchase.id)
end.to have_enqueued_mail(CustomerLowPriorityMailer, :purchase_review_reminder).with(purchase.id)
end
context "purchase has a review" do
before { purchase.product_review = create(:product_review) }
it "does not send an email" do
expect do
described_class.new.perform(purchase.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :purchase_review_reminder)
end
end
context "purchase was refunded" do
before { purchase.update!(stripe_refunded: true) }
it "does not send an email" do
expect do
described_class.new.perform(purchase.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :purchase_review_reminder)
end
end
context "purchase was charged back" do
before { purchase.update!(chargeback_date: Time.current) }
it "does not send an email" do
expect do
described_class.new.perform(purchase.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :purchase_review_reminder)
end
end
context "purchase was chargeback reversed" do
before { purchase.update!(chargeback_date: Time.current, chargeback_reversed: true) }
it "sends an email" do
expect do
described_class.new.perform(purchase.id)
end.to have_enqueued_mail(CustomerLowPriorityMailer, :purchase_review_reminder).with(purchase.id)
end
end
context "purchaser opted out of review reminders" do
before { purchase.update!(purchaser: create(:user, opted_out_of_review_reminders: true)) }
it "does not send an email" do
expect do
described_class.new.perform(purchase.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :purchase_review_reminder)
end
end
it "does not send duplicate emails" do
expect do
described_class.new.perform(purchase.id)
described_class.new.perform(purchase.id)
end.to have_enqueued_mail(CustomerLowPriorityMailer, :purchase_review_reminder).with(purchase.id).once
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/annual_payout_export_worker_spec.rb | spec/sidekiq/annual_payout_export_worker_spec.rb | # frozen_string_literal: true
describe AnnualPayoutExportWorker do
describe ".perform" do
let!(:year) { 2019 }
before do
@user = create(:user)
end
context "when send_email argument is true" do
it "sends an email to the creator" do
allow_any_instance_of(Exports::Payouts::Annual).to receive(:perform).and_return(csv_file: temp_csv_file, total_amount: 100)
expect do
AnnualPayoutExportWorker.new.perform(@user.id, year, true)
end.to change { ActionMailer::Base.deliveries.count }.by(1)
.and change { @user.reload.annual_reports.count }.by(1)
mail = ActionMailer::Base.deliveries.last
expect(mail.body.encoded).to include("In 2019 you made $100 on Gumroad.")
expect(mail.body.encoded).to include("Good luck in 2020!")
end
it "does not send an email if payout amount is zero" do
allow_any_instance_of(Exports::Payouts::Annual).to receive(:perform).and_return(csv_file: temp_csv_file, total_amount: 0)
expect do
AnnualPayoutExportWorker.new.perform(@user.id, year, true)
end.to change { ActionMailer::Base.deliveries.count }.by(0)
.and change { @user.reload.annual_reports.count }.by(0)
end
it "does not send an email if payout amount is negative" do
allow_any_instance_of(Exports::Payouts::Annual).to receive(:perform).and_return(csv_file: temp_csv_file, total_amount: -100)
expect do
AnnualPayoutExportWorker.new.perform(@user.id, year, true)
end.to change { ActionMailer::Base.deliveries.count }.by(0)
.and change { @user.reload.annual_reports.count }.by(0)
end
it "sends an email with link" do
allow_any_instance_of(ActiveStorage::Blob).to receive(:url).and_return("http://gumroad.com")
allow_any_instance_of(Exports::Payouts::Annual).to receive(:perform).and_return(csv_file: temp_csv_file, total_amount: 100)
expect do
AnnualPayoutExportWorker.new.perform(@user.id, year, true)
end.to change { ActionMailer::Base.deliveries.count }.by(1)
.and change { @user.reload.annual_reports.count }.by(1)
mail = ActionMailer::Base.deliveries.last
expect(mail.body.encoded).to include("In 2019 you made $100 on Gumroad.")
expect(mail.body.encoded).to include("Good luck in 2020!")
expect(mail.body.encoded).to include("Please click this link ( http://gumroad.com ) to download")
end
it "fetches export data from Exports::Payouts::Annual" do
exports_double = double
expect(exports_double).to receive(:perform).and_return(csv_file: temp_csv_file, total_amount: 100)
expect(Exports::Payouts::Annual).to receive(:new).with(user: @user, year:).and_return(exports_double)
AnnualPayoutExportWorker.new.perform(@user.id, year, true)
end
it "closes the tempfile after sending an email" do
tempfile = temp_csv_file
exports_double = double
expect(exports_double).to receive(:perform).and_return(csv_file: tempfile, total_amount: 100)
expect(Exports::Payouts::Annual).to receive(:new).with(user: @user, year:).and_return(exports_double)
AnnualPayoutExportWorker.new.perform(@user.id, year, true)
expect(tempfile.closed?).to eq(true)
end
it "does not create a new annual report for user if it already exists" do
@user = create(:user, :with_annual_report, year:)
allow_any_instance_of(Exports::Payouts::Annual).to receive(:perform).and_return(csv_file: temp_csv_file, total_amount: 0)
expect do
AnnualPayoutExportWorker.new.perform(@user.id, year, true)
end.to change { @user.reload.annual_reports.count }.by(0)
end
end
context "when send_email argument is false" do
it "does not send an email to the creator and creates an annual report for user" do
allow_any_instance_of(Exports::Payouts::Annual).to receive(:perform).and_return(csv_file: temp_csv_file, total_amount: 100)
expect do
AnnualPayoutExportWorker.new.perform(@user.id, year)
end.to change { ActionMailer::Base.deliveries.count }.by(0)
.and change { @user.reload.annual_reports.count }.by(1)
end
it "does create an annual report for user if payout amount is zero" do
allow_any_instance_of(Exports::Payouts::Annual).to receive(:perform).and_return(csv_file: temp_csv_file, total_amount: 0)
expect do
AnnualPayoutExportWorker.new.perform(@user.id, year)
end.to change { @user.reload.annual_reports.count }.by(0)
end
it "does not create an annual report for user if payout amount is negative" do
allow_any_instance_of(Exports::Payouts::Annual).to receive(:perform).and_return(csv_file: temp_csv_file, total_amount: -100)
expect do
AnnualPayoutExportWorker.new.perform(@user.id, year)
end.to change { @user.reload.annual_reports.count }.by(0)
end
it "fetches export data from Exports::Payouts::Annual" do
exports_double = double
expect(exports_double).to receive(:perform).and_return(csv_file: temp_csv_file, total_amount: 100)
expect(Exports::Payouts::Annual).to receive(:new).with(user: @user, year:).and_return(exports_double)
AnnualPayoutExportWorker.new.perform(@user.id, year)
end
it "closes the tempfile after sending an email" do
tempfile = temp_csv_file
exports_double = double
expect(exports_double).to receive(:perform).and_return(csv_file: tempfile, total_amount: 100)
expect(Exports::Payouts::Annual).to receive(:new).with(user: @user, year:).and_return(exports_double)
AnnualPayoutExportWorker.new.perform(@user.id, year)
expect(tempfile.closed?).to eq(true)
end
end
private
def temp_csv_file
tempfile = Tempfile.new
CSV.open(tempfile, "wb") { |csv| 10.times { csv << ["Some", "CSV", "Data"] } }
tempfile.rewind
tempfile
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_memberships_price_update_emails_job_spec.rb | spec/sidekiq/send_memberships_price_update_emails_job_spec.rb | # frozen_string_literal: true
describe SendMembershipsPriceUpdateEmailsJob do
describe "#perform" do
let(:subscription) { create(:subscription) }
let(:effective_on) { rand(1..7).days.from_now.to_date }
before do
allow(CustomerLowPriorityMailer).to receive(:subscription_price_change_notification).and_return(double(deliver_later: true))
end
context "when there are applicable subscription plan changes" do
let!(:applicable_plan_change) do
create(:subscription_plan_change, for_product_price_change: true, subscription:,
effective_on:, perceived_price_cents: 20_00)
end
it "sends notification emails for applicable changes", :freeze_time do
expect do
subject.perform
end.to change { applicable_plan_change.reload.notified_subscriber_at }.from(nil).to(Time.current)
expect(CustomerLowPriorityMailer).to have_received(:subscription_price_change_notification).with(
subscription_id: subscription.id,
new_price: 20_00
)
end
it "does not send notification emails for subscriptions pending cancellation" do
subscription.update!(cancelled_at: effective_on + 1.day)
expect do
subject.perform
end.not_to change { applicable_plan_change.reload.notified_subscriber_at }
expect(CustomerLowPriorityMailer).not_to have_received(:subscription_price_change_notification)
end
it "does not send notification emails for subscriptions that are fully cancelled" do
subscription.update!(cancelled_at: 1.day.ago, deactivated_at: 1.day.ago)
expect do
subject.perform
end.not_to change { applicable_plan_change.reload.notified_subscriber_at }
expect(CustomerLowPriorityMailer).not_to have_received(:subscription_price_change_notification)
end
it "does not send notification emails for subscriptions that have ended" do
subscription.update!(ended_at: 1.day.ago, deactivated_at: 1.day.ago)
expect do
subject.perform
end.not_to change { applicable_plan_change.reload.notified_subscriber_at }
expect(CustomerLowPriorityMailer).not_to have_received(:subscription_price_change_notification)
end
it "does not send notification emails for subscriptions that have failed" do
subscription.update!(failed_at: 1.day.ago, deactivated_at: 1.day.ago)
expect do
subject.perform
end.not_to change { applicable_plan_change.reload.notified_subscriber_at }
expect(CustomerLowPriorityMailer).not_to have_received(:subscription_price_change_notification)
end
end
context "when there are non-applicable subscription plan changes" do
before do
create(:subscription_plan_change, for_product_price_change: false, subscription:, effective_on:)
create(:subscription_plan_change, for_product_price_change: true, subscription:, effective_on:, applied: true)
create(:subscription_plan_change, for_product_price_change: true, subscription:, effective_on:, deleted_at: Time.current)
create(:subscription_plan_change, for_product_price_change: true, subscription:, effective_on:, notified_subscriber_at: Time.current)
create(:subscription_plan_change, for_product_price_change: true, subscription:, effective_on: 8.days.from_now.to_date)
end
it "does not send any emails" do
subject.perform
expect(CustomerLowPriorityMailer).not_to have_received(:subscription_price_change_notification)
end
end
context "when there are no subscription plan changes" do
it "does not send any emails" do
subject.perform
expect(CustomerLowPriorityMailer).not_to have_received(:subscription_price_change_notification)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/utm_link_sale_attribution_job_spec.rb | spec/sidekiq/utm_link_sale_attribution_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UtmLinkSaleAttributionJob do
let(:browser_guid) { "test_browser_guid" }
let(:seller) { create(:user) }
let!(:product) { create(:product, user: seller) }
let!(:utm_link) { create(:utm_link, seller:) }
let!(:order) { create(:order) }
before do
Feature.activate_user(:utm_links, seller)
end
it "attributes purchases to utm link visits within the attribution window" do
purchase = create(:purchase, link: product, seller:)
order.purchases << purchase
visit = create(:utm_link_visit, utm_link:, browser_guid:, created_at: 6.days.ago)
described_class.new.perform(order.id, browser_guid)
driven_sale = utm_link.utm_link_driven_sales.sole
expect(driven_sale.purchase_id).to eq(purchase.id)
expect(driven_sale.utm_link_visit_id).to eq(visit.id)
end
it "does not attribute purchases to visits outside the attribution window" do
purchase = create(:purchase, link: product, seller:)
order.purchases << purchase
create(:utm_link_visit, utm_link:, browser_guid:, created_at: 8.days.ago)
expect do
described_class.new.perform(order.id, browser_guid)
end.not_to change { utm_link.utm_link_driven_sales.count }
end
it "only attributes purchases to the latest visit per utm link" do
purchase = create(:purchase, link: product, seller:)
order.purchases << purchase
_old_visit = create(:utm_link_visit, utm_link:, browser_guid:, created_at: 6.days.ago)
latest_visit = create(:utm_link_visit, utm_link:, browser_guid:, created_at: 1.day.ago)
described_class.new.perform(order.id, browser_guid)
driven_sale = utm_link.utm_link_driven_sales.sole
expect(driven_sale.purchase_id).to eq(purchase.id)
expect(driven_sale.utm_link_visit_id).to eq(latest_visit.id)
end
it "only attributes purchases to visits with matching browser guid" do
purchase = create(:purchase, link: product, seller:)
order.purchases << purchase
create(:utm_link_visit, utm_link:, browser_guid: "different_guid", created_at: 1.day.ago)
described_class.new.perform(order.id, browser_guid)
expect(utm_link.utm_link_driven_sales.count).to eq(0)
end
it "only attributes successful purchases" do
successful_purchase = create(:purchase, link: product, seller:)
failed_purchase = create(:failed_purchase, link: product, seller:)
unqualified_purchase = create(:purchase)
order.purchases << [successful_purchase, failed_purchase, unqualified_purchase]
visit = create(:utm_link_visit, utm_link:, browser_guid:, created_at: 1.day.ago)
described_class.new.perform(order.id, browser_guid)
driven_sale = utm_link.utm_link_driven_sales.sole
expect(driven_sale.purchase_id).to eq(successful_purchase.id)
expect(driven_sale.utm_link_visit_id).to eq(visit.id)
end
context "when utm link targets specific product" do
let(:target_product) { create(:product, user: seller) }
let(:other_product) { create(:product, user: seller) }
let(:utm_link) { create(:utm_link, seller:, target_resource_id: target_product.id, target_resource_type: "product_page") }
it "only attributes purchases for the targeted product" do
target_purchase = create(:purchase, link: target_product, seller:)
other_purchase = create(:purchase, link: other_product, seller:)
order.purchases << [target_purchase, other_purchase]
visit = create(:utm_link_visit, utm_link:, browser_guid:, created_at: 1.day.ago)
described_class.new.perform(order.id, browser_guid)
driven_sale = utm_link.utm_link_driven_sales.sole
expect(driven_sale.purchase_id).to eq(target_purchase.id)
expect(driven_sale.utm_link_visit_id).to eq(visit.id)
end
end
context "when feature flag is disabled" do
before do
Feature.deactivate_user(:utm_links, seller)
end
it "does not attribute any purchases" do
purchase = create(:purchase, link: product, seller:)
order.purchases << purchase
create(:utm_link_visit, utm_link:, browser_guid:, created_at: 1.day.ago)
expect do
described_class.new.perform(order.id, browser_guid)
end.not_to change { utm_link.utm_link_driven_sales.count }
end
end
context "when visit has no country code" do
it "sets country code from purchase" do
purchase = create(:purchase, link: product, seller:, country: "Australia")
order.purchases << purchase
visit = create(:utm_link_visit, utm_link:, browser_guid:, created_at: 1.day.ago, country_code: nil)
described_class.new.perform(order.id, browser_guid)
expect(visit.reload.country_code).to eq("AU")
end
end
context "when visit already has country code" do
it "preserves existing country code" do
purchase = create(:purchase, link: product, seller:, country: "United States")
order.purchases << purchase
visit = create(:utm_link_visit, utm_link:, browser_guid:, created_at: 1.day.ago, country_code: "JP")
described_class.new.perform(order.id, browser_guid)
expect(visit.reload.country_code).to eq("JP")
end
end
context "when visit was already attributed to a purchase" do
it "attributes a new purchase to the same visit" do
purchase = create(:purchase, link: product, seller:)
order.purchases << purchase
visit = create(:utm_link_visit, utm_link:, browser_guid:, created_at: 1.day.ago)
create(:utm_link_driven_sale, utm_link:, utm_link_visit: visit, purchase:)
new_purchase = create(:purchase, link: product, seller:)
new_order = create(:order, purchases: [new_purchase])
expect do
described_class.new.perform(new_order.id, browser_guid)
end.to change { utm_link.utm_link_driven_sales.count }.from(1).to(2)
driven_sale = utm_link.utm_link_driven_sales.last
expect(driven_sale.purchase_id).to eq(new_purchase.id)
expect(driven_sale.utm_link_visit_id).to eq(visit.id)
end
end
context "when multiple visits of different utm links qualify for the same purchase" do
it "attributes the purchase to only one visit which is the most recent among all applicable links" do
purchase = create(:purchase, link: product, seller:)
order.purchases << purchase
utm_link1_visit = create(:utm_link_visit, utm_link:, browser_guid:, created_at: 1.day.ago)
utm_link2 = create(:utm_link, seller:)
create(:utm_link_visit, utm_link: utm_link2, browser_guid:, created_at: 2.day.ago)
expect do
described_class.new.perform(order.id, browser_guid)
end.to change { UtmLinkDrivenSale.count }.from(0).to(1)
driven_sale = UtmLinkDrivenSale.sole
expect(driven_sale.purchase_id).to eq(purchase.id)
expect(driven_sale.utm_link_visit_id).to eq(utm_link1_visit.id)
expect(driven_sale.utm_link_id).to eq(utm_link.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_stripe_currency_balances_report_job_spec.rb | spec/sidekiq/send_stripe_currency_balances_report_job_spec.rb | # frozen_string_literal: true
describe SendStripeCurrencyBalancesReportJob do
describe "perform" do
before do
@mailer_double = double("mailer")
allow(AccountingMailer).to receive(:stripe_currency_balances_report).and_return(@mailer_double)
allow(StripeCurrencyBalancesReport).to receive(:stripe_currency_balances_report).and_return("Currency,Balance\nusd,997811.63\n")
allow(@mailer_double).to receive(:deliver_now)
allow(Rails.env).to receive(:production?).and_return(true)
end
it "enqueues AccountingMailer.stripe_currency_balances_report" do
expect(AccountingMailer).to receive(:stripe_currency_balances_report).and_return(@mailer_double)
expect(@mailer_double).to receive(:deliver_now)
SendStripeCurrencyBalancesReportJob.new.perform
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/block_suspended_account_ip_worker_spec.rb | spec/sidekiq/block_suspended_account_ip_worker_spec.rb | # frozen_string_literal: true
describe BlockSuspendedAccountIpWorker do
describe "#perform" do
before do
@user = create(:user, last_sign_in_ip: "10.2.2.2")
@user1 = create(:user, last_sign_in_ip: "10.2.2.2")
@no_ip_user = create(:user, last_sign_in_ip: nil)
end
it "adds the sellers ip to the BlockedObject table if last_sign_in_ip is present" do
described_class.new.perform(@user.id)
blocked_object = BlockedObject.find_by(object_value: @user.last_sign_in_ip)
expect(blocked_object).to_not be(nil)
expect(blocked_object.expires_at).to eq(
blocked_object.blocked_at + BlockedObject::IP_ADDRESS_BLOCKING_DURATION_IN_MONTHS.months
)
end
it "does nothing if last_sign_in_ip is not present" do
described_class.new.perform(@no_ip_user.id)
expect(BlockedObject.find_by(object_value: @no_ip_user.last_sign_in_ip)).to be(nil)
end
it "does nothing if there is a compliant user with same last_sign_in_ip" do
@user1.mark_compliant!(author_name: "iffy")
described_class.new.perform(@user.id)
expect(BlockedObject.find_by(object_value: @user.last_sign_in_ip)).to be(nil)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_wishlist_updated_emails_job_spec.rb | spec/sidekiq/send_wishlist_updated_emails_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SendWishlistUpdatedEmailsJob do
let(:wishlist) { create(:wishlist) }
let(:wishlist_follower) { create(:wishlist_follower, wishlist: wishlist, created_at: 10.minutes.ago) }
let(:wishlist_product) { create(:wishlist_product, wishlist: wishlist, created_at: 5.minutes.ago) }
let(:wishlist_product_ids) { [wishlist_product.id] }
describe "#perform" do
it "sends an email to the wishlist follower" do
expect(CustomerLowPriorityMailer).to receive(:wishlist_updated).with(wishlist_follower.id, 1).and_call_original
described_class.new.perform(wishlist.id, wishlist_product_ids)
end
it "updates the last contacted at timestamp" do
described_class.new.perform(wishlist.id, wishlist_product_ids)
expect(wishlist.reload.followers_last_contacted_at).to eq(wishlist_product.created_at)
end
context "when the wishlist has no new products" do
let(:wishlist_product_ids) { [] }
it "does not send an email" do
expect(CustomerLowPriorityMailer).not_to receive(:wishlist_updated)
described_class.new.perform(wishlist.id, wishlist_product_ids)
end
it "does not update the last contacted at timestamp" do
described_class.new.perform(wishlist.id, wishlist_product_ids)
expect(wishlist.reload.followers_last_contacted_at).to be_nil
end
end
context "when a product was added before a user followed" do
let(:wishlist_product_2) { create(:wishlist_product, wishlist: wishlist, created_at: 1.hour.ago) }
let(:wishlist_product_ids) { [wishlist_product.id, wishlist_product_2.id] }
let(:old_follower) { create(:wishlist_follower, wishlist: wishlist, created_at: 2.hours.ago) }
it "excludes the product from emails to new followers" do
expect(CustomerLowPriorityMailer).to receive(:wishlist_updated).with(old_follower.id, 2).and_call_original
expect(CustomerLowPriorityMailer).to receive(:wishlist_updated).with(wishlist_follower.id, 1).and_call_original
described_class.new.perform(wishlist.id, wishlist_product_ids)
end
end
context "when another product was added after the job was scheduled" do
let!(:newer_product) { create(:wishlist_product, wishlist: wishlist, created_at: 1.minute.ago) }
it "does nothing since the job for the newer product is expected to send the email" do
expect(CustomerLowPriorityMailer).not_to receive(:wishlist_updated)
described_class.new.perform(wishlist.id, wishlist_product_ids)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/fight_dispute_job_spec.rb | spec/sidekiq/fight_dispute_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe FightDisputeJob do
describe "#perform" do
let(:dispute_evidence) { create(:dispute_evidence) }
let(:dispute) { dispute_evidence.dispute }
shared_examples_for "submitted dispute evidence" do
it "fights chargeback" do
expect_any_instance_of(Purchase).to receive(:fight_chargeback)
described_class.new.perform(dispute.id)
expect(dispute_evidence.reload.resolved?).to eq(true)
expect(dispute_evidence.resolution).to eq(DisputeEvidence::RESOLUTION_SUBMITTED)
end
end
shared_examples_for "does nothing" do
it "does nothing" do
expect_any_instance_of(Purchase).not_to receive(:fight_chargeback)
described_class.new.perform(dispute.id)
end
end
context "when dispute is on a combined charge", :vcr do
let(:dispute_evidence) { create(:dispute_evidence_on_charge) }
before do
dispute_evidence.update_as_not_seller_contacted!
expect_any_instance_of(Charge).to receive(:fight_chargeback)
end
it "submits evidence correctly" do
described_class.new.perform(dispute.id)
expect(dispute_evidence.reload.resolved?).to eq(true)
expect(dispute_evidence.resolution).to eq(DisputeEvidence::RESOLUTION_SUBMITTED)
end
end
context "when the dispute evidence has been resolved" do
before do
dispute_evidence.update_as_resolved!(
resolution: DisputeEvidence::RESOLUTION_SUBMITTED,
seller_contacted_at: nil
)
end
it_behaves_like "does nothing"
end
context "when the dispute evidence has not been submitted" do
context "when the seller hasn't been contacted" do
before do
dispute_evidence.update_as_not_seller_contacted!
end
it_behaves_like "submitted dispute evidence"
context "when the dispute is already closed" do
let(:error_message) { "(Status 400) (Request req_OagvpePrZlJtTF) This dispute is already closed" }
before do
allow_any_instance_of(Purchase).to receive(:fight_chargeback)
.and_raise(ChargeProcessorInvalidRequestError.new(error_message))
end
it "marks the dispute evidence as rejected" do
described_class.new.perform(dispute.id)
expect(dispute_evidence.reload.resolved?).to eq(true)
expect(dispute_evidence.resolution).to eq(DisputeEvidence::RESOLUTION_REJECTED)
expect(dispute_evidence.error_message).to eq(error_message)
end
end
end
context "when the seller has been contacted" do
context "when the seller has submitted the evidence" do
before do
dispute_evidence.update_as_seller_submitted!
end
context "when there are still hours left to submit evidence" do
before do
dispute_evidence.update_as_seller_contacted!
end
it_behaves_like "submitted dispute evidence"
end
context "when there are no more hours left to submit evidence" do
before do
dispute_evidence.update!(seller_contacted_at: DisputeEvidence::SUBMIT_EVIDENCE_WINDOW_DURATION_IN_HOURS.hours.ago)
end
it_behaves_like "submitted dispute evidence"
end
end
context "when the seller has not submitted the evidence" do
context "when there are still hours left to submit evidence" do
before do
dispute_evidence.update_as_seller_contacted!
end
it_behaves_like "does nothing"
end
context "when there are no more hours left to submit evidence" do
before do
dispute_evidence.update!(seller_contacted_at: DisputeEvidence::SUBMIT_EVIDENCE_WINDOW_DURATION_IN_HOURS.hours.ago)
end
it_behaves_like "submitted dispute evidence"
end
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/find_expired_subscriptions_to_set_as_deactivated_worker_spec.rb | spec/sidekiq/find_expired_subscriptions_to_set_as_deactivated_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe FindExpiredSubscriptionsToSetAsDeactivatedWorker do
describe "#perform" do
it "queues subscriptions that should be set as deactivated" do
subscriptions = [
create(:subscription),
create(:subscription, cancelled_at: 1.day.from_now),
create(:subscription, cancelled_at: 1.day.ago, is_test_subscription: true),
create(:subscription, cancelled_at: 1.day.ago, deactivated_at: 1.hour.ago),
create(:subscription, cancelled_at: 1.day.ago),
create(:subscription, failed_at: 1.day.ago),
create(:subscription, ended_at: 1.day.ago),
]
described_class.new.perform
expect(SetSubscriptionAsDeactivatedWorker).not_to have_enqueued_sidekiq_job(subscriptions[0].id)
expect(SetSubscriptionAsDeactivatedWorker).not_to have_enqueued_sidekiq_job(subscriptions[1].id)
expect(SetSubscriptionAsDeactivatedWorker).not_to have_enqueued_sidekiq_job(subscriptions[2].id)
expect(SetSubscriptionAsDeactivatedWorker).not_to have_enqueued_sidekiq_job(subscriptions[3].id)
expect(SetSubscriptionAsDeactivatedWorker).to have_enqueued_sidekiq_job(subscriptions[4].id)
expect(SetSubscriptionAsDeactivatedWorker).to have_enqueued_sidekiq_job(subscriptions[5].id)
expect(SetSubscriptionAsDeactivatedWorker).to have_enqueued_sidekiq_job(subscriptions[6].id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.