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/duplicate_product_worker_spec.rb | spec/sidekiq/duplicate_product_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DuplicateProductWorker do
describe "#perform" do
before do
@product = create(:product, name: "test product")
end
it "duplicates product successfully" do
expect { described_class.new.perform(@product.id) }.to change(Link, :count).by(1)
expect(Link.exists?(name: "test product (copy)")).to be(true)
end
it "sets product is_duplicating to false" do
@product.update!(is_duplicating: true)
expect { described_class.new.perform(@product.id) }.to change(Link, :count).by(1)
expect(@product.reload.is_duplicating).to be(false)
end
it "sets product is_duplicating to false on failure" do
@product.update!(is_duplicating: true)
expect_any_instance_of(ProductDuplicatorService).to receive(:duplicate).and_raise(StandardError)
expect { described_class.new.perform(@product.id) }.to_not change(Link, :count)
expect(@product.reload.is_duplicating).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/update_user_balance_stats_cache_worker_spec.rb | spec/sidekiq/update_user_balance_stats_cache_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateUserBalanceStatsCacheWorker do
describe "#perform" do
it "writes cache" do
user = create(:user)
expect(UserBalanceStatsService.new(user:).send(:read_cache)).to eq(nil)
described_class.new.perform(user.id)
expect(UserBalanceStatsService.new(user:).send(:read_cache)).not_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/stamp_pdf_for_purchase_job_spec.rb | spec/sidekiq/stamp_pdf_for_purchase_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StampPdfForPurchaseJob do
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
let(:purchase) { create(:purchase, link: product, seller: seller) }
before do
allow(PdfStampingService).to receive(:stamp_for_purchase!)
end
it "performs the job" do
described_class.new.perform(purchase.id)
expect(PdfStampingService).to have_received(:stamp_for_purchase!).with(purchase)
end
it "enqueues files ready email when notify flag is true" do
expect do
purchase.create_url_redirect!
described_class.new.perform(purchase.id, true)
end.to have_enqueued_mail(CustomerMailer, :files_ready_for_download).with(purchase.id)
end
context "when stamping the PDFs fails with a known error" do
before do
allow(PdfStampingService).to receive(:stamp_for_purchase!).and_raise(PdfStampingService::Error)
end
it "logs and doesn't raise an error" do
expect(Rails.logger).to receive(:error).with(/Failed stamping for purchase #{purchase.id}:/)
expect { described_class.new.perform(purchase.id) }.not_to raise_error
end
end
context "when stamping the PDFs fails with an unknown error" do
before do
allow(PdfStampingService).to receive(:stamp_for_purchase!).and_raise(StandardError)
end
it "raise an error" do
expect { described_class.new.perform(purchase.id) }.to raise_error(StandardError)
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_subscriptions_for_product_worker_spec.rb | spec/sidekiq/cancel_subscriptions_for_product_worker_spec.rb | # frozen_string_literal: true
describe CancelSubscriptionsForProductWorker do
describe "#perform" do
before do
@product = create(:membership_product, subscription_duration: "monthly", deleted_at: 1.day.ago)
@subscription = create(:subscription, link: @product)
@product.subscriptions << @subscription
create(:purchase, subscription: @subscription, link: @product, is_original_subscription_purchase: true)
end
it "cancels the subscriptions" do
expect(@subscription.alive?).to eq(true)
described_class.new.perform(@product.id)
expect(@subscription.reload.alive?).to eq(false)
end
it "sends out the email" do
expect do
described_class.new.perform(@product.id)
end.to have_enqueued_mail(ContactingCreatorMailer, :subscription_product_deleted).with(@product.id)
end
it "doesn't cancel the subscriptions for a published product" do
@product.publish!
expect(@subscription.alive?).to eq(true)
described_class.new.perform(@product.id)
expect(@subscription.reload.alive?).to eq(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/perform_payouts_up_to_delay_days_ago_worker_spec.rb | spec/sidekiq/perform_payouts_up_to_delay_days_ago_worker_spec.rb | # frozen_string_literal: true
describe PerformPayoutsUpToDelayDaysAgoWorker do
describe "perform" do
let(:payout_period_end_date) { User::PayoutSchedule.next_scheduled_payout_end_date }
let(:payout_processor_type) { PayoutProcessorType::PAYPAL }
it "calls 'create_payments_for_balances_up_to_date' on 'Payouts' which will do all the work" do
expect(Payouts).to receive(:create_payments_for_balances_up_to_date).with(payout_period_end_date, payout_processor_type)
described_class.new.perform(payout_processor_type)
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_transfer_gumroads_available_balances_to_gumroads_bank_account_worker_spec.rb | spec/sidekiq/stripe_transfer_gumroads_available_balances_to_gumroads_bank_account_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StripeTransferGumroadsAvailableBalancesToGumroadsBankAccountWorker, :vcr do
include StripeChargesHelper
describe "#perform" do
let(:estimate_held_amount_cents) { { HolderOfFunds::GUMROAD => 30_000_00, HolderOfFunds::STRIPE => 20_000_00 } }
before do
create_stripe_charge(StripePaymentMethodHelper.success_available_balance.to_stripejs_payment_method_id,
amount: 520_000_00,
currency: "usd"
)
create_stripe_charge(StripePaymentMethodHelper.success_available_balance.to_stripejs_payment_method_id,
amount: 500_000_00,
currency: "usd"
)
allow(Rails.env).to receive(:staging?).and_return(true)
allow(PayoutEstimates).to receive(:estimate_held_amount_cents).and_return(estimate_held_amount_cents)
end
it "aborts the process if a particular feature flag is set" do
Feature.activate(:skip_transfer_from_stripe_to_bank)
expect(StripeTransferExternallyToGumroad).to_not receive(:transfer_all_available_balances)
described_class.new.perform
ensure
Feature.deactivate(:skip_transfer_from_stripe_to_bank)
end
it "transfers all available balances with a buffer of 500k+ the expected Stripe connect payouts Gumroad is holding" do
expect(StripeTransferExternallyToGumroad).to receive(:transfer_all_available_balances).with(buffer_cents: 1_030_000_00).and_call_original
described_class.new.perform
end
it "leaves 530k in the Stripe balance" do
described_class.new.perform
balance = Stripe::Balance.retrieve
usd_available_balance = balance.available.find { |available_balance| available_balance["currency"] == "usd" }
expect(usd_available_balance["amount"]).to eq(1_030_000_00)
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_to_elasticsearch_worker_spec.rb | spec/sidekiq/send_to_elasticsearch_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SendToElasticsearchWorker do
before do
@product = create(:product)
@product_double = double("product")
end
it "attempts to index the product in Elasticsearch when instructed" do
expect(Link).to receive(:find_by).with(id: @product.id)
allow(Link).to receive(:find_by).with(id: @product.id).and_return(@product_double)
expect(@product_double).to receive_message_chain(:__elasticsearch__, :index_document)
SendToElasticsearchWorker.new.perform(@product.id, "index")
end
it "attempts to update the search index for the product in Elasticsearch when instructed" do
@product.update!(name: "Searching for Robby Fischer")
@product.tag!("tag")
search_update = @product.build_search_update(%w[name tags])
expect(Link).to receive(:find_by).with(id: @product.id)
allow(Link).to receive(:find_by).with(id: @product.id).and_return(@product_double)
allow(@product_double).to receive(:build_search_update).with(%w[name tags]).and_return(search_update)
expect(@product_double).to(
receive_message_chain(:__elasticsearch__, :update_document_attributes).with(
search_update.as_json
)
)
SendToElasticsearchWorker.new.perform(@product.id, "update", %w[name tags])
end
it "does not attempt to update the search index for the product in Elasticsearch " \
"when instructed with no attributes_to_update" do
expect(Link).to receive(:find_by).with(id: @product.id)
allow(Link).to receive(:find_by).with(id: @product.id).and_return(@product_double)
expect(@product_double).to_not receive(:build_search_update)
SendToElasticsearchWorker.new.perform(@product.id, "update", [])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/generate_ssl_certificate_spec.rb | spec/sidekiq/generate_ssl_certificate_spec.rb | # frozen_string_literal: true
describe GenerateSslCertificate do
describe "#perform" do
before do
@custom_domain = create(:custom_domain, domain: "www.example.com")
@obj_double = double("SslCertificates::Generate object")
allow(SslCertificates::Generate).to receive(:new).with(@custom_domain).and_return(@obj_double)
allow(@obj_double).to receive(:process)
end
context "when the environment is production or staging" do
before do
allow(Rails.env).to receive(:production?).and_return(true)
end
context "when the custom domain is not deleted" do
it "invokes SslCertificates::Generate service" do
expect(SslCertificates::Generate).to receive(:new).with(@custom_domain)
expect(@obj_double).to receive(:process)
described_class.new.perform(@custom_domain.id)
end
end
context "when the custom domain is deleted" do
before do
@custom_domain.mark_deleted!
end
it "doesn't invoke SslCertificates::Generate service" do
expect(SslCertificates::Generate).not_to receive(:new).with(@custom_domain)
described_class.new.perform(@custom_domain.id)
end
end
end
context "when the environment is not production or staging" do
it "doesn't invoke SslCertificates::Generate service" do
expect(SslCertificates::Generate).not_to receive(:new).with(@custom_domain)
expect(@obj_double).not_to receive(:process)
described_class.new.perform(@custom_domain.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/update_cached_sales_related_products_infos_job_spec.rb | spec/sidekiq/update_cached_sales_related_products_infos_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateCachedSalesRelatedProductsInfosJob do
describe "#perform" do
before do
Feature.activate(:update_sales_related_products_infos)
end
let(:product) { create(:product) }
let(:product_2) { create(:product) }
let(:product_3) { create(:product) }
before do
purchases = [
build(:purchase, link: product, email: "joe@example.com"),
build(:purchase, link: product_2, email: "joe@example.com"),
build(:purchase, link: product_3, email: "joe@example.com"),
build(:purchase, link: product, email: "alice@example.com"),
build(:purchase, link: product_2, email: "alice@example.com"),
]
# manually populate SRPIs
purchases.each do |purchase|
purchase.save!
UpdateSalesRelatedProductsInfosJob.new.perform(purchase.id)
end
# sanity check
expect(SalesRelatedProductsInfo.all).to match_array([
have_attributes(smaller_product_id: product.id, larger_product_id: product_2.id, sales_count: 2),
have_attributes(smaller_product_id: product.id, larger_product_id: product_3.id, sales_count: 1),
have_attributes(smaller_product_id: product_2.id, larger_product_id: product_3.id, sales_count: 1),
])
end
it "creates or update cache record of related products sales counts" do
# creates record
expect do
described_class.new.perform(product.id)
end.to change(CachedSalesRelatedProductsInfo, :count).by(1)
expect(CachedSalesRelatedProductsInfo.find_by(product:).normalized_counts).to eq(
product_2.id => 2,
product_3.id => 1,
)
# updates record
purchase = create(:purchase, link: product_3, email: "alice@example.com")
UpdateSalesRelatedProductsInfosJob.new.perform(purchase.id)
expect do
described_class.new.perform(product.id)
end.not_to change(CachedSalesRelatedProductsInfo, :count)
expect(CachedSalesRelatedProductsInfo.find_by(product:).normalized_counts).to eq(
product_2.id => 2,
product_3.id => 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/handle_stripe_event_worker_spec.rb | spec/sidekiq/handle_stripe_event_worker_spec.rb | # frozen_string_literal: true
describe HandleStripeEventWorker do
describe "perform" do
describe "stripe_connect_account_id is not provided" do
it "calls the StripeEventHandler" do
id = rand(10_000).to_s
expect_any_instance_of(StripeEventHandler).to receive(:handle_stripe_event)
expect(StripeEventHandler).to receive(:new).with({ id:, type: "deauthorized" }).and_call_original
described_class.new.perform(id:, type: "deauthorized")
end
end
describe "stripe_connect_account_id is provided" do
it "calls the StripeEventHandler" do
id = rand(10_000).to_s
expect_any_instance_of(StripeEventHandler).to receive(:handle_stripe_event)
expect(StripeEventHandler).to receive(:new).with({ id:, user_id: "acct_1234", type: "deauthorized" }).and_call_original
described_class.new.perform(id:, user_id: "acct_1234", type: "deauthorized")
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/perform_daily_instant_payouts_worker_spec.rb | spec/sidekiq/perform_daily_instant_payouts_worker_spec.rb | # frozen_string_literal: true
describe PerformDailyInstantPayoutsWorker do
describe "perform" do
let(:payout_period_end_date) { Date.yesterday }
it "calls 'create_instant_payouts_for_balances_up_to_date' on 'Payouts' which will do all the work" do
expect(Payouts).to receive(:create_instant_payouts_for_balances_up_to_date).with(payout_period_end_date)
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/elasticsearch_indexer_worker_spec.rb | spec/sidekiq/elasticsearch_indexer_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ElasticsearchIndexerWorker, :elasticsearch_wait_for_refresh do
describe "#perform without ActiveRecord objects" do
before do
class TravelEvent
include Elasticsearch::Model
index_name "test_travel_events"
end
EsClient.indices.delete(index: TravelEvent.index_name, ignore: [404])
class FinancialEvent
include Elasticsearch::Model
index_name "test_financial_events"
def self.index_name_from_body(body)
"#{index_name}-#{body["timestamp"].first(7)}"
end
end
EsClient.indices.delete(index: "#{FinancialEvent.index_name}*", ignore: [404])
end
context "when indexing" do
it "creates a document with the specified body" do
id = SecureRandom.uuid
described_class.new.perform(
"index",
"class_name" => "TravelEvent",
"id" => id,
"body" => {
"destination" => "Paris",
"timestamp" => "2021-07-20T01:02:03Z"
}
)
expect(EsClient.get(index: TravelEvent.index_name, id:).fetch("_source")).to eq(
"destination" => "Paris",
"timestamp" => "2021-07-20T01:02:03Z"
)
end
it "creates a document in an index which name is specified dynamically" do
id = SecureRandom.uuid
described_class.new.perform(
"index",
"class_name" => "FinancialEvent",
"id" => id,
"body" => {
"stock" => "TSLA",
"timestamp" => "2021-12-01T01:02:03Z"
}
)
expect(EsClient.get(index: "#{FinancialEvent.index_name}-2021-12", id:).fetch("_source")).to eq(
"stock" => "TSLA",
"timestamp" => "2021-12-01T01:02:03Z"
)
end
end
end
describe "#perform with ActiveRecord objects" do
before do
@client = EsClient.dup
@model = create_mock_model do |t|
t.string :name
t.string :country
t.string :ip_country
end
@model.class_eval <<-RUBY, __FILE__, __LINE__ + 1
include Elasticsearch::Model
include SearchIndexModelCommon
index_name "test_products"
mapping do
indexes :name, type: :keyword
indexes :country, type: :keyword
indexes :has_long_title, type: :boolean
end
def search_field_value(field_name)
case field_name
when "name", "country" then attributes[field_name]
when "has_long_title" then true
end
end
RUBY
EsClient.indices.delete(index: @model.index_name, ignore: [404])
end
after do
destroy_mock_model(@model)
end
context "when indexing" do
before do
@record = @model.create!(name: "Drawing")
end
it "creates a document" do
described_class.new.perform(
"index",
"class_name" => @model.name,
"record_id" => @record.id
)
expect(get_document_attributes).to eq(
"country" => nil,
"name" => "Drawing",
"has_long_title" => true,
)
end
end
context "when updating" do
before do
@record = @model.create!(name: "Drawing", country: "France")
end
context "an existing document" do
before do
@client.index(
index: @model.index_name,
id: @record.id,
body: {
"name" => "Drawing",
"country" => "Japan"
}
)
end
it "updates the document" do
described_class.new.perform(
"update",
"class_name" => @model.name,
"record_id" => @record.id,
"fields" => ["name", "has_long_title", "country"]
)
expect(get_document_attributes).to eq(
"name" => "Drawing",
"has_long_title" => true,
"country" => "France"
)
end
end
context "a non-existing document" do
subject(:perform) do
described_class.new.perform(
"update",
"class_name" => @model.name,
"record_id" => @record.id,
"fields" => ["name", "has_long_title"]
)
end
it "raises an error" do
expect { perform }.to raise_error(/document_missing_exception/)
end
context "while ignoring 404 errors from index" do
before do
$redis.sadd(RedisKey.elasticsearch_indexer_worker_ignore_404_errors_on_indices, @model.index_name)
end
it "does not raise an error and ignores the request" do
expect { perform }.not_to raise_error
expect(get_document_attributes).to eq(nil)
end
end
end
end
context "when updating by query" do
before do
@model.mapping do
indexes :country, type: :keyword
indexes :some_array_field, type: :long
indexes :some_string_field, type: :keyword
indexes :some_boolean_field, type: :boolean
indexes :some_integer_field, type: :long
indexes :null_field, type: :keyword
end
@model.__elasticsearch__.create_index!
@source_record = @model.create!(country: "United States")
@source_record.define_singleton_method(:search_field_value) do |field_name|
case field_name
when "some_array_field" then [1, 2, 3]
when "some_string_field" then "foobar"
when "some_boolean_field" then true
when "some_integer_field" then 456
when "some_unsupported_type_field" then {}
when "null_field" then nil
end
end
allow(@model).to receive(:find).with(@source_record.id).and_return(@source_record)
@record_2 = @model.create!(country: "United States")
@record_3 = @model.create!(country: "France")
@record_4 = @model.create!(country: "United States")
[@source_record, @record_2, @record_3, @record_4].each do |record|
record.__elasticsearch__.index_document
end
# To be able to test that a `null` value can be actually set for a field, we need to first set a value to it.
[@record_2, @record_3].each do |record|
@client.update(
index: @model.index_name,
id: record.id,
body: { doc: { null_field: "some string" } }
)
end
end
it "updates values matching the query" do
expect(EsClient).not_to receive(:search)
expect(EsClient).not_to receive(:scroll)
expect(EsClient).not_to receive(:clear_scroll)
described_class.new.perform(
"update_by_query",
"class_name" => @model.name,
"source_record_id" => @source_record.id,
"query" => { "term" => { "country" => "United States" } },
"fields" => %w[some_array_field some_string_field some_boolean_field some_integer_field null_field]
)
[get_document_attributes(@record_2), get_document_attributes(@record_4)].each do |attrs|
expect(attrs["some_array_field"]).to eq([1, 2, 3])
expect(attrs["some_string_field"]).to eq("foobar")
expect(attrs["some_boolean_field"]).to eq(true)
expect(attrs["some_integer_field"]).to eq(456)
expect(attrs["null_field"]).to eq(nil)
end
attrs = get_document_attributes(@record_3)
expect(attrs["some_array_field"]).to eq(nil)
expect(attrs["some_string_field"]).to eq(nil)
expect(attrs["some_boolean_field"]).to eq(nil)
expect(attrs["some_integer_field"]).to eq(nil)
expect(attrs["null_field"]).to eq("some string")
end
it "scrolls through results if the first query fails" do
stub_const("#{described_class}::UPDATE_BY_QUERY_SCROLL_SIZE", 1)
expect(EsClient).to receive(:update_by_query).once.and_raise(Elasticsearch::Transport::Transport::Errors::Conflict.new)
expect(EsClient).to receive(:search).and_call_original
expect(EsClient).to receive(:scroll).twice.and_call_original
expect(EsClient).to receive(:update_by_query).twice.and_call_original
expect(EsClient).to receive(:clear_scroll).and_call_original
described_class.new.perform(
"update_by_query",
"class_name" => @model.name,
"source_record_id" => @source_record.id,
"query" => { "term" => { "country" => "United States" } },
"fields" => %w[some_array_field some_string_field some_boolean_field some_integer_field null_field]
)
[get_document_attributes(@record_2), get_document_attributes(@record_4)].each do |attrs|
expect(attrs["some_string_field"]).to eq("foobar")
end
end
it "handles conflicts when updating scrolled results" do
stub_const("#{described_class}::UPDATE_BY_QUERY_SCROLL_SIZE", 1)
expect(EsClient).to receive(:update_by_query).twice.and_raise(Elasticsearch::Transport::Transport::Errors::Conflict.new)
expect(EsClient).to receive(:search).and_call_original
expect(EsClient).to receive(:scroll).twice.and_call_original
expect(EsClient).to receive(:update_by_query).twice.times.and_call_original
expect(EsClient).to receive(:clear_scroll).and_call_original
instance = described_class.new
expect(instance).to receive(:update_by_query_ids).twice.and_call_original
instance.perform(
"update_by_query",
"class_name" => @model.name,
"source_record_id" => @source_record.id,
"query" => { "term" => { "country" => "United States" } },
"fields" => %w[some_array_field some_string_field some_boolean_field some_integer_field null_field]
)
[get_document_attributes(@record_2), get_document_attributes(@record_4)].each do |attrs|
expect(attrs["some_string_field"]).to eq("foobar")
end
end
it "does not support nested fields", elasticsearch_wait_for_refresh: false do
expect do
described_class.new.perform(
"update_by_query",
"class_name" => @model.name,
"source_record_id" => @source_record.id,
"query" => { "term" => { "country" => "United States" } },
"fields" => %w[user.flags]
)
end.to raise_error(/nested fields.*not supported/)
end
end
context "when deleting" do
before do
@record = @model.create!(name: "Drawing")
end
context "an existing document" do
before do
@client.index(
index: @model.index_name,
id: @record.id,
body: {
"name" => "Drawing"
}
)
end
it "deletes the document" do
described_class.new.perform(
"delete",
"class_name" => @model.name,
"record_id" => @record.id
)
expect(get_document_attributes).to eq(nil)
end
end
context "a non-existing document" do
subject(:perform) do
described_class.new.perform(
"delete",
"class_name" => @model.name,
"record_id" => @record.id
)
end
it "does not raise an error" do
expect { perform }.not_to raise_error
end
end
end
end
describe ".columns_to_fields" do
it "returns matching fields" do
mapping = { "a" => ["a", "a_and_b"], "b" => "a_and_b", "d" => "d" }
expect(described_class.columns_to_fields(["a", "c"], mapping:)).to eq(["a", "a_and_b"])
expect(described_class.columns_to_fields(["c"], mapping:)).to eq([])
expect(described_class.columns_to_fields(["b", "d"], mapping:)).to eq(["a_and_b", "d"])
expect(described_class.columns_to_fields(["a", "b"], mapping:)).to eq(["a", "a_and_b"])
end
end
def get_document_attributes(record = @record)
@client.get(index: @model.index_name, id: record.id).fetch("_source")
rescue Elasticsearch::Transport::Transport::Errors::NotFound => _
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/update_utm_link_stats_job_spec.rb | spec/sidekiq/update_utm_link_stats_job_spec.rb | # frozen_string_literal: true
describe UpdateUtmLinkStatsJob do
describe "#perform" do
let(:utm_link) { create(:utm_link) }
let!(:utm_link_visit1) { create(:utm_link_visit, utm_link:, browser_guid: "abc123") }
let!(:utm_link_visit2) { create(:utm_link_visit, utm_link:, browser_guid: "def456") }
let!(:utm_link_visit3) { create(:utm_link_visit, utm_link:, browser_guid: "abc123") }
it "updates the utm_link's stats" do
described_class.new.perform(utm_link.id)
expect(utm_link.reload.total_clicks).to eq(3)
expect(utm_link.unique_clicks).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/purge_old_deleted_asset_previews_worker_spec.rb | spec/sidekiq/purge_old_deleted_asset_previews_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PurgeOldDeletedAssetPreviewsWorker do
describe "#perform" do
it "deletes targeted rows" do
stub_const("#{described_class}::DELETION_BATCH_SIZE", 1)
create(:asset_preview, deleted_at: 2.months.ago)
recently_marked_as_deleted = create(:asset_preview, deleted_at: 1.day.ago)
not_marked_as_deleted = create(:asset_preview)
described_class.new.perform
expect(AssetPreview.all).to match_array([recently_marked_as_deleted, not_marked_as_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/retry_failed_paypal_payouts_worker_spec.rb | spec/sidekiq/retry_failed_paypal_payouts_worker_spec.rb | # frozen_string_literal: true
describe RetryFailedPaypalPayoutsWorker do
describe "perform" do
it "calls `Payouts.create_payments_for_balances_up_to_date_for_users`" do
payout_period_end_date = User::PayoutSchedule.manual_payout_end_date
failed_payment = create(:payment_failed, user: create(:user), payout_period_end_date:)
expect(Payouts).to receive(:create_payments_for_balances_up_to_date_for_users).with(payout_period_end_date, PayoutProcessorType::PAYPAL, [failed_payment.user], { perform_async: true, retrying: true })
described_class.new.perform
end
it "does nothing if no failed payouts" do
expect(Payouts).to_not receive(:create_payments_for_balances_up_to_date_for_users)
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/refund_purchase_worker_spec.rb | spec/sidekiq/refund_purchase_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RefundPurchaseWorker do
describe "#perform" do
let(:admin_user) { create(:admin_user) }
let(:purchase) { create(:purchase) }
let(:purchase_double) { double }
before do
expect(Purchase).to receive(:find).with(purchase.id).and_return(purchase_double)
end
context "when the reason is `Refund::FRAUD`" do
it "calls #refund_for_fraud_and_block_buyer! on the purchase" do
expect(purchase_double).to receive(:refund_for_fraud_and_block_buyer!).with(admin_user.id)
described_class.new.perform(purchase.id, admin_user.id, Refund::FRAUD)
end
end
context "when the reason is not supplied" do
it "calls #refund_and_save! on the purchase" do
expect(purchase_double).to receive(:refund_and_save!).with(admin_user.id)
described_class.new.perform(purchase.id, admin_user.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/update_payout_status_worker_spec.rb | spec/sidekiq/update_payout_status_worker_spec.rb | # frozen_string_literal: true
describe UpdatePayoutStatusWorker do
describe "#perform" do
context "when the payout is not created in the split mode" do
let(:payment) { create(:payment, processor_fee_cents: 10, txn_id: "Some ID") }
it "fetches and sets the new payment status from PayPal" do
expect(PaypalPayoutProcessor).to(
receive(:get_latest_payment_state_from_paypal).with(payment.amount_cents,
payment.txn_id,
payment.created_at.beginning_of_day - 1.day,
payment.state).and_return("completed"))
expect do
described_class.new.perform(payment.id)
end.to change { payment.reload.state }.from("processing").to("completed")
end
it "does not attempt to fetch or update the status for a payment not in the 'processing' state" do
payment.mark_completed!
expect(PaypalPayoutProcessor).not_to receive(:get_latest_payment_state_from_paypal)
expect_any_instance_of(Payment).not_to receive(:mark!)
described_class.new.perform(payment.id)
end
end
context "when the payout is created in the split mode" do
let(:payment) do
# Payout was sent out
payment = create(:payment, processor_fee_cents: 10)
# IPN was received and one of the split parts was in the pending state
payment.was_created_in_split_mode = true
payment.split_payments_info = [
{ "unique_id" => "SPLIT_1-1", "state" => "completed", "correlation_id" => "fcf", "amount_cents" => 100, "errors" => [], "txn_id" => "02P" },
{ "unique_id" => "SPLIT_1-2", "state" => "pending", "correlation_id" => "6db", "amount_cents" => 50, "errors" => [], "txn_id" => "4LR" }
]
payment.save!
payment
end
it "fetches and sets the new payment status from PayPal" do
expect(PaypalPayoutProcessor).to(
receive(:get_latest_payment_state_from_paypal).with(50,
"4LR",
payment.created_at.beginning_of_day - 1.day,
"pending").and_return("completed"))
expect do
described_class.new.perform(payment.id)
end.to change { payment.reload.state }.from("processing").to("completed")
end
# Sidekiq will retry on exception
it "raises an exception if the status fetched is 'pending'" do
expect(PaypalPayoutProcessor).to(
receive(:get_latest_payment_state_from_paypal).with(50,
"4LR",
payment.created_at.beginning_of_day - 1.day,
"pending").and_return("pending"))
expect do
described_class.new.perform(payment.id)
end.to raise_error("Some split payment parts are still in the 'pending' state")
end
it "does not attempt to fetch or update the status for a payment not in the 'processing' state" do
payment.txn_id = "something"
payment.mark_completed!
expect(PaypalPayoutProcessor).not_to receive(:get_latest_payment_state_from_paypal)
expect_any_instance_of(Payment).not_to receive(:mark_completed!)
expect_any_instance_of(Payment).not_to receive(:mark_failed!)
described_class.new.perform(payment.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/process_early_fraud_warning_job_spec.rb | spec/sidekiq/process_early_fraud_warning_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ProcessEarlyFraudWarningJob, :vcr do
let(:purchase) { create(:purchase, stripe_transaction_id: "ch_2O8n7J9e1RjUNIyY1rs9MIRL") }
let!(:early_fraud_warning) { create(:early_fraud_warning, purchase:) }
describe "#perform" do
context "when the dispute evidence has been resolved" do
before do
early_fraud_warning.update_as_resolved!(resolution: EarlyFraudWarning::RESOLUTION_RESOLVED_IGNORED)
end
it "does nothing" do
expect_any_instance_of(EarlyFraudWarning).not_to receive(:update_from_stripe!)
described_class.new.perform(early_fraud_warning.id)
end
end
context "when not actionable" do
before do
early_fraud_warning.update!(actionable: false)
expect_any_instance_of(EarlyFraudWarning).to receive(:update_from_stripe!).and_return(true)
end
context "when there is no dispute or refund" do
it "raises an error" do
expect { described_class.new.perform(early_fraud_warning.id) }.to raise_error("Cannot determine resolution")
end
end
context "when there is a refund" do
let!(:refund) { create(:refund, purchase:) }
before do
early_fraud_warning.update!(refund:)
end
it "resolves as not actionable refunded" do
described_class.new.perform(early_fraud_warning.id)
expect(early_fraud_warning.reload.resolved?).to eq(true)
expect(early_fraud_warning.resolution).to eq(EarlyFraudWarning::RESOLUTION_NOT_ACTIONABLE_REFUNDED)
end
context "when there is also a dispute" do
let!(:dispute) { create(:dispute_formalized, purchase:, created_at: 1.hour.ago) }
before do
early_fraud_warning.update!(dispute:)
end
it "resolves as not actionable disputed if created before" do
described_class.new.perform(early_fraud_warning.id)
expect(early_fraud_warning.reload.resolved?).to eq(true)
expect(early_fraud_warning.resolution).to eq(EarlyFraudWarning::RESOLUTION_NOT_ACTIONABLE_DISPUTED)
end
end
end
end
describe "actionable" do
before do
expect_any_instance_of(EarlyFraudWarning).to receive(:update_from_stripe!).and_return(true)
end
shared_examples_for "resolves as ignored" do |resolution_message|
it "resolves as ignored" do
described_class.new.perform(early_fraud_warning.id)
expect(early_fraud_warning.reload.resolved?).to eq(true)
expect(early_fraud_warning.resolution).to eq(EarlyFraudWarning::RESOLUTION_RESOLVED_IGNORED)
expect(early_fraud_warning.resolution_message).to eq(resolution_message)
end
end
describe "refundable for fraud" do
context "when the purchase is refundable for fraud" do
before do
expect_any_instance_of(EarlyFraudWarning).to receive(:chargeable_refundable_for_fraud?).and_return(true)
end
context "when associated with a purchase" do
it "resolves as refunded for fraud" do
expect_any_instance_of(Purchase).to receive(:refund_for_fraud_and_block_buyer!).once.with(GUMROAD_ADMIN_ID)
described_class.new.perform(early_fraud_warning.id)
expect(early_fraud_warning.reload.resolved?).to eq(true)
expect(early_fraud_warning.resolution).to eq(EarlyFraudWarning::RESOLUTION_RESOLVED_REFUNDED_FOR_FRAUD)
end
end
context "when associated with a charge" do
let(:another_purchase) { create(:purchase, stripe_transaction_id: "ch_2O8n7J9e1RjUNIyY1rs9MIRL") }
let(:charge) { create(:charge, processor_transaction_id: "ch_2O8n7J9e1RjUNIyY1rs9MIRL", purchases: [purchase, another_purchase]) }
let!(:early_fraud_warning) { create(:early_fraud_warning, purchase: nil, charge:) }
it "resolves as refunded for fraud" do
expect_any_instance_of(Charge).to receive(:refund_for_fraud_and_block_buyer!).once.with(GUMROAD_ADMIN_ID)
described_class.new.perform(early_fraud_warning.id)
expect(early_fraud_warning.reload.resolved?).to eq(true)
expect(early_fraud_warning.resolution).to eq(EarlyFraudWarning::RESOLUTION_RESOLVED_REFUNDED_FOR_FRAUD)
end
end
end
context "when the purchase is not refundable for fraud" do
before do
expect_any_instance_of(EarlyFraudWarning).to receive(:chargeable_refundable_for_fraud?).and_return(false)
end
it_behaves_like "resolves as ignored"
end
end
context "subscription contactable" do
let(:purchase) { create(:membership_purchase) }
context "when the purchase is subscription contactable" do
before do
expect_any_instance_of(EarlyFraudWarning).to receive(:purchase_for_subscription_contactable?).and_return(true)
expect_any_instance_of(EarlyFraudWarning).to receive(:chargeable_refundable_for_fraud?).and_return(false)
end
it "sends email and resolves as customer contacted" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(CustomerLowPriorityMailer).to receive(
:subscription_early_fraud_warning_notification
).with(purchase.id).and_return(mail_double)
described_class.new.perform(early_fraud_warning.id)
expect(early_fraud_warning.reload.resolved?).to eq(true)
expect(early_fraud_warning.resolution).to eq(EarlyFraudWarning::RESOLUTION_RESOLVED_CUSTOMER_CONTACTED)
end
context "when there are other purchases that have been contacted" do
before do
expect_any_instance_of(EarlyFraudWarning).to receive(
:associated_early_fraud_warning_ids_for_subscription_contacted
).and_return([123])
end
it_behaves_like "resolves as ignored", "Already contacted for EFW id 123"
end
end
context "when the purchase is not refundable for fraud" do
before do
expect_any_instance_of(EarlyFraudWarning).to receive(:purchase_for_subscription_contactable?).and_return(false)
expect_any_instance_of(EarlyFraudWarning).to receive(:chargeable_refundable_for_fraud?).and_return(false)
end
it_behaves_like "resolves as ignored"
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/activate_integrations_worker_spec.rb | spec/sidekiq/activate_integrations_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ActivateIntegrationsWorker do
it "calls CircleIntegrationService#activate" do
purchase = create(:purchase)
expect_any_instance_of(Integrations::CircleIntegrationService).to receive(:activate).with(purchase)
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")
expect_any_instance_of(Integrations::CircleIntegrationService).to_not receive(:activate)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/create_vat_report_job_spec.rb | spec/sidekiq/create_vat_report_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CreateVatReportJob do
it "raises an ArgumentError if the year is less than 2014 or greater than 3200" do
expect do
described_class.new.perform(2, 2013)
end.to raise_error(ArgumentError)
end
it "raises an ArgumentError if the quarter is not within 1 and 4 inclsusive" do
expect do
described_class.new.perform(0, 2013)
end.to raise_error(ArgumentError)
expect do
described_class.new.perform(5, 2013)
end.to raise_error(ArgumentError)
end
describe "happy case", :vcr do
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/vat-reporting-spec-#{SecureRandom.hex(18)}.zip")
end
before do
create(:zip_tax_rate, country: "AT", state: nil, zip_code: nil, combined_rate: 0.20, flags: 0)
create(:zip_tax_rate, country: "AT", state: nil, zip_code: nil, combined_rate: 0.10, flags: 2)
create(:zip_tax_rate, country: "ES", state: nil, zip_code: nil, combined_rate: 0.21, flags: 0)
create(:zip_tax_rate, country: "GB", state: nil, zip_code: nil, combined_rate: 0.20, flags: 0)
create(:zip_tax_rate, country: "CY", state: nil, zip_code: nil, combined_rate: 0.19, flags: 0)
q1_time = Time.zone.local(2015, 1, 1)
q1_m2_time = Time.zone.local(2015, 2, 1)
q2_time = Time.zone.local(2015, 5, 1)
product = create(:product, price_cents: 200_00)
epublication_product = create(:product, price_cents: 300_00, is_epublication: true)
travel_to(q1_time) do
at_test_purchase1 = create(:purchase, link: product, purchaser: product.user, purchase_state: "in_progress",
quantity: 2, perceived_price_cents: 200_00, country: "Austria", ip_country: "Austria")
at_test_purchase1.mark_test_successful!
at_test_purchase2 = create(:purchase, link: epublication_product, purchaser: epublication_product.user, purchase_state: "in_progress",
quantity: 2, perceived_price_cents: 300_00, country: "Austria", ip_country: "Austria")
at_test_purchase2.mark_test_successful!
es_test_purchase1 = create(:purchase, link: product, purchaser: product.user, purchase_state: "in_progress",
quantity: 2, perceived_price_cents: 400_00, country: "Spain", ip_country: "Spain")
es_test_purchase1.mark_test_successful!
gb_purchase1 = create(:purchase, link: product, chargeable: build(:chargeable), quantity: 1,
perceived_price_cents: 200_00, country: "United Kingdom", ip_country: "United Kingdom")
gb_purchase1.process!
gb_purchase2 = create(:purchase, link: product, chargeable: build(:chargeable), quantity: 1,
perceived_price_cents: 200_00, country: "United Kingdom", ip_country: "United Kingdom")
gb_purchase2.process!
gb_purchase2.refund_gumroad_taxes!(refunding_user_id: 1)
cy_purchase_1 = create(:purchase, link: product, chargeable: build(:chargeable), quantity: 1,
perceived_price_cents: 200_00, country: "Cyprus", ip_country: "Cyprus")
cy_purchase_1.process!
cy_purchase_1_refund_flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(Currency::USD, cy_purchase_1.gross_amount_refundable_cents)
cy_purchase_1.refund_purchase!(cy_purchase_1_refund_flow_of_funds, nil)
gb_purchase1.chargeback_date = Time.current
gb_purchase1.chargeback_reversed = true
gb_purchase1.save!
end
travel_to(q1_m2_time) do
at_test_purchase1 = create(:purchase, link: product, purchaser: product.user, purchase_state: "in_progress",
quantity: 2, perceived_price_cents: 200_00, country: "Austria", ip_country: "Austria")
at_test_purchase1.mark_test_successful!
at_test_purchase2 = create(:purchase, link: epublication_product, purchaser: epublication_product.user, purchase_state: "in_progress",
quantity: 2, perceived_price_cents: 300_00, country: "Austria", ip_country: "Austria")
at_test_purchase2.mark_test_successful!
es_test_purchase1 = create(:purchase, link: product, purchaser: product.user, purchase_state: "in_progress",
quantity: 2, perceived_price_cents: 400_00, country: "Spain", ip_country: "Spain")
es_test_purchase1.mark_test_successful!
gb_purchase1 = create(:purchase, link: product, chargeable: build(:chargeable), quantity: 1,
perceived_price_cents: 200_00, country: "United Kingdom", ip_country: "United Kingdom")
gb_purchase1.process!
create(:purchase, link: product, chargeable: build(:chargeable), quantity: 1,
perceived_price_cents: 200_00, country: "United Kingdom", ip_country: "United Kingdom").process!
cy_purchase_1 = create(:purchase, link: product, chargeable: build(:chargeable), quantity: 1,
perceived_price_cents: 200_00, country: "Cyprus", ip_country: "Cyprus")
cy_purchase_1.process!
cy_purchase_1_refund_flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(Currency::USD, cy_purchase_1.gross_amount_refundable_cents)
cy_purchase_1.refund_purchase!(cy_purchase_1_refund_flow_of_funds, nil)
gb_purchase1.chargeback_date = Time.current
gb_purchase1.chargeback_reversed = true
gb_purchase1.save!
end
travel_to(q2_time) do
es_purchase2 = build(:purchase, link: product, chargeable: build(:chargeable),
quantity: 2, perceived_price_cents: 400_00, country: "Spain", ip_country: "Spain")
es_purchase2.process!
gb_purchase2 = build(:purchase, link: product, chargeable: build(:chargeable), quantity: 1,
perceived_price_cents: 200_00, country: "United Kingdom", ip_country: "United Kingdom")
gb_purchase2.process!
es_purchase2.chargeback_date = Time.current
es_purchase2.chargeback_reversed = true
es_purchase2.save!
end
end
it "returns a zipped file containing a csv file for every month in the quarter" do
expect(s3_bucket_double).to receive(:object).and_return(@s3_object)
expect(AccountingMailer).to receive(:vat_report).with(1, 2015, anything).and_call_original
allow_any_instance_of(described_class).to receive(:gbp_to_usd_rate_for_date).and_return(1.5)
described_class.new.perform(1, 2015)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "VAT Reporting", anything, "green")
report_verification_helper
end
def report_verification_helper
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(["Member State of Consumption", "VAT rate type", "VAT rate in Member State",
"Total value of supplies excluding VAT (USD)",
"Total value of supplies excluding VAT (Estimated, USD)",
"VAT amount due (USD)",
"Total value of supplies excluding VAT (GBP)",
"Total value of supplies excluding VAT (Estimated, GBP)",
"VAT amount due (GBP)"])
expect(actual_payload[1]).to eq(["Austria", "Standard", "20.0", "0.00", "0.00", "0.00", "0.00", "0.00", "0.00"])
expect(actual_payload[2]).to eq(["Austria", "Reduced", "10.0", "0.00", "0.00", "0.00", "0.00", "0.00", "0.00"])
expect(actual_payload[3]).to eq(["Spain", "Standard", "21.0", "0.00", "0.00", "0.00", "0.00", "0.00", "0.00"])
expect(actual_payload[4]).to eq(["United Kingdom", "Standard", "20.0", "800.00", "600.00", "120.00", "533.33", "400.00", "80.00"])
expect(actual_payload[5]).to eq(["Cyprus", "Standard", "19.0", "0.00", "0.00", "0.00", "0.00", "0.00", "0.00"])
ensure
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/expire_stamped_pdfs_job_spec.rb | spec/sidekiq/expire_stamped_pdfs_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ExpireStampedPdfsJob do
describe "#perform" do
it "marks old stamped pdfs as deleted" do
record_1 = create(:stamped_pdf, created_at: 1.year.ago)
record_2 = create(:stamped_pdf, created_at: 1.day.ago)
described_class.new.perform
expect(record_1.reload.deleted?).to be(true)
expect(record_2.reload.deleted?).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/send_preorder_seller_summary_worker_spec.rb | spec/sidekiq/send_preorder_seller_summary_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SendPreorderSellerSummaryWorker, :vcr do
before do
travel_to 2.days.ago
@product = create(:product, price_cents: 600, is_in_preorder_state: false)
@preorder_product = create(:preorder_product_with_content, link: @product, release_at: 2.days.from_now)
travel_back
@card_will_succeed = build(:chargeable)
@card_will_decline = build(:chargeable_success_charge_decline)
@mail_double = double
allow(@mail_double).to receive(:deliver_later)
end
it "sends the summary email if all preorders are charged" do
authorization_purchase = build(:purchase, link: @product, chargeable: @card_will_succeed, purchase_state: "in_progress", is_preorder_authorization: true)
preorder = @preorder_product.build_preorder(authorization_purchase)
preorder.authorize!
preorder.mark_authorization_successful
preorder.charge!
expect(ContactingCreatorMailer).to receive(:preorder_summary).with(@preorder_product.id).and_return(@mail_double)
SendPreorderSellerSummaryWorker.new.perform(@preorder_product.id)
end
it "does not send the summary email if there are un-charged preorders" do
authorization_purchase = build(:purchase, link: @product, chargeable: @card_will_succeed, purchase_state: "in_progress", is_preorder_authorization: true)
preorder = @preorder_product.build_preorder(authorization_purchase)
preorder.authorize!
preorder.mark_authorization_successful
# Should not count `in_progress` purchases towards preorder being charged
create(:purchase_in_progress, link: @product, preorder:, chargeable: @card_will_succeed)
expect(ContactingCreatorMailer).to_not receive(:preorder_summary).with(@preorder_product.id)
SendPreorderSellerSummaryWorker.new.perform(@preorder_product.id)
# since we weren't done charging all the cards it should have queued the summary job again.
expect(SendPreorderSellerSummaryWorker).to have_enqueued_sidekiq_job(@preorder_product.id, anything)
end
it "sends the summary email if the preorder was charged and failed" do
authorization_purchase = build(:purchase, link: @product, chargeable: @card_will_decline, purchase_state: "in_progress",
is_preorder_authorization: true)
preorder = @preorder_product.build_preorder(authorization_purchase)
preorder.authorize!
preorder.mark_authorization_successful
preorder.charge!
expect(ContactingCreatorMailer).to receive(:preorder_summary).with(@preorder_product.id).and_return(@mail_double)
SendPreorderSellerSummaryWorker.new.perform(@preorder_product.id)
end
context "when preorders take more than 24h to charge" do
it "stops waiting and notifies Bugsnag", :sidekiq_inline do
authorization_purchase = build(:purchase, link: @product, chargeable: @card_will_decline, purchase_state: "in_progress",
is_preorder_authorization: true)
preorder = @preorder_product.build_preorder(authorization_purchase)
preorder.authorize!
preorder.mark_authorization_successful
expect(ContactingCreatorMailer).not_to receive(:preorder_summary).with(@preorder_product.id)
expect(SendPreorderSellerSummaryWorker).to receive(:perform_in).with(20.minutes, @preorder_product.id, anything).exactly(72).times.and_call_original
expect(Bugsnag).to receive(:notify).with("Timed out waiting for all preorders to be charged. PreorderLink: #{@preorder_product.id}.")
expect do
SendPreorderSellerSummaryWorker.new.perform(@preorder_product.id)
end.to raise_error(/Timed out waiting for all preorders to be charged/)
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_user_compliance_info_worker_spec.rb | spec/sidekiq/handle_new_user_compliance_info_worker_spec.rb | # frozen_string_literal: true
describe HandleNewUserComplianceInfoWorker do
describe "perform" do
let(:user_compliance_info) { create(:user_compliance_info) }
it "calls StripeMerchantAccountManager.handle_new_user_compliance_info with the user compliance info object" do
expect(StripeMerchantAccountManager).to receive(:handle_new_user_compliance_info).with(user_compliance_info)
described_class.new.perform(user_compliance_info.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/refund_unpaid_purchases_worker_spec.rb | spec/sidekiq/refund_unpaid_purchases_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RefundUnpaidPurchasesWorker, :vcr do
describe "#perform" do
before do
@admin_user = create(:admin_user)
@purchase = create(:purchase_in_progress, chargeable: create(:chargeable))
@purchase.process!
@purchase.mark_successful!
@purchase.increment_sellers_balance!
@purchase_without_balance = create(:purchase_in_progress, chargeable: create(:chargeable))
@purchase_without_balance.process!
@purchase_without_balance.mark_successful!
@purchase_with_paid_balance = create(:purchase_in_progress, chargeable: create(:chargeable))
@purchase_with_paid_balance.process!
@purchase_with_paid_balance.mark_successful!
@purchase_with_paid_balance.increment_sellers_balance!
@purchase_with_paid_balance.purchase_success_balance.tap do |balance|
balance.mark_processing!
balance.mark_paid!
end
@user = @purchase.seller
end
it "does not refund purchases if the user is not suspended" do
@user.mark_compliant!(author_id: @admin_user.id)
described_class.new.perform(@user.id, @admin_user.id)
expect(RefundPurchaseWorker).not_to have_enqueued_sidekiq_job(@purchase.id, @admin_user.id)
end
it "queues the refund of unpaid purchases" do
@user.flag_for_fraud!(author_id: @admin_user.id)
@user.suspend_for_fraud!(author_id: @admin_user.id)
described_class.new.perform(@user.id, @admin_user.id)
expect(RefundPurchaseWorker).to have_enqueued_sidekiq_job(@purchase.id, @admin_user.id)
expect(@purchase.purchase_success_balance.unpaid?).to be(true)
expect(RefundPurchaseWorker).not_to have_enqueued_sidekiq_job(@purchase_without_balance.id, @admin_user.id)
expect(RefundPurchaseWorker).not_to have_enqueued_sidekiq_job(@purchase_with_paid_balance.id, @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/send_last_post_job_spec.rb | spec/sidekiq/send_last_post_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SendLastPostJob do
describe "#perform" do
let(:product) { create(:membership_product) }
let(:tier) { product.default_tier }
let(:purchase) { create(:membership_purchase, link: product, seller: product.user, tier:) }
let(:recipient) { { email: purchase.email, purchase:, subscription: purchase.subscription } }
let!(:product_post) { create(:post, :published, link: product, published_at: 1.day.ago) }
let!(:variant_post) { create(:variant_post, :published, link: product, base_variant: tier, published_at: 1.day.ago) }
let!(:seller_post) { create(:seller_post, :published, seller: product.user, published_at: 1.day.ago) }
before do
# invalid because different product
create(:post, :published, link: create(:product, user: purchase.seller))
# invalid because workflow post
create(:post, :published, link: purchase.link, workflow: create(:workflow))
# invalid because different variant
base_variant = create(:variant, variant_category: create(:variant_category, link: product))
create(:variant_post, :published, link: product, base_variant:)
# invalid because not published
create(:post, link: product)
# invalid because deleted
create(:post, :published, link: product, deleted_at: Time.current)
# invalid because send_emails: false
create(:post, :published, link: product, send_emails: false, shown_on_profile: true)
# invalid because purchase does not pass filters
create(:post, :published, link: product, created_before: 1.day.ago)
end
shared_examples_for "sending latest post" do
before { post.update!(published_at: 1.minute.ago) }
it "sends that post" do
expect(PostSendgridApi).to receive(:process).with(post:, recipients: [recipient])
described_class.new.perform(purchase.id)
end
end
context "when the last valid post is a product post" do
let(:post) { product_post }
it_behaves_like "sending latest post"
end
context "when the last valid post is a variant post" do
let(:post) { variant_post }
it_behaves_like "sending latest post"
end
context "when the last valid post is a seller post" do
let(:post) { seller_post }
it_behaves_like "sending latest post"
end
context "when the post has files" do
before do
product_post.update!(published_at: 1.minute.ago)
product_post.product_files << create(:pdf_product_file)
end
it "creates and uses UrlRedirect" do
allow(PostSendgridApi).to receive(:process)
expect do
described_class.new.perform(purchase.id)
end.to change { UrlRedirect.count }.by(1)
url_redirect = UrlRedirect.last!
expect(url_redirect.installment).to eq(product_post)
expect(url_redirect.subscription).to eq(purchase.subscription)
recipient[:url_redirect] = url_redirect
expect(PostSendgridApi).to have_received(:process).with(post: product_post, recipients: [recipient])
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/publish_scheduled_post_job_spec.rb | spec/sidekiq/publish_scheduled_post_job_spec.rb | # frozen_string_literal: true
describe PublishScheduledPostJob, :freeze_time do
before do
@post = create(:audience_installment, shown_on_profile: true, send_emails: true)
@rule = create(:installment_rule, installment: @post)
end
describe "#perform" do
it "publishes post, creates a blast and enqueues SendPostBlastEmailsJob when send_emails? is true" do
described_class.new.perform(@post.id, @rule.version)
expect(@post.reload.published?).to eq(true)
blast = PostEmailBlast.where(post: @post).last!
expect(blast.requested_at).to eq(@rule.to_be_published_at)
expect(SendPostBlastEmailsJob).to have_enqueued_sidekiq_job(blast.id)
end
it "publishes post but does not create a blast when there was already one" do
create(:blast, post: @post)
expect do
described_class.new.perform(@post.id, @rule.version)
end.not_to change(PostEmailBlast, :count)
expect(@post.reload.published?).to eq(true)
expect(SendPostBlastEmailsJob.jobs).to be_empty
end
it "publishes post but does not enqueue SendPostBlastEmailsJob when send_emails? is false" do
@post.update!(send_emails: false)
described_class.new.perform(@post.id, @rule.version)
expect(@post.reload.published?).to eq(true)
expect(SendPostBlastEmailsJob.jobs).to be_empty
end
it "does not publish post if the post is deleted" do
@post.mark_deleted!
described_class.new.perform(@post.id, @rule.version)
expect(@post.reload.published?).to eq(false)
expect(SendPostBlastEmailsJob.jobs).to be_empty
end
it "does not send emails if the post is already published" do
@post.publish!
described_class.new.perform(@post.id, @rule.version)
expect(@post.reload.published?).to eq(true)
expect(SendPostBlastEmailsJob.jobs).to be_empty
end
it "does not publish post if rule has a different version" do
described_class.new.perform(@post.id, @rule.version + 1)
expect(@post.reload.published?).to eq(false)
expect(SendPostBlastEmailsJob.jobs).to be_empty
end
it "does not publish post if rule is deleted" do
@rule.mark_deleted!
described_class.new.perform(@post.id, @rule.version)
expect(@post.reload.published?).to eq(false)
expect(SendPostBlastEmailsJob.jobs).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/create_stripe_apple_pay_domain_worker_spec.rb | spec/sidekiq/create_stripe_apple_pay_domain_worker_spec.rb | # frozen_string_literal: true
describe CreateStripeApplePayDomainWorker, :vcr do
describe "#perform" do
before do
@user = create(:user, username: "sampleusername")
allow(Subdomain).to receive(:from_username).and_return("sampleusername.gumroad.dev")
allow(Rails.env).to receive(:test?).and_return(false)
end
it "creates Stripe::ApplePayDomain and persists StripeApplePayDomain" do
described_class.new.perform(@user.id)
expect(StripeApplePayDomain.last.stripe_id).to match(/apwc/)
expect(StripeApplePayDomain.last.domain).to eq("sampleusername.gumroad.dev")
expect(StripeApplePayDomain.last.user_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/reindex_user_elasticsearch_data_worker_spec.rb | spec/sidekiq/reindex_user_elasticsearch_data_worker_spec.rb | # frozen_string_literal: true
describe ReindexUserElasticsearchDataWorker do
it "reindexes ES data for user" do
user = create(:user)
admin = create(:admin_user)
allow(DevTools).to receive(:reindex_all_for_user).and_return(nil)
expect(DevTools).to receive(:reindex_all_for_user).with(user.id)
described_class.new.perform(user.id, admin.id)
admin_comment = user.comments.last
expect(admin_comment.content).to eq("Refreshed ES Data")
expect(admin_comment.author_id).to eq(admin.id)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/generate_sales_report_job_spec.rb | spec/sidekiq/generate_sales_report_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GenerateSalesReportJob do
let (:country_code) { "GB" }
let(:start_date) { Date.new(2015, 1, 1) }
let (:end_date) { Date.new(2015, 3, 31) }
it "raises an argument error if the country code is not valid" do
expect { described_class.new.perform("AUS", start_date, end_date, GenerateSalesReportJob::ALL_SALES) }.to raise_error(ArgumentError)
end
it "raises an argument error if the sales_type is neither all_sales nor discover_sales" do
expect { described_class.new.perform("AU", start_date, end_date, nil) }.to raise_error(ArgumentError)
expect { described_class.new.perform("AU", start_date, end_date, "abc") }.to raise_error(ArgumentError)
expect { described_class.new.perform("AU", start_date, end_date, "all") }.to raise_error(ArgumentError)
expect { described_class.new.perform("AU", start_date, end_date, "discover") }.to raise_error(ArgumentError)
expect { described_class.new.perform("AU", start_date, end_date, GenerateSalesReportJob::ALL_SALES) }.not_to raise_error(ArgumentError)
expect { described_class.new.perform("AU", start_date, end_date, GenerateSalesReportJob::DISCOVER_SALES) }.not_to raise_error(ArgumentError)
end
describe "happy case", :vcr do
before do
@mock_service = double("ExpiringS3FileService")
allow(ExpiringS3FileService).to receive(:new).and_return(@mock_service)
allow(@mock_service).to receive(:perform).and_return("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/test-url")
end
before do
travel_to(Time.zone.local(2015, 1, 1)) do
product = create(:product, price_cents: 100_00, native_type: "digital")
@purchase1 = create(:purchase_in_progress, link: product, country: "United Kingdom")
@purchase2 = create(:purchase_in_progress, link: product, country: "Australia")
@purchase3 = create(:purchase_in_progress, link: product, country: "United Kingdom")
@purchase4 = create(:purchase_in_progress, link: product, country: "Singapore")
@purchase5 = create(:purchase_in_progress, link: product, country: "United Kingdom")
@purchase6 = create(:purchase_in_progress, link: product, recommended_by: RecommendationType::GUMROAD_DISCOVER_RECOMMENDATION, country: "United Kingdom")
@purchase7 = create(:purchase_in_progress, link: product, recommended_by: RecommendationType::GUMROAD_SEARCH_RECOMMENDATION, country: "United Kingdom")
@purchase8 = create(:purchase_in_progress, link: product, recommended_by: RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION, country: "United Kingdom")
@purchase9 = create(:purchase_in_progress, link: product, recommended_by: RecommendationType::GUMROAD_STAFF_PICKS_RECOMMENDATION, country: "United Kingdom")
Purchase.in_progress.find_each do |purchase|
purchase.chargeable = create(:chargeable)
purchase.process!
purchase.update_balance_and_mark_successful!
end
end
end
it "creates a CSV file for sales into the United Kingdom" do
expect(ExpiringS3FileService).to receive(:new) do |args|
expect(args[:path]).to eq("sales-tax/gb-sales-quarterly")
expect(args[:filename]).to include("united-kingdom-all-sales-report-2015-01-01-to-2015-03-31")
expect(args[:bucket]).to eq(REPORTING_S3_BUCKET)
expect(args[:expiry]).to eq(1.week)
@mock_service
end
described_class.new.perform(country_code, start_date, end_date, GenerateSalesReportJob::ALL_SALES)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "VAT Reporting", anything, "green")
end
it "creates a CSV file for sales into Australia" do
expect(ExpiringS3FileService).to receive(:new) do |args|
expect(args[:path]).to eq("sales-tax/au-sales-quarterly")
expect(args[:filename]).to include("australia-all-sales-report-2015-01-01-to-2015-03-31")
expect(args[:bucket]).to eq(REPORTING_S3_BUCKET)
expect(args[:expiry]).to eq(1.week)
@mock_service
end
described_class.new.perform("AU", start_date, end_date, GenerateSalesReportJob::ALL_SALES)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "GST Reporting", anything, "green")
end
it "creates a CSV file for sales into Singapore" do
expect(ExpiringS3FileService).to receive(:new) do |args|
expect(args[:path]).to eq("sales-tax/sg-sales-quarterly")
expect(args[:filename]).to include("singapore-all-sales-report-2015-01-01-to-2015-03-31")
expect(args[:bucket]).to eq(REPORTING_S3_BUCKET)
expect(args[:expiry]).to eq(1.week)
@mock_service
end
described_class.new.perform("SG", start_date, end_date, GenerateSalesReportJob::ALL_SALES)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "GST Reporting", anything, "green")
end
it "creates a CSV file for sales into the United Kingdom and does not send slack notification when send_notification is false",
vcr: { cassette_name: "GenerateSalesReportJob/happy_case/creates_a_CSV_file_for_sales_into_the_United_Kingdom" } do
expect(ExpiringS3FileService).to receive(:new).and_return(@mock_service)
described_class.new.perform(country_code, start_date, end_date, GenerateSalesReportJob::ALL_SALES, false)
expect(SlackMessageWorker.jobs.size).to eq(0)
end
it "creates a CSV file for sales into the United Kingdom and sends slack notification when send_notification is true",
vcr: { cassette_name: "GenerateSalesReportJob/happy_case/creates_a_CSV_file_for_sales_into_the_United_Kingdom" } do
expect(ExpiringS3FileService).to receive(:new).and_return(@mock_service)
described_class.new.perform(country_code, start_date, end_date, GenerateSalesReportJob::ALL_SALES, true)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "VAT Reporting", anything, "green")
end
it "creates a CSV file for sales into the United Kingdom and sends slack notification when send_slack_notification is not provided (default behavior)",
vcr: { cassette_name: "GenerateSalesReportJob/happy_case/creates_a_CSV_file_for_sales_into_the_United_Kingdom" } do
expect(ExpiringS3FileService).to receive(:new).and_return(@mock_service)
described_class.new.perform(country_code, start_date, end_date, GenerateSalesReportJob::ALL_SALES)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "VAT Reporting", anything, "green")
end
it "creates a CSV file for discover sales into the United Kingdom sales_type is set as discover_sales",
vcr: { cassette_name: "GenerateSalesReportJob/happy_case/creates_a_CSV_file_for_discover_sales_into_the_United_Kingdom" } do
expect(ExpiringS3FileService).to receive(:new) do |args|
expect(args[:path]).to eq("sales-tax/gb-sales-quarterly")
expect(args[:filename]).to include("united-kingdom-discover-sales-report-2015-01-01-to-2015-03-31")
expect(args[:bucket]).to eq(REPORTING_S3_BUCKET)
expect(args[:expiry]).to eq(1.week)
@mock_service
end
described_class.new.perform(country_code, start_date, end_date, GenerateSalesReportJob::DISCOVER_SALES)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "VAT Reporting", anything, "green")
end
end
describe "s3_prefix functionality", :vcr do
before do
@mock_service = double("ExpiringS3FileService")
allow(ExpiringS3FileService).to receive(:new).and_return(@mock_service)
allow(@mock_service).to receive(:perform).and_return("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/test-url")
end
before do
travel_to(Time.zone.local(2015, 1, 1)) do
product = create(:product, price_cents: 100_00, native_type: "digital")
@purchase = create(:purchase_in_progress, link: product, country: "United Kingdom")
@purchase.chargeable = create(:chargeable)
@purchase.process!
@purchase.update_balance_and_mark_successful!
end
end
it "uses custom s3_prefix when provided" do
custom_prefix = "custom/reports"
expect(ExpiringS3FileService).to receive(:new) do |args|
expect(args[:path]).to eq("#{custom_prefix}/sales-tax/gb-sales-quarterly")
expect(args[:filename]).to include("united-kingdom-all-sales-report-2015-01-01-to-2015-03-31")
expect(args[:bucket]).to eq(REPORTING_S3_BUCKET)
@mock_service
end
described_class.new.perform(country_code, start_date, end_date, GenerateSalesReportJob::ALL_SALES, true, custom_prefix)
end
it "handles s3_prefix with trailing slash" do
custom_prefix = "custom/reports/"
expect(ExpiringS3FileService).to receive(:new) do |args|
expect(args[:path]).to eq("custom/reports/sales-tax/gb-sales-quarterly")
expect(args[:filename]).to include("united-kingdom-all-sales-report-2015-01-01-to-2015-03-31")
expect(args[:bucket]).to eq(REPORTING_S3_BUCKET)
@mock_service
end
described_class.new.perform(country_code, start_date, end_date, GenerateSalesReportJob::ALL_SALES, true, custom_prefix)
end
it "uses default path when s3_prefix is nil" do
expect(ExpiringS3FileService).to receive(:new) do |args|
expect(args[:path]).to eq("sales-tax/gb-sales-quarterly")
expect(args[:filename]).to include("united-kingdom-all-sales-report-2015-01-01-to-2015-03-31")
expect(args[:bucket]).to eq(REPORTING_S3_BUCKET)
@mock_service
end
described_class.new.perform(country_code, start_date, end_date, GenerateSalesReportJob::ALL_SALES, true, nil)
end
it "uses default path when s3_prefix is empty string" do
expect(ExpiringS3FileService).to receive(:new) do |args|
expect(args[:path]).to eq("sales-tax/gb-sales-quarterly")
expect(args[:filename]).to include("united-kingdom-all-sales-report-2015-01-01-to-2015-03-31")
expect(args[:bucket]).to eq(REPORTING_S3_BUCKET)
@mock_service
end
described_class.new.perform(country_code, start_date, end_date, GenerateSalesReportJob::ALL_SALES, 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/send_reminders_for_outstanding_user_compliance_info_requests_worker_spec.rb | spec/sidekiq/send_reminders_for_outstanding_user_compliance_info_requests_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SendRemindersForOutstandingUserComplianceInfoRequestsWorker do
describe "#perform" do
let(:user_1) { create(:user) }
let(:user_2) { create(:user) }
let(:user_3) { create(:user) }
let(:user_4) { create(:user) }
let(:user_5) { create(:user) }
let(:user_6) { create(:user) }
let(:user_7) { create(:user) }
let(:user_8) { create(:user, deleted_at: 1.minute.ago) }
let(:user_9) do
user = create(:user)
admin = create(:admin_user)
user.flag_for_fraud!(author_id: admin.id)
user.suspend_for_fraud!(author_id: admin.id)
user
end
let!(:user_1_request_1) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::FIRST_NAME, user: user_1) }
let!(:user_1_request_2) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::LAST_NAME, user: user_1) }
let!(:user_1_request_3) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::TAX_ID, user: user_1) }
let!(:user_2_request_1) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::TAX_ID, user: user_2) }
let!(:user_3_request_1) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::TAX_ID, user: user_3) }
let!(:user_4_request_1) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::TAX_ID, user: user_4) }
let!(:user_5_request_1) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::TAX_ID, user: user_5) }
let!(:user_6_request_1) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::FIRST_NAME, user: user_6) }
let!(:user_6_request_2) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::LAST_NAME, user: user_6) }
let!(:user_7_request_1) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::TAX_ID, user: user_7) }
let!(:user_8_request_1) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::FIRST_NAME, user: user_8) }
let!(:user_9_request_1) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::FIRST_NAME, user: user_9) }
let(:time_now) { Time.current.change(usec: 0) }
before do
travel_to(time_now)
end
before do
user_2_request_1.record_email_sent!(Time.current)
user_3_request_1.record_email_sent!(1.day.ago)
user_4_request_1.record_email_sent!(2.days.ago)
user_5_request_1.record_email_sent!(3.days.ago)
user_6_request_1.record_email_sent!(3.days.ago)
user_7_request_1.record_email_sent!(10.days.ago)
user_7_request_1.record_email_sent!(8.days.ago)
described_class.new.perform
user_1_request_1.reload
user_1_request_2.reload
user_1_request_3.reload
user_2_request_1.reload
user_3_request_1.reload
user_4_request_1.reload
user_5_request_1.reload
user_6_request_1.reload
user_6_request_2.reload
user_7_request_1.reload
end
it "reminds a user of all the outstanding requests, if they have never been reminded" do
expect(user_1_request_1.emails_sent_at).to eq([Time.current])
expect(user_1_request_2.emails_sent_at).to eq([Time.current])
expect(user_1_request_3.emails_sent_at).to eq([Time.current])
end
it "does not remind a user who was just reminded" do
expect(user_2_request_1.emails_sent_at).to eq([Time.current])
end
it "does not remind a user who was reminded less than 2 days ago" do
expect(user_3_request_1.emails_sent_at).to eq([1.day.ago])
end
it "does not remind a user who was reminded 2 days ago" do
expect(user_4_request_1.emails_sent_at).to eq([2.days.ago])
end
it "reminds a user who was reminded more than 2 days ago" do
expect(user_5_request_1.emails_sent_at).to eq([3.days.ago, Time.current])
expect(user_6_request_1.emails_sent_at).to eq([3.days.ago, Time.current])
expect(user_6_request_2.emails_sent_at).to eq([Time.current])
end
it "does not remind a user who was reminded twice already" do
expect(user_7_request_1.emails_sent_at).to eq([10.days.ago, 8.days.ago])
end
it "does not remind a deleted user" do
expect(user_8_request_1.emails_sent_at).to be_empty
end
it "does not remind a suspended user" do
expect(user_9_request_1.emails_sent_at).to be_empty
end
end
describe "singapore identity verification requests", :vcr do
before do
@user = create(:user)
create(:merchant_account, user: @user, country: "SG")
@sg_verification_request = create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::STRIPE_ENHANCED_IDENTITY_VERIFICATION, user: @user)
end
it "reminds a user of the outstanding request if they have never been reminded" do
described_class.new.perform
expect(Time.zone.parse(@sg_verification_request.reload.sg_verification_reminder_sent_at)).to eq(Time.current.change(usec: 0))
end
it "does not remind a user who was reminded less than 7 days ago" do
@sg_verification_request.sg_verification_reminder_sent_at = 6.days.ago
@sg_verification_request.save!
described_class.new.perform
expect(Time.zone.parse(@sg_verification_request.reload.sg_verification_reminder_sent_at)).to eq(6.days.ago.change(usec: 0))
end
it "reminds a user who was reminded more than 7 days ago" do
@sg_verification_request.sg_verification_reminder_sent_at = 8.days.ago
@sg_verification_request.save!
described_class.new.perform
expect(Time.zone.parse(@sg_verification_request.reload.sg_verification_reminder_sent_at)).to eq(Time.current.change(usec: 0))
end
it "does not remind a user if their account was created more than 120 days ago" do
user = create(:user)
create(:merchant_account, user:, country: "SG", created_at: 121.days.ago)
sg_verification_request = create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::STRIPE_ENHANCED_IDENTITY_VERIFICATION, user:)
described_class.new.perform
expect(sg_verification_request.reload.sg_verification_reminder_sent_at).to be_nil
end
it "does not remind a deleted user" do
@user.update!(deleted_at: 1.minute.ago)
described_class.new.perform
expect(@sg_verification_request.reload.sg_verification_reminder_sent_at).to be_nil
end
it "does not remind a suspended user" do
@user.flag_for_fraud!(author_id: @user.id)
@user.suspend_for_fraud!(author_id: @user.id)
described_class.new.perform
expect(@sg_verification_request.reload.sg_verification_reminder_sent_at).to be_nil
end
it "does not remind if user's current stripe account is not a singapore account" do
user = create(:user)
sg_verification_request = create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::STRIPE_ENHANCED_IDENTITY_VERIFICATION, user:)
create(:merchant_account, user:, country: "US")
described_class.new.perform
expect(sg_verification_request.reload.sg_verification_reminder_sent_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/update_installment_events_count_cache_worker_spec.rb | spec/sidekiq/update_installment_events_count_cache_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateInstallmentEventsCountCacheWorker do
describe "#perform" do
it "calculates and caches the correct installment_events count" do
installment = create(:installment)
create_list(:installment_event, 2, installment:)
UpdateInstallmentEventsCountCacheWorker.new.perform(installment.id)
installment.reload
expect(installment.installment_events_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/renew_facebook_access_tokens_worker_spec.rb | spec/sidekiq/renew_facebook_access_tokens_worker_spec.rb | # frozen_string_literal: true
describe RenewFacebookAccessTokensWorker do
describe "#perform" do
before do
@oauth = double "oauth"
allow(Koala::Facebook::OAuth).to receive(:new).and_return @oauth
end
it "renews tokens for accounts with tokens updated < 30 days ago" do
create(:user, updated_at: Date.today, facebook_access_token: "old token")
expect(@oauth).to receive(:exchange_access_token).and_return("new access token")
RenewFacebookAccessTokensWorker.new.perform
end
it "doesn't renew tokens for accounts without tokens" do
create(:user, updated_at: Date.today, facebook_access_token: nil)
expect(@oauth).to_not receive(:exchange_access_token)
RenewFacebookAccessTokensWorker.new.perform
end
it "doesn't renew tokens for accounts updated > 30 days ago with or without token" do
create(:user, updated_at: Date.today - 31, facebook_access_token: nil)
create(:user, updated_at: Date.today - 31, facebook_access_token: "old old old token")
expect(@oauth).to_not receive(:exchange_access_token)
RenewFacebookAccessTokensWorker.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_membership_price_updates_job_spec.rb | spec/sidekiq/schedule_membership_price_updates_job_spec.rb | # frozen_string_literal: true
describe ScheduleMembershipPriceUpdatesJob do
describe "perform" do
context "for a non-tiered membership variant" do
it "does nothing" do
variant = create(:variant)
purchase = create(:purchase, variant_attributes: [variant])
create(:subscription, original_purchase: purchase)
expect do
described_class.new.perform(variant.id)
end.not_to change { SubscriptionPlanChange.count }
end
end
context "for a membership tier" do
let(:yearly_price) { 10_99 }
let(:product) do
recurrence_price_values = [
{ monthly: { enabled: true, price: 3 }, yearly: { enabled: true, price: yearly_price / 100.0 } },
{ monthly: { enabled: true, price: 5 }, yearly: { enabled: true, price: 24.99 } }
]
create(:membership_product_with_preset_tiered_pricing, recurrence_price_values:)
end
let(:effective_on) { 7.days.from_now.to_date }
let(:enabled_tier) do
tier = product.tiers.first
tier.update!(apply_price_changes_to_existing_memberships: true, subscription_price_change_effective_date: effective_on)
tier
end
let(:disabled_tier) { product.tiers.last }
let(:new_price) { enabled_tier.prices.find_by(recurrence: "monthly").price_cents }
let(:original_price) { new_price - 1_00 }
let(:enabled_subscription) { create(:membership_purchase, price_cents: original_price, link: product, variant_attributes: [enabled_tier]).subscription }
let(:disabled_subscription) { create(:membership_purchase, link: product, variant_attributes: [disabled_tier]).subscription }
context "for a tier with apply_price_changes_to_existing_memberships disabled" do
it "does nothing" do
described_class.new.perform(disabled_tier.id)
expect(SubscriptionPlanChange.count).to eq(0)
end
context "that has a pending plan change to an enabled tier" do
it "records a plan change" do
subscription = create(:membership_purchase, link: product, variant_attributes: [disabled_tier]).subscription
create(:subscription_plan_change, subscription:, tier: enabled_tier)
described_class.new.perform(enabled_tier.id)
expect(subscription.subscription_plan_changes.for_product_price_change.alive.count).to eq(1)
end
end
end
context "for a tier with apply_price_changes_to_existing_memberships enabled" do
it "records a plan change for each live or pending cancellation subscription on the next charge after the effective date" do
effective_on_next_billing_period = create(:membership_purchase, link: product, variant_attributes: [enabled_tier], succeeded_at: 2.weeks.ago).subscription
effective_in_two_billing_periods = create(:membership_purchase, link: product, variant_attributes: [enabled_tier], succeeded_at: 25.days.ago).subscription
pending_cancellation = create(:membership_purchase, link: product, variant_attributes: [enabled_tier], succeeded_at: 2.weeks.ago).tap do
_1.subscription.update!(cancelled_at: 1.day.ago)
end.subscription
create(:membership_purchase, link: product, variant_attributes: [disabled_tier])
create(:membership_purchase, variant_attributes: [disabled_tier])
create(:membership_purchase)
expect do
described_class.new.perform(enabled_tier.id)
end.to change { SubscriptionPlanChange.count }.by(3)
.and change { Purchase.count }.by(0) # test that `Subscription#update_current_plan!` changes are rolled back
expect(effective_on_next_billing_period.subscription_plan_changes.for_product_price_change.alive.count).to eq(1)
expect(effective_on_next_billing_period.subscription_plan_changes.sole.effective_on).to eq(effective_on_next_billing_period.end_time_of_subscription.to_date)
expect(pending_cancellation.subscription_plan_changes.for_product_price_change.alive.count).to eq(1)
expect(pending_cancellation.subscription_plan_changes.sole.effective_on).to eq(pending_cancellation.end_time_of_subscription.to_date)
expect(effective_in_two_billing_periods.subscription_plan_changes.for_product_price_change.alive.count).to eq(1)
expect(effective_in_two_billing_periods.subscription_plan_changes.sole.effective_on).to eq(
(effective_in_two_billing_periods.end_time_of_subscription + effective_in_two_billing_periods.period).to_date
)
end
context "when the subscription has an offer code" do
it "applies the offer code when calculating the new price" do
offer_code = create(:offer_code, user: product.user, amount_cents: 1_50)
enabled_subscription.original_purchase.update!(offer_code:)
expect do
described_class.new.perform(enabled_tier.id)
end.to change { enabled_subscription.subscription_plan_changes.count }.by(1)
.and change { Purchase.count }.by(0) # test that `Subscription#update_current_plan!` changes are rolled back
latest_plan_change = enabled_subscription.subscription_plan_changes.for_product_price_change.last
expect(latest_plan_change.tier).to eq enabled_tier
expect(latest_plan_change.recurrence).to eq enabled_subscription.recurrence
expect(latest_plan_change.perceived_price_cents).to eq new_price - 1_50
end
end
context "when the subscription has a pending plan change" do
context "that will switch away from the given tier" do
it "does nothing" do
create(:subscription_plan_change, subscription: enabled_subscription, tier: disabled_tier)
expect do
described_class.new.perform(enabled_tier.id)
end.not_to change { enabled_subscription.subscription_plan_changes.count }
end
end
context "that will switch to the given tier" do
it "records a subscription plan change if the price is different from the agreed on price" do
create(:subscription_plan_change, subscription: disabled_subscription, tier: enabled_tier, perceived_price_cents: new_price - 1)
expect do
described_class.new.perform(enabled_tier.id)
end.to change { disabled_subscription.purchases.count }.by(0) # test that `Subscription#update_current_plan!` changes are rolled back
.and change { disabled_subscription.subscription_plan_changes.count }.by(1)
latest_plan_change = disabled_subscription.subscription_plan_changes.for_product_price_change.last
expect(latest_plan_change.tier).to eq enabled_tier
expect(latest_plan_change.recurrence).to eq enabled_subscription.recurrence
expect(latest_plan_change.perceived_price_cents).to eq new_price
expect(latest_plan_change.effective_on).to eq(disabled_subscription.end_time_of_subscription.to_date)
end
it "does nothing but notify Bugsnag if the price is the same as the agreed on price" do
expect(Bugsnag).to receive(:notify).with("Not adding a plan change for membership price change - subscription_id: #{disabled_subscription.id} - reason: price has not changed")
create(:subscription_plan_change, subscription: disabled_subscription, tier: enabled_tier, perceived_price_cents: new_price)
expect do
described_class.new.perform(enabled_tier.id)
end.not_to change { disabled_subscription.subscription_plan_changes.count }
end
end
context "that switches billing periods" do
it "records a subscription plan change if the new price is different from the agreed on price" do
create(:subscription_plan_change, subscription: enabled_subscription, tier: enabled_tier, recurrence: "yearly", perceived_price_cents: yearly_price - 1)
expect do
described_class.new.perform(enabled_tier.id)
end.to change { enabled_subscription.purchases.count }.by(0)
.and change { enabled_subscription.subscription_plan_changes.count }.by(1)
latest_plan_change = enabled_subscription.subscription_plan_changes.for_product_price_change.last
expect(latest_plan_change.tier).to eq enabled_tier
expect(latest_plan_change.recurrence).to eq "yearly"
expect(latest_plan_change.perceived_price_cents).to eq yearly_price
end
it "does nothing but notify Bugsnag if the new price is the same as the agreed on price" do
expect(Bugsnag).to receive(:notify).with("Not adding a plan change for membership price change - subscription_id: #{enabled_subscription.id} - reason: price has not changed")
create(:subscription_plan_change, subscription: enabled_subscription, tier: enabled_tier, recurrence: "yearly", perceived_price_cents: yearly_price)
expect do
described_class.new.perform(enabled_tier.id)
end.not_to change { enabled_subscription.subscription_plan_changes.count }
end
end
it "deletes existing plan changes for product price changes, but not user-initiated plan changes" do
by_user = create(:subscription_plan_change, subscription: disabled_subscription, tier: enabled_tier, perceived_price_cents: new_price - 1)
for_price_change = create(:subscription_plan_change, subscription: disabled_subscription, for_product_price_change: true)
described_class.new.perform(enabled_tier.id)
expect(by_user.reload).not_to be_deleted
expect(for_price_change.reload).to be_deleted
end
context "but updating the subscription raises an error" do
it "rolls back the transaction and does not retry" do
allow_any_instance_of(Subscription).to receive(:update_current_plan!).and_raise(Subscription::UpdateFailed)
create(:subscription_plan_change, subscription: disabled_subscription, tier: enabled_tier, perceived_price_cents: new_price - 1)
expect do
described_class.new.perform(enabled_tier.id)
end.not_to change { disabled_subscription.purchases.count }
expect(described_class.jobs.size).to eq(0)
end
end
end
context "for a fixed length subscription that has completed its charges" do
it "does nothing" do
sub = create(:membership_purchase, link: product, variant_attributes: [enabled_tier]).subscription
sub.update!(charge_occurrence_count: 1)
expect do
described_class.new.perform(enabled_tier.id)
end.not_to change { sub.reload.subscription_plan_changes.count }
end
end
context "for a subscription that is inactive" do
it "does nothing" do
enabled_subscription.deactivate!
expect do
described_class.new.perform(enabled_tier.id)
end.not_to change { enabled_subscription.subscription_plan_changes.count }
end
end
context "when the price has not changed" do
it "does nothing but notify Bugsnag" do
expect(Bugsnag).to receive(:notify).with("Not adding a plan change for membership price change - subscription_id: #{enabled_subscription.id} - reason: price has not changed")
enabled_subscription.original_purchase.update!(displayed_price_cents: new_price)
expect do
described_class.new.perform(enabled_tier.id)
end.not_to change { enabled_subscription.subscription_plan_changes.count }
end
end
context "when the price for a recurrence is deleted" do
it "does nothing but notify Bugsnag" do
enabled_tier.prices.alive.find_by(recurrence: "monthly").mark_deleted!
expect(Bugsnag).to receive(:notify).with(/subscription_id: #{enabled_subscription.id} - reason: zero or negative price/)
expect do
described_class.new.perform(enabled_tier.id)
end.not_to change { enabled_subscription.reload.subscription_plan_changes.count }
zero_price_plan_changes = enabled_subscription.subscription_plan_changes
.for_product_price_change
.where(perceived_price_cents: 0)
expect(zero_price_plan_changes.count).to eq(0)
expect(enabled_subscription.current_subscription_price_cents).to eq(original_price)
expect(enabled_subscription.latest_applicable_plan_change).to be_nil
expect(enabled_subscription.build_purchase.perceived_price_cents).to eq(original_price)
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/create_missing_purchase_events_worker_spec.rb | spec/sidekiq/create_missing_purchase_events_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CreateMissingPurchaseEventsWorker do
let!(:purchase) do
create(:purchase, created_at: 1.day.ago, ip_country: "United States", ip_state: "CA") do |purchase|
purchase.seller.update!(timezone: "UTC")
end
end
it "creates the missing event and regenerate cached analytics for that day" do
described_class.new.perform
expect(Event.first!.attributes.symbolize_keys).to include(
event_name: "purchase",
created_at: purchase.created_at,
user_id: purchase.purchaser_id,
link_id: purchase.link_id,
purchase_id: purchase.id,
ip_address: purchase.ip_address,
referrer: purchase.referrer,
referrer_domain: Referrer.extract_domain(purchase.referrer),
price_cents: purchase.price_cents,
card_type: purchase.card_type,
card_visual: purchase.card_visual,
purchase_state: purchase.purchase_state,
billing_zip: purchase.zip_code,
ip_country: purchase.ip_country,
ip_state: purchase.ip_state,
browser_guid: purchase.browser_guid,
visit_id: Event.flag_mapping["visit_id"][:manufactured],
)
expect(RegenerateCreatorAnalyticsCacheWorker).to have_enqueued_sidekiq_job(purchase.seller_id, Date.yesterday.to_s)
end
it "does not create another event if it already exists" do
create(:event, event_name: "purchase", link_id: purchase.link_id, purchase_id: purchase.id)
described_class.new.perform
expect(Event.count).to eq(1)
expect(RegenerateCreatorAnalyticsCacheWorker.jobs.size).to eq(0)
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_sent_email_info_records_job_spec.rb | spec/sidekiq/delete_old_sent_email_info_records_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DeleteOldSentEmailInfoRecordsJob do
describe "#perform" do
it "deletes targeted rows" do
create(:sent_email_info, created_at: 3.years.ago)
create(:sent_email_info, created_at: 2.years.ago)
create(:sent_email_info, created_at: 6.months.ago)
expect(SentEmailInfo.count).to eq(3)
described_class.new.perform
expect(SentEmailInfo.count).to eq(1)
end
it "does not fail when there are no 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/set_subscription_as_deactivated_worker_spec.rb | spec/sidekiq/set_subscription_as_deactivated_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SetSubscriptionAsDeactivatedWorker do
describe "#perform" do
it "sets subscription as deactivated" do
product = create(:membership_product)
purchase = create(:membership_purchase, link: product)
subscription = purchase.subscription
subscription.update!(cancelled_at: 1.day.ago)
described_class.new.perform(subscription.id)
expect(subscription.reload.deactivated_at).not_to eq(nil)
end
it "does not set subscriptions cancelled in the future as deactivated" do
subscription = create(:subscription, cancelled_at: 1.day.from_now)
described_class.new.perform(subscription.id)
expect(subscription.reload.deactivated_at).to eq(nil)
end
it "does not set alive subscription as deactivated" do
subscription = create(:subscription)
described_class.new.perform(subscription.id)
expect(subscription.reload.deactivated_at).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/check_payment_address_worker_spec.rb | spec/sidekiq/check_payment_address_worker_spec.rb | # frozen_string_literal: true
describe CheckPaymentAddressWorker do
before do
@previously_banned_user = create(:user, user_risk_state: "suspended_for_fraud", payment_address: "tuhins@gmail.com")
@blocked_email_object = BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], "fraudulent_email@zombo.com", nil)
end
it "does not flag the user for fraud if there are no other banned users with the same payment address" do
@user = create(:user, payment_address: "cleanuser@gmail.com")
CheckPaymentAddressWorker.new.perform(@user.id)
expect(@user.reload.flagged?).to be(false)
end
it "flags the user for fraud if there are other banned users with the same payment address" do
@user = create(:user, payment_address: "tuhins@gmail.com")
CheckPaymentAddressWorker.new.perform(@user.id)
expect(@user.reload.flagged?).to be(true)
end
it "flags the user for fraud if a blocked email object exists for their payment address" do
@user = create(:user, payment_address: "fraudulent_email@zombo.com")
CheckPaymentAddressWorker.new.perform(@user.id)
expect(@user.reload.flagged?).to be(true)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/generate_canada_sales_report_job_spec.rb | spec/sidekiq/generate_canada_sales_report_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GenerateCanadaSalesReportJob do
let(:month) { 8 }
let(:year) { 2022 }
it "raises an argument error if the year is out of bounds" do
expect { described_class.new.perform(month, 2013) }.to raise_error(ArgumentError)
end
it "raises an agrument error if the month is out of bounds" do
expect { described_class.new.perform(13, year) }.to raise_error(ArgumentError)
end
describe "happy case", :vcr do
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/canada-sales-reporting-spec-#{SecureRandom.hex(18)}.zip")
end
before do
canada_product = nil
spain_product = nil
travel_to(Time.find_zone("UTC").local(2022, 7, 1)) do
canada_creator = create(:user).tap do |creator|
creator.fetch_or_build_user_compliance_info.dup_and_save! do |new_compliance_info|
new_compliance_info.country = "Canada"
new_compliance_info.state = "BC"
end
end
canada_product = create(:product, user: canada_creator, price_cents: 100_00, native_type: "digital")
spain_creator = create(:user).tap do |creator|
creator.fetch_or_build_user_compliance_info.dup_and_save! do |new_compliance_info|
new_compliance_info.country = "Spain"
end
end
spain_product = create(:product, user: spain_creator, price_cents: 100_00, native_type: "digital")
end
travel_to(Time.find_zone("UTC").local(2022, 7, 30)) do
create(:purchase_in_progress, link: canada_product, country: "Canada", state: "BC")
Purchase.in_progress.find_each do |purchase|
purchase.chargeable = create(:chargeable)
purchase.process!
purchase.update_balance_and_mark_successful!
end
end
travel_to(Time.find_zone("UTC").local(2022, 8, 1)) do
create(:purchase_in_progress, link: spain_product, country: "Spain")
@purchase1 = create(:purchase_in_progress, link: canada_product, country: "Canada", state: "ON")
@purchase2 = create(:purchase_in_progress, link: canada_product, country: "United States", zip_code: "22207")
@purchase3 = create(:purchase_in_progress, link: canada_product, country: "Spain")
Purchase.in_progress.find_each do |purchase|
purchase.chargeable = create(:chargeable)
purchase.process!
purchase.update_balance_and_mark_successful!
end
end
travel_to(Time.find_zone("UTC").local(2022, 9, 1)) do
create(:purchase_in_progress, link: canada_product, country: "Canada", state: "QC")
Purchase.in_progress.find_each do |purchase|
purchase.chargeable = create(:chargeable)
purchase.process!
purchase.update_balance_and_mark_successful!
end
end
end
it "creates a CSV file for Canada sales" do
expect(s3_bucket_double).to receive(:object).ordered.and_return(@s3_object)
described_class.new.perform(month, year)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "Canada Sales Fees 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.length).to eq(4)
expect(actual_payload[0]).to eq([
"Sale time",
"Sale ID",
"Seller ID",
"Seller Name",
"Seller Email",
"Seller Country",
"Seller Province",
"Product ID",
"Product Name",
"Product / Subscription",
"Product Type",
"Physical/Digital Product",
"Direct-To-Customer/Buy-Sell Product",
"Buyer ID",
"Buyer Name",
"Buyer Email",
"Buyer Card",
"Buyer Country",
"Buyer State",
"Price",
"Total Gumroad Fee",
"Gumroad Discover Fee",
"Creator Sales Tax",
"Gumroad Sales Tax",
"Shipping",
"Total"
])
expect(actual_payload[1]).to eq([
"2022-08-01 00:00:00 UTC",
@purchase1.external_id,
@purchase1.seller.external_id,
@purchase1.seller.name_or_username,
@purchase1.seller.form_email&.gsub(/.{0,4}@/, '####@'),
"Canada",
"British Columbia",
@purchase1.link.external_id,
"The Works of Edgar Gumstein",
"Product",
"digital",
"Digital",
"BS",
nil,
nil,
@purchase1.email&.gsub(/.{0,4}@/, '####@'),
"**** **** **** 4242",
"Canada",
"ON",
"10000",
"1370",
"0",
"0",
"0",
"0",
"10000"
])
expect(actual_payload[2]).to eq([
"2022-08-01 00:00:00 UTC",
@purchase2.external_id,
@purchase2.seller.external_id,
@purchase2.seller.name_or_username,
@purchase2.seller.form_email&.gsub(/.{0,4}@/, '####@'),
"Canada",
"British Columbia",
@purchase2.link.external_id,
"The Works of Edgar Gumstein",
"Product",
"digital",
"Digital",
"BS",
nil,
nil,
@purchase2.email&.gsub(/.{0,4}@/, '####@'),
"**** **** **** 4242",
"United States",
"Uncategorized",
"10000",
"1370",
"0",
"0",
"0",
"0",
"10000"
])
expect(actual_payload[3]).to eq([
"2022-08-01 00:00:00 UTC",
@purchase3.external_id,
@purchase3.seller.external_id,
@purchase3.seller.name_or_username,
@purchase3.seller.form_email&.gsub(/.{0,4}@/, '####@'),
"Canada",
"British Columbia",
@purchase3.link.external_id,
"The Works of Edgar Gumstein",
"Product",
"digital",
"Digital",
"BS",
nil,
nil,
@purchase3.email&.gsub(/.{0,4}@/, '####@'),
"**** **** **** 4242",
"Spain",
"Uncategorized",
"10000",
"1370",
"0",
"0",
"0",
"0",
"10000"
])
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_creator_analytics_cache_worker_spec.rb | spec/sidekiq/regenerate_creator_analytics_cache_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RegenerateCreatorAnalyticsCacheWorker do
describe "#perform" do
it "runs CreatorAnalytics::CachingProxy#overwrite_cache" do
user = create(:user)
service_object = double("CreatorAnalytics::CachingProxy object")
expect(CreatorAnalytics::CachingProxy).to receive(:new).with(user).and_return(service_object)
expect(service_object).to receive(:overwrite_cache).with(Date.new(2020, 7, 5), by: :date)
expect(service_object).to receive(:overwrite_cache).with(Date.new(2020, 7, 5), by: :state)
expect(service_object).to receive(:overwrite_cache).with(Date.new(2020, 7, 5), by: :referral)
described_class.new.perform(user.id, "2020-07-05")
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_us_state_monthly_sales_reports_job_spec.rb | spec/sidekiq/create_us_state_monthly_sales_reports_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CreateUsStateMonthlySalesReportsJob do
let (:subdivision_code) { "WA" }
let(:month) { 8 }
let (:year) { 2022 }
it "raises an argument error if the year is out of bounds" do
expect { described_class.new.perform(subdivision_code, month, 2013) }.to raise_error(ArgumentError)
end
it "raises an argument error if the month is out of bounds" do
expect { described_class.new.perform(subdivision_code, 13, year) }.to raise_error(ArgumentError)
end
it "raises an argument error if the subdivision code is not valid" do
expect { described_class.new.perform("subdivision", month, year) }.to raise_error(ArgumentError)
end
describe "happy case", :vcr do
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/washington-reporting-spec-#{SecureRandom.hex(18)}.zip")
end
before do
travel_to(Time.find_zone("UTC").local(2022, 8, 10)) do
product = create(:product, price_cents: 100_00, native_type: "digital")
@purchase1 = create(:purchase_in_progress, link: product, was_product_recommended: true, country: "United States", zip_code: "98121") # King County, Washington
@purchase2 = create(:purchase_in_progress, link: product, was_product_recommended: true, country: "United States", zip_code: "94016") # San Francisco, California
@purchase3 = create(:purchase_in_progress, link: product, country: "United States", zip_code: "98184") # Seattle, Washington (TaxJar returns King County, instead of Seattle though)
@purchase4 = create(:purchase_in_progress, link: product, country: "United States", zip_code: "98612", gumroad_tax_cents: 760) # Wahkiakum County, Washington
@purchase5 = create(:purchase_in_progress, link: product, country: "United States", zip_code: "19464", gumroad_tax_cents: 760, ip_address: "67.183.58.7") # Montgomery County, Pennsylvania with IP address in Washington
@purchase6 = create(:purchase_in_progress, link: product, was_product_recommended: true, country: "United States", zip_code: "98121", quantity: 3) # King County, Washington
@purchase_to_refund = create(:purchase_in_progress, link: product, country: "United States", zip_code: "98604", gumroad_tax_cents: 780) # Hockinson County, Washington
refund_flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(Currency::USD, 30_00)
@purchase_to_refund.refund_purchase!(refund_flow_of_funds, nil)
@purchase_without_taxjar_info = create(:purchase, link: product, country: "United States", zip_code: "98612", gumroad_tax_cents: 650) # Wahkiakum County, Washington
Purchase.in_progress.find_each do |purchase|
purchase.chargeable = create(:chargeable)
purchase.process!
purchase.update_balance_and_mark_successful!
end
end
end
it "creates CSV files for sales into the state of Washington" do
expect(s3_bucket_double).to receive(:object).ordered.and_return(@s3_object)
expect_any_instance_of(TaxjarApi).to receive(:create_order_transaction).exactly(6).times.and_call_original
described_class.new.perform(subdivision_code, month, year)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "US Sales Tax 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.length).to eq(7)
expect(actual_payload[0]).to eq([
"Purchase External ID",
"Purchase Date",
"Member State of Consumption",
"Total Transaction",
"Price",
"Tax Collected by Gumroad",
"Combined Tax Rate",
"Calculated Tax Amount",
"Jurisdiction State",
"Jurisdiction County",
"Jurisdiction City",
"State Tax Rate",
"County Tax Rate",
"City Tax Rate",
"Amount not collected by Gumroad",
"Gumroad Product Type",
"TaxJar Product Tax Code",
])
expect(@purchase1.purchase_taxjar_info).to be_present
expect(actual_payload[1]).to eq([
@purchase1.external_id,
"08/10/2022",
"Washington",
"110.35",
"100.00",
"10.35",
"0.1035",
"10.35",
"WA",
"KING",
"SEATTLE",
"0.065",
"0.004",
"0.0115",
"0.00",
"digital",
"31000"
])
expect(actual_payload[2]).to eq([
@purchase3.external_id,
"08/10/2022",
"Washington",
"110.20",
"100.00",
"10.20",
"0.102",
"10.20",
"WA",
"KING",
nil,
"0.065",
"0.004",
"0.01",
"0.00",
"digital",
"31000"
])
expect(actual_payload[3]).to eq([
@purchase4.external_id,
"08/10/2022",
"Washington",
"107.80",
"100.00",
"7.80",
"0.078",
"7.80",
"WA",
"WAHKIAKUM",
nil,
"0.065",
"0.003",
"0.01",
"0.00",
"digital",
"31000"
])
expect(actual_payload[4]).to eq([
@purchase6.external_id,
"08/10/2022",
"Washington",
"331.05",
"300.00",
"31.05",
"0.1035",
"31.05",
"WA",
"KING",
"SEATTLE",
"0.065",
"0.004",
"0.0115",
"0.00",
"digital",
"31000"
])
expect(actual_payload[5]).to eq([
@purchase_to_refund.external_id,
"08/10/2022",
"Washington",
"77.80",
"72.17",
"5.63",
"0.078",
"5.63",
"WA",
"CLARK",
nil,
"0.065",
"0.003",
"0.01",
"0.00",
"digital",
"31000"
])
# When TaxJar info is not stored for a purchase, it fetches the latest
# info from TaxJar API to calculate the tax amount
expect(@purchase_without_taxjar_info.purchase_taxjar_info).to be_nil
expect(actual_payload[6]).to eq([
@purchase_without_taxjar_info.external_id,
"08/10/2022",
"Washington",
"106.50",
"100.00",
"6.50",
"0.078",
"7.80",
"WA",
"WAHKIAKUM",
nil,
"0.065",
"0.003",
"0.01",
"1.30",
"digital",
"31000"
])
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_canada_monthly_sales_report_job_spec.rb | spec/sidekiq/create_canada_monthly_sales_report_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CreateCanadaMonthlySalesReportJob do
let(:month) { 1 }
let(:year) { 2015 }
it "raises an argument error if the year is out of bounds" do
expect { described_class.new.perform(month, 2013) }.to raise_error(ArgumentError)
end
it "raises an agrument error if the month is out of bounds" do
expect { described_class.new.perform(13, year) }.to raise_error(ArgumentError)
end
describe "happy case", :vcr do
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/international-sales-reporting-spec-#{SecureRandom.hex(18)}.zip")
end
before do
allow_any_instance_of(Link).to receive(:recommendable?).and_return(true)
subscription_product = nil
subscription = nil
travel_to(Time.zone.local(2014, 12, 1)) do
subscription_product = create(:subscription_product, price_cents: 100_00)
subscription = create(:subscription, link_id: subscription_product.id)
create(:purchase, link: subscription_product, is_original_subscription_purchase: true, subscription:, was_product_recommended: true, country: "Canada", state: nil)
end
travel_to(Time.zone.local(2015, 1, 1)) do
product = create(:product, price_cents: 100_00, native_type: "digital")
@purchase1 = create(:purchase_in_progress, link: product, was_product_recommended: true, country: "Canada", state: "ON", ip_country: "Canada")
@purchase2 = create(:purchase_in_progress, link: product, was_product_recommended: true, country: "Canada", state: "QC", ip_country: "Canada")
@purchase3 = create(:purchase_in_progress, link: product, country: "Canada", state: "AB", ip_country: "Canada")
create(:purchase_in_progress, link: product, country: "Singapore")
create(:purchase_in_progress, link: product, country: "Canada", state: "saskatoon")
create(:purchase_in_progress, link: product, country: "Canada", state: "ON", card_country: "US", ip_country: "United States")
create(:purchase_in_progress, link: subscription_product, subscription:, country: "Canada", state: nil)
Purchase.in_progress.find_each do |purchase|
purchase.chargeable = create(:chargeable)
purchase.process!
purchase.update_balance_and_mark_successful!
end
end
end
it "creates a CSV file for all sales into Canada" do
expect(s3_bucket_double).to receive(:object).ordered.and_return(@s3_object)
described_class.new.perform(month, year)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "Canada 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.length).to eq(4)
expect(actual_payload[0]).to eq([
"Purchase External ID",
"Purchase Date",
"Member State of Consumption",
"Gumroad Product Type",
"TaxJar Product Tax Code",
"GST Tax Rate",
"PST Tax Rate",
"QST Tax Rate",
"Combined Tax Rate",
"Calculated Tax Amount",
"Tax Collected by Gumroad",
"Price",
"Gumroad Fee",
"Shipping",
"Total",
"Receipt URL",
])
expect(@purchase1.purchase_taxjar_info).to be_present
expect(actual_payload[1]).to eq([
@purchase1.external_id,
"01/01/2015",
"Ontario",
"digital",
"31000",
"0.05",
"0.08",
"0.0",
"0.13",
"13.00",
"13.00",
"100.00",
"30.00",
"0.00",
"113.00",
@purchase1.receipt_url,
])
expect(@purchase2.purchase_taxjar_info).to be_present
expect(actual_payload[2]).to eq([
@purchase2.external_id,
"01/01/2015",
"Quebec",
"digital",
"31000",
"0.05",
"0.0",
"0.09975",
"0.14975",
"14.98",
"14.98",
"100.00",
"30.00",
"0.00",
"114.98",
@purchase2.receipt_url,
])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/exports/audience_export_worker_spec.rb | spec/sidekiq/exports/audience_export_worker_spec.rb | # frozen_string_literal: true
describe Exports::AudienceExportWorker do
describe "#perform" do
let(:seller) { create(:user) }
let(:audience_options) { { followers: true } }
let(:recipient) { create(:user) }
before do
ActionMailer::Base.deliveries.clear
end
it "sends email to seller when it is also the recipient" do
expect(ContactingCreatorMailer).to receive(:subscribers_data).and_call_original
described_class.new.perform(seller.id, seller.id, audience_options)
mail = ActionMailer::Base.deliveries.last
expect(mail.to).to eq([seller.email])
end
it "sends email to recipient" do
expect(ContactingCreatorMailer).to receive(:subscribers_data).and_call_original
described_class.new.perform(seller.id, recipient.id, audience_options)
mail = ActionMailer::Base.deliveries.last
expect(mail.to).to eq([recipient.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/exports/affiliate_export_worker_spec.rb | spec/sidekiq/exports/affiliate_export_worker_spec.rb | # frozen_string_literal: true
describe Exports::AffiliateExportWorker do
describe "#perform" do
before do
@seller = create(:user)
ActionMailer::Base.deliveries.clear
end
it "sends email to seller when it is also the recipient" do
expect(ContactingCreatorMailer).to receive(:affiliates_data).and_call_original
described_class.new.perform(@seller.id, @seller.id)
mail = ActionMailer::Base.deliveries.last
expect(mail.to).to eq([@seller.email])
end
it "sends email to recipient" do
expect(ContactingCreatorMailer).to receive(:affiliates_data).and_call_original
recipient = create(:user)
described_class.new.perform(@seller.id, recipient.id)
mail = ActionMailer::Base.deliveries.last
expect(mail.to).to eq([recipient.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/exports/sales/compile_chunks_worker_spec.rb | spec/sidekiq/exports/sales/compile_chunks_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Exports::Sales::CompileChunksWorker do
before do
@worker = described_class.new
# Check the tests of UsersController#export_sales for the complete overall behavior,
# what the email sent contains, with which custom fields, etc.
@csv_tempfile = Tempfile.new
allow(@worker).to receive(:generate_compiled_tempfile).and_return(@csv_tempfile)
@export = create(:sales_export)
create(:sales_export_chunk, export: @export)
end
it "sends email" do
expect(ContactingCreatorMailer).to receive(:user_sales_data).with(@export.recipient_id, @csv_tempfile).and_call_original
@worker.perform(@export.id)
end
it "destroys export and chunks" do
@worker.perform(@export.id)
expect(SalesExport.count).to eq(0)
expect(SalesExportChunk.count).to eq(0)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/exports/sales/create_and_enqueue_chunks_worker_spec.rb | spec/sidekiq/exports/sales/create_and_enqueue_chunks_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Exports::Sales::CreateAndEnqueueChunksWorker do
before do
seller = create(:user)
product = create(:product, user: seller)
@purchases = create_list(:purchase, 3, link: product)
@export = create(:sales_export, query: PurchaseSearchService.new(seller:).query.deep_stringify_keys)
index_model_records(Purchase)
stub_const("#{described_class}::MAX_PURCHASES_PER_CHUNK", 2)
end
it "creates and enqueues a job for each generated chunk" do
described_class.new.perform(@export.id)
@export.reload
expect(@export.chunks.count).to eq(2)
expect(@export.chunks.first.purchase_ids).to eq([@purchases[0].id, @purchases[1].id])
expect(@export.chunks.second.purchase_ids).to eq([@purchases[2].id])
expect(Exports::Sales::ProcessChunkWorker).to have_enqueued_sidekiq_job(@export.chunks.first.id)
expect(Exports::Sales::ProcessChunkWorker).to have_enqueued_sidekiq_job(@export.chunks.second.id)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/exports/sales/process_chunk_worker_spec.rb | spec/sidekiq/exports/sales/process_chunk_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Exports::Sales::ProcessChunkWorker do
before do
@worker = described_class.new
# Check the tests of UsersController#export_sales for the complete overall behavior,
# what the email sent contains, with which custom fields, etc.
@csv_tempfile = Tempfile.new
allow(@worker).to receive(:compile_chunks).and_return(@csv_tempfile)
@export = create(:sales_export)
end
context "when there are still chunks to process" do
before do
create(:sales_export_chunk, export: @export)
@chunk_2 = create(:sales_export_chunk, export: @export)
end
it "does not send email" do
expect(ContactingCreatorMailer).not_to receive(:sales_data)
@worker.perform(@chunk_2.id)
end
it "updates chunk" do
@worker.perform(@chunk_2.id)
@chunk_2.reload
expect(@chunk_2.processed).to eq(true)
expect(@chunk_2.revision).to eq(REVISION)
end
end
context "when chunks were processed with another revision" do
before do
@chunk_1 = create(:sales_export_chunk, export: @export, processed: true, revision: "old-revision")
@chunk_2 = create(:sales_export_chunk, export: @export)
end
it "does not send email" do
expect(ContactingCreatorMailer).not_to receive(:sales_data)
@worker.perform(@chunk_2.id)
end
it "updates chunk" do
@worker.perform(@chunk_2.id)
@chunk_2.reload
expect(@chunk_2.processed).to eq(true)
expect(@chunk_2.revision).to eq(REVISION)
end
it "requeues chunks that were processed with another revision" do
@worker.perform(@chunk_2.id)
expect(described_class).to have_enqueued_sidekiq_job(@chunk_1.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/reports/generate_ytd_sales_report_job_spec.rb | spec/sidekiq/reports/generate_ytd_sales_report_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Reports::GenerateYtdSalesReportJob do
let(:job) { described_class.new }
let(:es_results_double) { double("Elasticsearch::Persistence::Repository::Response::Results") }
let(:mailer_double) { double("ActionMailer::MessageDelivery", deliver_now: true) }
let(:recipient_emails) { ["test1@example.com", "test2@example.com"] }
let(:redis_key) { RedisKey.ytd_sales_report_emails }
before do
allow(Purchase).to receive(:search).and_return(es_results_double)
allow($redis).to receive(:lrange).with(redis_key, 0, -1).and_return(recipient_emails)
allow(AccountingMailer).to receive(:ytd_sales_report).and_return(mailer_double)
end
describe "#perform" do
context "when processing actual purchase records", :sidekiq_inline, :elasticsearch_wait_for_refresh do
let(:csv_report_emails) { ["report_user1@example.com", "report_user2@example.com"] }
before do
recreate_model_index(Purchase)
allow(Purchase).to receive(:search).and_call_original
allow($redis).to receive(:lrange).with(redis_key, 0, -1).and_return(csv_report_emails)
allow(AccountingMailer).to receive(:ytd_sales_report).and_return(mailer_double)
travel_to Time.zone.local(2023, 8, 15) do
create(:purchase, ip_country: "US", ip_state: "CA", price_cents: 10000, purchase_state: "successful", chargeback_date: nil, created_at: Time.zone.local(2023, 1, 15))
create(:purchase, ip_country: "US", ip_state: "NY", price_cents: 5000, purchase_state: "successful", chargeback_date: nil, created_at: Time.zone.local(2023, 2, 10))
create(:purchase, ip_country: "GB", ip_state: "London", price_cents: 7500, purchase_state: "preorder_concluded_successfully", chargeback_date: nil, created_at: Time.zone.local(2023, 3, 5))
refunded_purchase_us_ca = create(:purchase, ip_country: "US", ip_state: "CA", price_cents: 2000, purchase_state: "successful", chargeback_date: nil, created_at: Time.zone.local(2023, 5, 1))
create(:refund, purchase: refunded_purchase_us_ca, amount_cents: 1000)
# Reindex the purchase to update the amount_refunded_cents field
options = { "record_id" => refunded_purchase_us_ca.id, "class_name" => "Purchase" }
ElasticsearchIndexerWorker.perform_async("index", options)
create(:purchase, ip_country: "FR", ip_state: "Paris", price_cents: 2000, purchase_state: "successful", created_at: Time.zone.local(2022, 12, 20))
create(:purchase, ip_country: "DE", ip_state: "Berlin", price_cents: 3000, purchase_state: "successful", chargeback_date: Time.zone.local(2023, 1, 20), chargeback_reversed: false, created_at: Time.zone.local(2023, 1, 18))
create(:purchase, ip_country: "ES", ip_state: "Madrid", price_cents: 4000, purchase_state: "failed", created_at: Time.zone.local(2023, 4, 1))
end
end
it "generates correct CSV data including refunds" do
captured_csv_string = nil
allow(AccountingMailer).to receive(:ytd_sales_report) do |csv_string, email|
captured_csv_string = csv_string if email == csv_report_emails.first
mailer_double
end.and_return(mailer_double)
travel_to Time.zone.local(2023, 8, 15) do
job.perform
end
expect(captured_csv_string).not_to be_nil
csv_data = CSV.parse(captured_csv_string, headers: true)
parsed_rows = csv_data.map(&:to_h)
expected_rows = [
{ "Country" => "US", "State" => "CA", "Net Sales (USD)" => "110.0" },
{ "Country" => "US", "State" => "NY", "Net Sales (USD)" => "50.0" },
{ "Country" => "GB", "State" => "London", "Net Sales (USD)" => "75.0" }
]
expect(parsed_rows).to match_array(expected_rows)
end
it "enqueues emails to recipients" do
travel_to Time.zone.local(2023, 8, 15) do
job.perform
end
expect(AccountingMailer).to have_received(:ytd_sales_report).with(any_args, csv_report_emails[0]).once
expect(AccountingMailer).to have_received(:ytd_sales_report).with(any_args, csv_report_emails[1]).once
expect(mailer_double).to have_received(:deliver_now).twice
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/onetime/generate_subscribe_previews_spec.rb | spec/sidekiq/onetime/generate_subscribe_previews_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Onetime::GenerateSubscribePreviews do
let(:users) { create_list(:user, 2) }
let(:user_ids) { users.map(&:id) }
describe "#perform" do
context "when subscribe preview generation succeeds" do
it "attaches the generated image to the user and enables the rollout flag for the user" do
subscribe_preview = File.binread("#{Rails.root}/spec/support/fixtures/subscribe_preview.png")
allow(SubscribePreviewGeneratorService).to receive(:generate_pngs).and_return([subscribe_preview, subscribe_preview])
expect(users.first.subscribe_preview).not_to be_attached
expect(users.second.subscribe_preview).not_to be_attached
described_class.new.perform(user_ids)
expect(users.first.reload.subscribe_preview).to be_attached
expect(users.second.reload.subscribe_preview).to be_attached
end
end
context "image generation does not work" do
it "raises an error" do
allow(SubscribePreviewGeneratorService).to receive(:generate_pngs).and_return([nil])
expect { described_class.new.perform(user_ids) }.to raise_error("Failed to generate all subscribe previews for top sellers")
end
end
context "error occurred" do
it "propagates the error to Sidekiq" do
allow(SubscribePreviewGeneratorService).to receive(:generate_pngs).and_raise("WHOOPS")
expect { described_class.new.perform(user_ids) }.to raise_error("WHOOPS")
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/iffy/event_job_spec.rb | spec/sidekiq/iffy/event_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Iffy::EventJob do
describe "#perform" do
let(:id) { 1 }
let(:entity) { "Product" }
context "when event is valid" do
Iffy::EventJob::EVENTS.each do |event|
it "calls the appropriate service for #{event}" do
service_class = (
case event
when "user.banned"
Iffy::User::BanService
when "user.suspended"
Iffy::User::SuspendService
when "user.compliant"
Iffy::User::MarkCompliantService
when "record.flagged"
entity == "Product" ? Iffy::Product::FlagService : Iffy::Post::FlagService
when "record.compliant"
entity == "Product" ? Iffy::Product::MarkCompliantService : Iffy::Post::MarkCompliantService
end
)
service = double(perform: true)
expect(service_class).to receive(:new).with(id).and_return(service)
expect(service).to receive(:perform)
described_class.new.perform(event, id, entity)
end
end
end
context "when event is invalid" do
it "does not call any service" do
expect(Iffy::User::BanService).not_to receive(:new)
expect(Iffy::User::SuspendService).not_to receive(:new)
expect(Iffy::User::MarkCompliantService).not_to receive(:new)
expect(Iffy::Product::FlagService).not_to receive(:new)
expect(Iffy::Product::MarkCompliantService).not_to receive(:new)
expect(Iffy::Post::FlagService).not_to receive(:new)
expect(Iffy::Post::MarkCompliantService).not_to receive(:new)
described_class.new.perform("invalid.event", id, entity)
end
end
context "when user is protected" do
let(:event) { "record.flagged" }
let(:protected_user) { { "protected" => true } }
it "does not call FlagService for protected users" do
expect(Iffy::Product::FlagService).not_to receive(:new)
expect(Iffy::Post::FlagService).not_to receive(:new)
described_class.new.perform(event, id, entity, protected_user)
end
it "calls FlagService for non-protected users" do
non_protected_user = { "protected" => false }
service = double(perform: true)
expect(Iffy::Product::FlagService).to receive(:new).with(id).and_return(service)
expect(service).to receive(:perform)
described_class.new.perform(event, id, entity, non_protected_user)
end
end
context "when user was suspended by an admin" do
let(:admin_user) { create(:admin_user) }
let(:user) { create(:user) }
before do
user.flag_for_tos_violation!(author_id: admin_user.id, bulk: true)
user.suspend_for_tos_violation!(author_id: admin_user.id, bulk: true)
end
it "does not call MarkCompliantService for admin-suspended users" do
expect(Iffy::User::MarkCompliantService).not_to receive(:new)
described_class.new.perform("user.compliant", user.external_id, entity)
end
end
context "when user was suspended by Iffy" do
let(:user) { create(:user) }
before do
user.flag_for_tos_violation!(author_name: "Iffy", bulk: true)
user.suspend_for_tos_violation!(author_name: "Iffy", bulk: true)
end
it "call MarkCompliantService for Iffy-suspended users" do
service = double(perform: true)
expect(Iffy::User::MarkCompliantService).to receive(:new).with(user.external_id).and_return(service)
expect(service).to receive(:perform)
described_class.new.perform("user.compliant", user.external_id, entity)
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/iffy/product/ingest_job_spec.rb | spec/sidekiq/iffy/product/ingest_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Iffy::Product::IngestJob do
describe "#perform" do
let(:product) { create(:product) }
it "invokes the ingest service with the correct product" do
expect(Iffy::Product::IngestService).to receive(:new).with(product).and_call_original
expect_any_instance_of(Iffy::Product::IngestService).to receive(:perform)
Iffy::Product::IngestJob.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/iffy/profile/ingest_job_spec.rb | spec/sidekiq/iffy/profile/ingest_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Iffy::Profile::IngestJob do
describe "#perform" do
let(:user) { create(:user) }
it "invokes the ingest service with the correct user" do
expect(Iffy::Profile::IngestService).to receive(:new).with(user).and_call_original
expect_any_instance_of(Iffy::Profile::IngestService).to receive(:perform)
Iffy::Profile::IngestJob.new.perform(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/iffy/post/ingest_job_spec.rb | spec/sidekiq/iffy/post/ingest_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Iffy::Post::IngestJob do
describe "#perform" do
let(:installment) { create(:installment) }
it "invokes the ingest service with the correct installment" do
expect(Iffy::Post::IngestService).to receive(:new).with(installment).and_call_original
expect_any_instance_of(Iffy::Post::IngestService).to receive(:perform)
Iffy::Post::IngestJob.new.perform(installment.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/affiliate_mailer_spec.rb | spec/mailers/affiliate_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe AffiliateMailer do
describe "#notify_affiliate_of_sale" do
let(:seller) { create(:named_user) }
let(:product_name) { "Affiliated Product" }
let(:purchaser_email) { generate(:email) }
shared_examples "notifies affiliate of a sale" do
it "sends email to affiliate" do
product = create(:product, user: seller, name: product_name)
purchase = create(:purchase, affiliate:, link: product, seller:, email: purchaser_email)
mail = AffiliateMailer.notify_affiliate_of_sale(purchase.id)
expect(mail.to).to eq([affiliate.affiliate_user.form_email])
expect(mail.subject).to include(email_subject)
expect(mail.body.encoded).to include(email_body)
expect(mail.body.encoded).to include("Thanks for being part of the team and helping make another sale happen!")
end
context "for a subscription purchase" do
it "tells them they will receive a commission for recurring charges" do
product = create(:membership_product, user: seller)
purchase = create(:membership_purchase, affiliate:, link: product, seller:)
mail = AffiliateMailer.notify_affiliate_of_sale(purchase.id)
expect(mail.body.encoded).to include "You'll continue to receive a commission once a month as long as the subscription is active."
end
end
context "for a free trial purchase" do
it "clarifies when they will receive their affiliate credits" do
product = create(:membership_product, :with_free_trial_enabled, user: seller)
purchase = create(:free_trial_membership_purchase, affiliate:, link: product, seller:)
formatted_amount = MoneyFormatter.format(purchase.affiliate_credit_cents, :usd, no_cents_if_whole: true, symbol: true)
mail = AffiliateMailer.notify_affiliate_of_sale(purchase.id)
expect(mail.body.encoded).to include "Your commission rate: #{affiliate.affiliate_percentage}%"
expect(mail.body.encoded).to include "Your earnings (after fees): #{formatted_amount}"
expect(mail.body.encoded).to include "If the subscriber continues with their subscription after their free trial has expired on #{purchase.subscription.free_trial_end_date_formatted}, we'll add your commission to your balance"
end
end
end
context "for a direct affiliate" do
let(:affiliate) { create(:direct_affiliate, seller:) }
let(:email_subject) { "You helped #{seller.name_or_username} make a sale" }
let(:email_body) { "Great news - #{seller.name_or_username} just sold a copy of #{product_name} to #{purchaser_email} thanks to your referral." }
it_behaves_like "notifies affiliate of a sale"
it "shows the correct affiliate commission for the purchased product" do
product = create(:product, user: seller, name: product_name, price_cents: 10_00)
create(:product_affiliate, product:, affiliate:, affiliate_basis_points: 25_00)
purchase = create(:purchase, affiliate:, link: product, seller:, email: purchaser_email, affiliate_credit_cents: 2_50)
mail = AffiliateMailer.notify_affiliate_of_sale(purchase.id)
expect(mail.to).to eq([affiliate.affiliate_user.form_email])
expect(mail.subject).to include(email_subject)
expect(mail.body.encoded).to include(email_body)
expect(mail.body.encoded).to include("We've added your commission to your balance.")
expect(mail.body.encoded).to include "Purchase amount: $10"
expect(mail.body.encoded).to include "Your commission rate: 25%"
expect(mail.body.encoded).to include "Your earnings (after fees): $1.97"
end
end
context "for a global affiliate" do
let(:affiliate) { create(:user).global_affiliate }
let(:email_subject) { "🎉 You earned a commission!" }
let(:email_body) { "Great news - #{seller.name_or_username} just sold a copy of #{product_name} thanks to your referral." }
it_behaves_like "notifies affiliate of a sale"
end
context "for a collaborator" do
let(:product) { create(:product, user: seller, name: product_name, price_cents: 20_00) }
let(:collaborator) { create(:collaborator, seller:, affiliate_basis_points: 40_00, products: [product]) }
let(:purchase) { create(:purchase_in_progress, affiliate: collaborator, link: product, seller:) }
before do
purchase.process!
purchase.update_balance_and_mark_successful!
end
it "notifies collaborator of a sale" do
mail = AffiliateMailer.notify_affiliate_of_sale(purchase.id)
expect(mail.to).to eq([collaborator.affiliate_user.form_email])
expect(mail.subject).to include("New sale of #{product_name} for $20")
expect(mail.body.encoded).to include("You made a sale!")
expect(mail.body.encoded).to include "Product price"
expect(mail.body.encoded).to include "$20"
expect(mail.body.encoded).to include "Your cut"
expect(mail.body.encoded).to include "$8"
expect(mail.body.encoded).to include "Quantity"
expect(mail.body.encoded).to include "1"
end
it "includes variant information if the purchase is for a variant" do
purchase.variant_attributes = [
create(:variant, variant_category: create(:variant_category, link: product), name: "Blue"),
create(:variant, variant_category: create(:variant_category, link: product), name: "Small"),
]
mail = AffiliateMailer.notify_affiliate_of_sale(purchase.id)
expect(mail.body.encoded).to include "Variants"
expect(mail.body.encoded).to include "(Blue, Small)"
end
end
end
describe "#notify_direct_affiliate_of_updated_products" do
it "sends email to affiliate" do
seller = create(:named_user)
product = create(:product, name: "Gumbot bits", user: seller)
product_2 = create(:product, name: "The Gumroad Handbook", user: seller)
create(:product, name: "Unaffiliated product that we ignore", user: seller)
affiliate = create(:direct_affiliate, seller:)
create(:product_affiliate, product:, affiliate:)
create(:product_affiliate, product: product_2, affiliate:, affiliate_basis_points: 30_00)
create(:product, name: "The Road of Gum", user: seller)
mail = AffiliateMailer.notify_direct_affiliate_of_updated_products(affiliate.id)
expect(mail.to).to eq([affiliate.affiliate_user.form_email])
expect(mail.subject).to include("#{seller.name} just updated your affiliated products")
body = mail.body.encoded.split("<body>").pop
mail_plaintext = ActionView::Base.full_sanitizer.sanitize(body).gsub("\r\n", " ").gsub(/\s{2,}/, " ").strip
expect(mail_plaintext).to_not include("The Road of Gum")
expect(mail_plaintext).to include("Gumbot bits - Your commission: 10%")
expect(mail_plaintext).to include("The Gumroad Handbook - Your commission: 30%")
expect(mail_plaintext).to include("You can now share the products linked below with your audience. For every sale you make, you will get a percentage of the total sale as your commission.")
expect(mail_plaintext).to include("You can direct them to this link: #{affiliate.referral_url}, or share the individual links listed above.")
end
end
describe "#direct_affiliate_removal" do
it "sends email to affiliate" do
seller = create(:named_user)
direct_affiliate = create(:direct_affiliate, seller:)
mail = AffiliateMailer.direct_affiliate_removal(direct_affiliate.id)
expect(mail.to).to eq([direct_affiliate.affiliate_user.form_email])
expect(mail.subject).to include("#{seller.name} just updated your affiliate status")
expect(mail.body.encoded).to include("#{seller.name} has removed you from their affiliate program. If you feel this was done accidentally, please reach out to #{seller.name} directly.")
expect(mail.body.encoded).to include("Thanks for being a part of the team.")
end
end
describe "#collaboration_ended_by_affiliate_user" do
it "sends email to seller" do
seller = create(:user, name: "Seller")
affiliate_user = create(:user, name: "Affiliate User")
collaborator = create(:collaborator, seller:, affiliate_user:)
mail = AffiliateMailer.collaboration_ended_by_affiliate_user(collaborator.id)
expect(mail.to).to eq([seller.form_email])
expect(mail.cc).to eq([affiliate_user.form_email])
expect(mail.subject).to include("Affiliate User has ended your collaboration")
expect(mail.body.encoded).to include("Affiliate User has ended your collaboration. They no longer have access to your product(s), or future earnings.")
end
end
describe "#direct_affiliate_invitation" do
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
before { create(:product, name: "Unaffiliated product that we ignore", user: seller) }
context "when affiliate has just a single product" do
context "when affiliate destination URL is set" do
it "sends email to affiliate with the affiliated product's URL and destination URL" do
direct_affiliate = create(:direct_affiliate, seller:, destination_url: "https://example.com")
create(:product_affiliate, product:, affiliate: direct_affiliate, destination_url: "https://example2.com")
mail = AffiliateMailer.direct_affiliate_invitation(direct_affiliate.id)
expect(mail.to).to eq([direct_affiliate.affiliate_user.form_email])
expect(mail.cc).to eq([direct_affiliate.seller.form_email])
expect(mail.subject).to include("#{seller.name} has added you as an affiliate.")
expect(mail.body.encoded).to include("For every sale you make, you will get 10% of the total sale as your commission.")
expect(mail.body.encoded.squish).to include(%(You can direct them to this link: <a clicktracking="off" href="#{direct_affiliate.referral_url}">#{direct_affiliate.referral_url}</a> — after they click, we'll redirect them to <a clicktracking="off" href="#{direct_affiliate.final_destination_url(product:)}">#{direct_affiliate.final_destination_url(product:)}</a>.))
expect(mail.body.encoded).to include("Or, if you'd like to share the product, you can use this link:")
end
end
context "when affiliate destination URL is not set" do
it "sends email to affiliate with the affiliated product's URL" do
direct_affiliate = create(:direct_affiliate, seller:)
create(:product_affiliate, product:, affiliate: direct_affiliate, destination_url: "https://example2.com")
mail = AffiliateMailer.direct_affiliate_invitation(direct_affiliate.id)
expect(mail.to).to eq([direct_affiliate.affiliate_user.form_email])
expect(mail.cc).to eq([direct_affiliate.seller.form_email])
expect(mail.subject).to include("#{seller.name} has added you as an affiliate.")
expect(mail.body.encoded).to include("For every sale you make, you will get 10% of the total sale as your commission.")
expect(mail.body.encoded.squish).to include(%(You can direct them to this link: <a clicktracking="off" href="#{direct_affiliate.referral_url_for_product(product)}">#{direct_affiliate.referral_url_for_product(product)}</a>))
expect(mail.body.encoded).to_not include("— after they click, we'll redirect them to")
end
end
end
context "when affiliate has multiple products" do
it "sends email to affiliate with the affiliated products' URLs" do
product_two = create(:product, name: "Gumbot bits", user: seller)
direct_affiliate = create(:direct_affiliate, seller:)
create(:product_affiliate, product:, affiliate: direct_affiliate, destination_url: "https://example.com")
create(:product_affiliate, product: product_two, affiliate_basis_points: 5_00, affiliate: direct_affiliate, destination_url: "https://example2.com")
mail = AffiliateMailer.direct_affiliate_invitation(direct_affiliate.id)
expect(mail.to).to eq([direct_affiliate.affiliate_user.form_email])
expect(mail.cc).to eq([direct_affiliate.seller.form_email])
expect(mail.subject).to include("#{seller.name} has added you as an affiliate.")
expect(mail.body.encoded.squish).to include(%(You can direct them to this link: <a clicktracking="off" href="#{direct_affiliate.referral_url}">#{direct_affiliate.referral_url}</a> — after they click, we'll redirect them to <a clicktracking="off" href="#{seller.subdomain_with_protocol}">#{seller.subdomain_with_protocol}</a>))
body = mail.body.encoded.split("<body>").pop
mail_plaintext = ActionView::Base.full_sanitizer.sanitize(body).gsub("\r\n", " ").gsub(/\s{2,}/, " ").strip
expect(mail_plaintext).to include("For every sale you make, you will get 5 - 10% of the total sale as your commission.")
expect(mail_plaintext).to include("Or, if you'd like to share individual products, you can use these links:")
expect(mail_plaintext).to include("#{product.name} - Your commission: 10%")
expect(mail_plaintext).to include("Gumbot bits - Your commission: 5%")
end
end
context "when prevent_sending_invitation_email_to_seller param is true" do
it "doesn't send the email to seller" do
direct_affiliate = create(:direct_affiliate, seller:, products: [product])
mail = AffiliateMailer.direct_affiliate_invitation(direct_affiliate.id, true)
expect(mail.to).to eq([direct_affiliate.affiliate_user.form_email])
expect(mail.cc).to be_nil
end
end
end
describe "#notify_direct_affiliate_of_new_product" do
it "sends email to affiliate" do
seller = create(:named_user)
direct_affiliate = create(:direct_affiliate, seller:)
product = create(:product, user: seller)
create(:product_affiliate, product:, affiliate: direct_affiliate)
mail = AffiliateMailer.notify_direct_affiliate_of_new_product(direct_affiliate.id, product.id)
expect(mail.to).to eq([direct_affiliate.affiliate_user.form_email])
expect(mail.subject).to include("#{seller.name} has added you as an affiliate to #{product.name}")
expect(mail.body.encoded).to include("You are now able to share #{product.name} with your audience. For every sale you make, you will get 10% of the total sale as your commission.")
end
end
describe "#collaborator_creation" do
let(:seller) { create(:named_user) }
let(:collaborator) { create(:collaborator, seller:) }
it "sends email to collaborator" do
product_affiliate = create(:product_affiliate, affiliate: collaborator, product: create(:product, user: seller, name: "Product", price_cents: 500))
mail = AffiliateMailer.collaborator_creation(collaborator.id)
expect(mail.to).to eq([collaborator.affiliate_user.form_email])
subject = "#{seller.name} has added you as a collaborator on Gumroad"
expect(mail.subject).to eq(subject)
expect(mail.body.encoded).to have_text("Product")
expect(mail.body.encoded).to have_link(product_affiliate.product.long_url, href: product_affiliate.product.long_url)
expect(mail.body.encoded).to have_text("Price")
expect(mail.body.encoded).to have_text("$5")
expect(mail.body.encoded).to have_text("Your cut")
expect(mail.body.encoded).to have_text("10% ($0.50)")
expect(mail.body.encoded).to have_link("Log in to Gumroad")
end
context "when the collaborator has more than 5 products" do
let!(:product_affiliates) do
build_list(:product_affiliate, 6, affiliate: collaborator) do |product_affiliate, i|
product_affiliate.product = create(:product, user: seller, name: "Product #{i}")
product_affiliate.save!
end
end
it "sends email to collaborator and truncates the product list" do
mail = AffiliateMailer.collaborator_creation(collaborator.id)
expect(mail.to).to eq([collaborator.affiliate_user.form_email])
subject = "#{seller.name} has added you as a collaborator on Gumroad"
expect(mail.subject).to eq(subject)
expect(mail.body.encoded).to have_text(subject)
expect(mail.body.encoded).to have_text("What is a collaborator?")
expect(mail.body.encoded).to have_text("A collaborator is someone who has contributed to the creation of a product and therefore earns a percentage of its sales.")
expect(mail.body.encoded).to have_text("How much will I earn?")
product_affiliates.take(5).map(&:product).each_with_index do |product, i|
expect(mail.body.encoded).to have_text("Product #{i}")
expect(mail.body.encoded).to have_link(product.long_url, href: product.long_url)
expect(mail.body.encoded).to have_text("Price")
expect(mail.body.encoded).to have_text("$1")
expect(mail.body.encoded).to have_text("Your cut")
expect(mail.body.encoded).to have_text("10% ($0.10)")
end
expect(mail.body.encoded).to have_link("Log in to see 1 more", href: products_collabs_url)
end
end
end
describe "#collaborator_update" do
let(:seller) { create(:named_user) }
let(:collaborator) { create(:collaborator, seller:) }
it "sends email to collaborator" do
product_affiliate = create(:product_affiliate, affiliate: collaborator, product: create(:product, user: seller, name: "Product", price_cents: 500))
mail = AffiliateMailer.collaborator_update(collaborator.id)
expect(mail.to).to eq([collaborator.affiliate_user.form_email])
subject = "#{seller.name} has updated your collaborator status on Gumroad"
expect(mail.subject).to eq(subject)
expect(mail.body.encoded).to have_text("Product")
expect(mail.body.encoded).to have_link(product_affiliate.product.long_url, href: product_affiliate.product.long_url)
expect(mail.body.encoded).to have_text("Price")
expect(mail.body.encoded).to have_text("$5")
expect(mail.body.encoded).to have_text("Your cut")
expect(mail.body.encoded).to have_text("10% ($0.50)")
expect(mail.body.encoded).to have_link("Log in to Gumroad")
end
context "when the collaborator has more than 5 products" do
let!(:product_affiliates) do
build_list(:product_affiliate, 6, affiliate: collaborator) do |product_affiliate, i|
product_affiliate.product = create(:product, user: seller, name: "Product #{i}")
product_affiliate.save!
end
end
it "sends email to collaborator and truncates the product list" do
mail = AffiliateMailer.collaborator_update(collaborator.id)
expect(mail.to).to eq([collaborator.affiliate_user.form_email])
subject = "#{seller.name} has updated your collaborator status on Gumroad"
expect(mail.subject).to eq(subject)
expect(mail.body.encoded).to have_text(subject)
expect(mail.body.encoded).to_not have_text("What is a collaborator?")
expect(mail.body.encoded).to have_text("How much will I earn?")
product_affiliates.take(5).map(&:product).each_with_index do |product, i|
expect(mail.body.encoded).to have_text("Product #{i}")
expect(mail.body.encoded).to have_link(product.long_url, href: product.long_url)
expect(mail.body.encoded).to have_text("Price")
expect(mail.body.encoded).to have_text("$1")
expect(mail.body.encoded).to have_text("Your cut")
expect(mail.body.encoded).to have_text("10% ($0.10)")
end
expect(mail.body.encoded).to have_link("Log in to see 1 more", href: products_collabs_url)
end
end
end
describe "#collaboration_ended_by_seller" do
let(:seller) { create(:named_user) }
let(:collaborator) { create(:collaborator, seller:) }
it "sends email to collaborator" do
mail = AffiliateMailer.collaboration_ended_by_seller(collaborator.id)
expect(mail.to).to eq([collaborator.affiliate_user.form_email])
expect(mail.subject).to include("#{seller.name} just updated your collaborator status")
expect(mail.body.encoded).to include("#{seller.name} has removed you as a collaborator. If you feel this was done accidentally, please reach out to #{seller.name} directly.")
end
end
describe "#collaborator_invited" do
let(:seller) { create(:named_user) }
let(:collaborator) { create(:collaborator, seller:) }
it "sends email to collaborator" do
product_affiliate = create(:product_affiliate, affiliate: collaborator, product: create(:product, user: seller, name: "Product", price_cents: 500))
mail = AffiliateMailer.collaborator_invited(collaborator.id)
expect(mail.to).to eq([collaborator.affiliate_user.form_email])
expect(mail.subject).to eq("#{seller.name} has invited you to collaborate on Gumroad")
expect(mail.body.encoded).to have_text("Product")
expect(mail.body.encoded).to have_link(product_affiliate.product.long_url, href: product_affiliate.product.long_url)
expect(mail.body.encoded).to have_text("Price")
expect(mail.body.encoded).to have_text("$5")
expect(mail.body.encoded).to have_text("Your cut")
expect(mail.body.encoded).to have_text("10% ($0.50)")
expect(mail.body.encoded).to have_link("Respond to this invitation", href: collaborators_incomings_url)
end
context "when the collaborator has more than 5 products" do
let!(:product_affiliates) do
build_list(:product_affiliate, 6, affiliate: collaborator) do |product_affiliate, i|
product_affiliate.product = create(:product, user: seller, name: "Product #{i}")
product_affiliate.save!
end
end
it "sends email to collaborator and truncates the product list" do
mail = AffiliateMailer.collaborator_invited(collaborator.id)
expect(mail.to).to eq([collaborator.affiliate_user.form_email])
subject = "#{seller.name} has invited you to collaborate on Gumroad"
expect(mail.subject).to eq(subject)
expect(mail.body.encoded).to have_text(subject)
expect(mail.body.encoded).to have_text("What is a collaborator?")
expect(mail.body.encoded).to have_text("A collaborator is someone who has contributed to the creation of a product and therefore earns a percentage of its sales.")
expect(mail.body.encoded).to have_text("How much will I earn?")
product_affiliates.take(5).map(&:product).each_with_index do |product, i|
expect(mail.body.encoded).to have_text("Product #{i}")
expect(mail.body.encoded).to have_link(product.long_url, href: product.long_url)
expect(mail.body.encoded).to have_text("Price")
expect(mail.body.encoded).to have_text("$1")
expect(mail.body.encoded).to have_text("Your cut")
expect(mail.body.encoded).to have_text("10% ($0.10)")
end
expect(mail.body.encoded).to have_text("And 1 more product...")
expect(mail.body.encoded).to have_link("Respond to this invitation", href: collaborators_incomings_url)
end
end
end
describe "#collaborator_invitation_accepted" do
let(:collaborator) { create(:collaborator) }
it "sends email to the seller" do
mail = AffiliateMailer.collaborator_invitation_accepted(collaborator.id)
expect(mail.to).to eq([collaborator.seller.form_email])
expect(mail.subject).to include("#{collaborator.affiliate_user.name} accepted your invitation to collaborate on Gumroad")
end
end
describe "#collaborator_invitation_declined" do
let(:collaborator) { create(:collaborator) }
it "sends email to the seller" do
mail = AffiliateMailer.collaborator_invitation_declined(collaborator.id)
expect(mail.to).to eq([collaborator.seller.form_email])
expect(mail.subject).to include("#{collaborator.affiliate_user.name} declined your invitation to collaborate on Gumroad")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/team_mailer_spec.rb | spec/mailers/team_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe TeamMailer do
let(:seller) { create(:named_seller) }
describe "#invite" do
let(:email) { "member@example.com" }
let(:team_invitation) { create(:team_invitation, seller:, email:) }
subject(:mail) { described_class.invite(team_invitation) }
it "generates email" do
expect(mail.to).to eq [email]
expect(mail.subject).to eq("Seller has invited you to join seller")
expect(mail.from).to eq [ApplicationMailer::NOREPLY_EMAIL]
expect(mail.reply_to).to eq [seller.email]
expect(mail.body).to include "This invitation will expire in 7 days."
expect(mail.body).to include "Accept invitation"
expect(mail.body).to include accept_settings_team_invitation_url(team_invitation.external_id)
end
end
describe "#invitation_accepted" do
let(:user) { create(:user, :without_username) }
let(:team_membership) { create(:team_membership, seller:, user:) }
subject(:mail) { described_class.invitation_accepted(team_membership) }
it "generates email" do
expect(mail.to).to eq [seller.email]
expect(mail.subject).to eq("#{user.email} has accepted your invitation")
expect(mail.from).to eq [ApplicationMailer::NOREPLY_EMAIL]
expect(mail.reply_to).to eq [user.email]
expect(mail.body).to include "#{user.email} joined the team at seller as Admin"
expect(mail.body).to include "Manage your team settings"
expect(mail.body).to include settings_team_url
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/invite_mailer_spec.rb | spec/mailers/invite_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe InviteMailer do
describe "receiver_signed_up" do
before do
@user = create(:user)
@invite = create(:invite, sender_id: @user.id)
@invited_user = create(:user, email: @invite.receiver_email)
@invited_user.mark_as_invited(@user.external_id)
end
it "has the correct 'to' and 'from' values" do
mail = InviteMailer.receiver_signed_up(@invite.id)
expect(mail.to).to eq [@user.form_email]
expect(mail.from).to eq [ApplicationMailer::NOREPLY_EMAIL]
end
it "has the correct subject and title when the user has no name set" do
mail = InviteMailer.receiver_signed_up(@invite.id)
expect(mail.subject).to eq "A creator you invited has joined Gumroad."
expect(mail.body.encoded).to include("A creator you invited has joined Gumroad.")
end
it "has the correct subject and title when the user has a name set" do
@invited_user.name = "Sam Smith"
@invited_user.save!
mail = InviteMailer.receiver_signed_up(@invite.id)
expect(mail.subject).to eq "#{@invited_user.name} has joined Gumroad, thanks to you."
expect(mail.body.encoded).to include("#{@invited_user.name} has joined Gumroad, thanks to you.")
end
it "does not attempt to send an email if the 'to' email is empty" do
@user.update_column(:email, nil)
expect do
InviteMailer.receiver_signed_up(@invite.id).deliver_now
end.to_not change { ActionMailer::Base.deliveries.count }
end
it "has both username and email in body" do
@invited_user.name = "Sam Smith"
@invited_user.save!
mail = InviteMailer.receiver_signed_up(@invite.id)
expect(mail.body.encoded).to include("#{@invited_user.name} - #{@invited_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/mailers/two_factor_authentication_mailer_spec.rb | spec/mailers/two_factor_authentication_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe TwoFactorAuthenticationMailer do
let(:user) { create :user }
describe "#authentication_token" do
before do
@mail = TwoFactorAuthenticationMailer.authentication_token(user.id)
end
it "has has all required information" do
expect(@mail.to).to eq [user.email]
expect(@mail.subject).to include("Your authentication token is #{user.otp_code}")
expect(@mail.body).to include(user.otp_code)
expect(@mail.body).to have_link("Login", href: verify_two_factor_authentication_url(token: user.otp_code, user_id: user.encrypted_external_id, format: :html))
expect(@mail.body).to include("This authentication token and login link will expire in 10 minutes.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/comment_mailer_spec.rb | spec/mailers/comment_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CommentMailer do
describe "notify_seller_of_new_comment" do
let(:comment) { create(:comment, content: "Their -> they're") }
subject(:mail) { described_class.notify_seller_of_new_comment(comment.id) }
it "emails to seller" do
expect(mail.to).to eq([comment.commentable.seller.form_email])
expect(mail.subject).to eq("New comment on #{comment.commentable.name}")
expect(mail.body.encoded).to include("#{comment.author.display_name} commented on #{CGI.escape_html comment.commentable.name}")
expect(mail.body.encoded).to include("Their -> they're")
expect(mail.body.encoded).to include(%Q{<a class="button primary" target="_blank" href="#{custom_domain_view_post_url(slug: comment.commentable.slug, host: comment.commentable.seller.subdomain_with_protocol)}">View comment</a>})
expect(mail.body.encoded).to include(%Q{To stop receiving comment notifications, please <a target="_blank" href="#{settings_main_url(anchor: "notifications")}">change your notification settings</a>.})
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/application_mailer_spec.rb | spec/mailers/application_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ApplicationMailer do
it "includes RescueSmtpErrors" do
expect(described_class).to include(RescueSmtpErrors)
end
describe "delivery method" do
let(:mailer) { described_class.new }
before do
described_class.class_eval do
def test_email
mail(to: "test@example.com", subject: "Test") do |format|
format.text { render plain: "Test email content" }
end
end
end
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.deliveries.clear
end
describe "delivery_method_options" do
it "uses MailerInfo.random_delivery_method_options with gumroad domain" do
expect(MailerInfo).to receive(:random_delivery_method_options).with(domain: :gumroad).and_return({})
mailer.test_email
end
it "evaluates options lazily" do
options = { address: "smtp.sendgrid.net" }
allow(MailerInfo).to receive(:random_delivery_method_options).and_return(options)
mail = mailer.test_email
expect(mail.delivery_method.settings).to include(options)
end
it "sets delivery method options correctly" do
options = { address: "smtp.sendgrid.net", domain: "gumroad.com" }
allow(MailerInfo).to receive(:random_delivery_method_options).and_return(options)
mail = mailer.test_email
expect(mail.delivery_method.settings).to include(options)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/affiliate_request_mailer_spec.rb | spec/mailers/affiliate_request_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe AffiliateRequestMailer do
let(:requester_email) { "requester@example.com" }
let(:creator) { create(:named_user) }
let(:affiliate_request) { create(:affiliate_request, email: requester_email, seller: creator) }
describe "notify_requester_of_request_submission" do
subject(:mail) { described_class.notify_requester_of_request_submission(affiliate_request.id) }
it "sends email to requester" do
expect(mail.to).to eq([requester_email])
expect(mail.subject).to eq("Your application request to #{creator.display_name} was submitted!")
expect(mail.body.encoded).to include("#{creator.display_name} is now reviewing your application and once they approve you, you will receive a confirmation email, along with some helpful tips to get started as an affiliate.")
expect(mail.body.encoded).to include("<strong>Name:</strong> #{affiliate_request.name}")
expect(mail.body.encoded).to include("<strong>Email:</strong> #{requester_email}")
expect(mail.body.encoded).to include("In the meantime, <a href=\"#{signup_url(email: requester_email)}\">create your Gumroad account</a> using email #{requester_email} and confirm it. You'll receive your affiliate links once your Gumroad account is active.")
end
context "when requester already has an account" do
let!(:requester) { create(:user, email: requester_email) }
it "does not ask to create an account" do
expect(mail.body.encoded).to_not include("In the meantime, <a href=\"#{signup_url(email: requester_email)}\">create your Gumroad account</a> using email #{requester_email} and confirm it. You'll receive your affiliate links once your Gumroad account is active.")
end
end
end
describe "notify_requester_of_request_approval" do
let(:affiliate_request) { create(:affiliate_request, email: requester_email, seller: creator) }
let!(:requester) { create(:user, email: requester_email) }
let(:published_product_one) { create(:product, user: creator) }
let(:published_product_two) { create(:product, user: creator) }
let(:published_product_three) { create(:product, user: creator) }
let!(:enabled_self_service_affiliate_product_for_published_product_one) { create(:self_service_affiliate_product, enabled: true, seller: creator, product: published_product_one) }
let!(:enabled_self_service_affiliate_product_for_published_product_two) { create(:self_service_affiliate_product, enabled: true, seller: creator, product: published_product_two) }
let!(:enabled_self_service_affiliate_product_for_published_product_three) { create(:self_service_affiliate_product, enabled: true, seller: creator, product: published_product_three, affiliate_basis_points: 1000) }
subject(:mail) { described_class.notify_requester_of_request_approval(affiliate_request.id) }
before(:each) do
affiliate_request.approve!
end
it "sends email to requester" do
expect(mail.to).to eq([requester_email])
expect(mail.subject).to eq("Your affiliate request to #{creator.display_name} was approved!")
expect(mail.body.encoded).to include("Congratulations, you are now an official affiliate for #{creator.display_name}!")
expect(mail.body.encoded).to include("You can now promote these products using these unique URLs:")
requester.directly_affiliated_products.where(affiliates: { seller_id: creator.id }).each do |product|
affiliate = product.direct_affiliates.first
affiliate_percentage = affiliate.basis_points(product_id: product.id) / 100
affiliate_product_url = affiliate.referral_url_for_product(product)
expect(mail.body.encoded.squish).to include(%Q(<strong>#{product.name}</strong> (#{affiliate_percentage}% commission) <br> <a clicktracking="off" href="#{affiliate_product_url}">#{affiliate_product_url}</a>))
end
expect(mail.body.encoded.squish).to include(%Q(<a class="button primary" href="#{products_affiliated_index_url}">View all affiliated products</a>))
end
end
describe "notify_requester_of_ignored_request" do
subject(:mail) { described_class.notify_requester_of_ignored_request(affiliate_request.id) }
before do
affiliate_request.ignore!
end
it "sends email to requester" do
expect(mail.to).to eq([requester_email])
expect(mail.subject).to eq("Your affiliate request to #{creator.display_name} was not approved")
expect(mail.body.encoded).to include("We are sorry, but your request to become an affiliate for #{creator.display_name} was not approved.")
expect(mail.body.encoded).to include("<strong>Name:</strong> #{affiliate_request.name}")
expect(mail.body.encoded).to include("<strong>Email:</strong> #{requester_email}")
end
end
describe "notify_unregistered_requester_of_request_approval" do
let(:affiliate_request) { create(:affiliate_request, email: requester_email, seller: creator) }
let(:published_product) { create(:product, user: creator) }
let!(:enabled_self_service_affiliate_product_for_published_product) { create(:self_service_affiliate_product, enabled: true, seller: creator, product: published_product) }
subject(:mail) { described_class.notify_unregistered_requester_of_request_approval(affiliate_request.id) }
before(:each) do
affiliate_request.approve!
end
it "sends email to requester" do
expect(mail.to).to eq([requester_email])
expect(mail.subject).to eq("Your affiliate request to #{creator.display_name} was approved!")
expect(mail.body.encoded).to include("Congratulations, #{creator.display_name} has approved your request to become an affiliate. In order to receive your affiliate links, you must first")
expect(mail.body.encoded).to include(%Q(<a href="#{signup_url(email: requester_email)}">create your Gumroad account</a> using email #{requester_email} and confirm it.))
end
end
describe "notify_seller_of_new_request" do
subject(:mail) { described_class.notify_seller_of_new_request(affiliate_request.id) }
it "sends email to creator" do
expect(mail.to).to eq([creator.email])
expect(mail.subject).to eq("#{affiliate_request.name} has applied to be an affiliate")
expect(mail.body.encoded).to include("<strong>Name:</strong> #{affiliate_request.name}")
expect(mail.body.encoded).to include("<strong>Email:</strong> #{requester_email}")
expect(mail.body.encoded).to include(%Q("#{affiliate_request.promotion_text}"))
expect(mail.body.encoded).to include(%Q(<a class="button primary" href="#{approve_affiliate_request_url(affiliate_request)}">Approve</a>))
expect(mail.body.encoded).to include(%Q(<a class="button" href="#{ignore_affiliate_request_url(affiliate_request)}">Ignore</a>))
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/community_chat_recap_mailer_spec.rb | spec/mailers/community_chat_recap_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CommunityChatRecapMailer do
describe "community_chat_recap_notification" do
let(:user) { create(:user) }
let(:seller) { create(:user, name: "John Doe") }
let(:product) { create(:product, user: seller, name: "Snap app") }
let!(:community) { create(:community, seller:, resource: product) }
context "when sending daily recap" do
let(:recap_run) { create(:community_chat_recap_run, :finished, from_date: Date.parse("Mar 26, 2025").beginning_of_day, to_date: Date.parse("Mar 26, 2025").end_of_day) }
let!(:community_chat_recap) { create(:community_chat_recap, :finished, community:, community_chat_recap_run: recap_run, summary: "<ul><li>Creator welcomed everyone to the community.</li><li>A customer asked about using <strong>a specific feature</strong>.</li><li>Creator provided detailed instructions on how to use the feature.</li><li>Two customers expressed their gratitude for the information and help.</li></ul>", summarized_message_count: 10) }
subject(:mail) { described_class.community_chat_recap_notification(user.id, seller.id, [community_chat_recap.id]) }
it "emails to user with daily recap" do
expect(mail.to).to eq([user.form_email])
expect(mail.subject).to eq("Your daily John Doe community recap: March 26, 2025")
expect(mail.body).to have_text("Here's a quick daily summary of what's been happening in John Doe community.")
expect(mail.body).to have_text("# Snap app")
expect(mail.body.encoded).to include("<li>Creator welcomed everyone to the community.</li>")
expect(mail.body.encoded).to include("<li>A customer asked about using <strong>a specific feature</strong>.</li>")
expect(mail.body.encoded).to include("<li>Creator provided detailed instructions on how to use the feature.</li>")
expect(mail.body.encoded).to include("<li>Two customers expressed their gratitude for the information and help.</li>")
expect(mail.body.encoded).to include("10 messages summarised")
expect(mail.body.encoded).to have_link("Join the conversation", href: community_url(seller.external_id, community.external_id))
expect(mail.body).to have_text("You are receiving this email because you're part of the John Doe community. To stop receiving daily recap emails, please update your notification settings.")
expect(mail.body.encoded).to have_link("update your notification settings", href: community_url(seller.external_id, community.external_id, notifications: "true"))
end
end
context "when sending weekly recap" do
let(:from_date) { Date.parse("Mar 17, 2025").beginning_of_day }
let(:weekly_recap_run) { create(:community_chat_recap_run, :weekly, from_date:, to_date: (from_date + 6.days).end_of_day) }
let!(:weekly_recap) { create(:community_chat_recap, :finished, community:, community_chat_recap_run: weekly_recap_run, summary: "<ul><li>The <strong>new version of the app</strong> was shared by the creator, along with a confirmed <strong>release date</strong> for Android.</li><li>Customers raised concerns regarding various <strong>product issues</strong>, which the creator acknowledged and assured would be addressed in the <strong>next version</strong>.</li></ul>", summarized_message_count: 104) }
let(:product2) { create(:product, user: seller, name: "Bubbles app") }
let(:community2) { create(:community, seller:, resource: product2) }
let!(:weekly_recap2) { create(:community_chat_recap, :finished, community: community2, community_chat_recap_run: weekly_recap_run, summary: "<ul><li>Creator welcomed everyone to the community.</li><li>People discussed various <strong>product issues</strong>.</li></ul>", summarized_message_count: 24) }
subject(:mail) { described_class.community_chat_recap_notification(user.id, seller.id, [weekly_recap.id, weekly_recap2.id]) }
it "emails to user with weekly recap" do
expect(mail.to).to eq([user.form_email])
expect(mail.subject).to eq("Your weekly John Doe community recap: March 17-23, 2025")
expect(mail.body).to have_text("Here's a weekly summary of what happened in John Doe community.")
expect(mail.body).to have_text("# Snap app")
expect(mail.body.encoded).to include("The <strong>new version of the app</strong> was shared by the creator")
expect(mail.body.encoded).to include("Customers raised concerns regarding various <strong>product issues</strong>")
expect(mail.body.encoded).to include("104 messages summarised")
expect(mail.body).to have_text("# Bubbles app")
expect(mail.body.encoded).to include("<li>Creator welcomed everyone to the community.</li>")
expect(mail.body.encoded).to include("<li>People discussed various <strong>product issues</strong>.</li>")
expect(mail.body.encoded).to include("24 messages summarised")
expect(mail.body.encoded).to have_link("Join the conversation", href: community_url(seller.external_id, community.external_id))
expect(mail.body).to have_text("You are receiving this email because you're part of the John Doe community. To stop receiving weekly recap emails, please update your notification settings.")
expect(mail.body.encoded).to have_link("update your notification settings", href: community_url(seller.external_id, community.external_id, notifications: "true"))
end
context "when recap spans multiple months" do
let(:from_date) { Date.new(2025, 12, 28) }
let(:to_date) { Date.new(2026, 1, 3) }
let(:weekly_recap_run) { create(:community_chat_recap_run, :weekly, from_date:, to_date:) }
it "formats date range correctly in subject" do
expect(mail.subject).to eq("Your weekly John Doe community recap: December 28, 2025-January 3, 2026")
end
end
context "when recap spans different months in same year" do
let(:from_date) { Date.new(2025, 3, 30) }
let(:to_date) { Date.new(2025, 4, 5) }
let(:weekly_recap_run) { create(:community_chat_recap_run, :weekly, from_date:, to_date:) }
it "formats date range correctly in subject" do
expect(mail.subject).to eq("Your weekly John Doe community recap: March 30-April 5, 2025")
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/mailers/user_signup_mailer_spec.rb | spec/mailers/user_signup_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UserSignupMailer do
it "includes RescueSmtpErrors" do
expect(described_class).to include(RescueSmtpErrors)
end
describe "#confirmation_instructions" do
before do
user = create(:user)
@mail = described_class.confirmation_instructions(user, {})
end
it "sets the correct headers" do
expect(@mail.subject).to eq "Confirmation instructions"
expect(@mail.from).to eq [ApplicationMailer::NOREPLY_EMAIL]
expect(@mail.reply_to).to eq [ApplicationMailer::NOREPLY_EMAIL]
end
it "includes the notification message" do
expect(@mail.body).to include("Confirm your email address")
expect(@mail.body).to include("Please confirm your account by clicking the button below.")
expect(@mail.body).to include("If you didn't request this, please ignore this email. You won't get another one!")
end
end
describe "#email_changed" do
before do
@user = create(:user, email: "original@example.com", unconfirmed_email: "new@example.com")
@mail = described_class.email_changed(@user)
end
it "sets the correct headers" do
expect(@mail.subject).to eq "Security alert: Your Gumroad account email is being changed"
expect(@mail.from).to eq [ApplicationMailer::NOREPLY_EMAIL]
expect(@mail.reply_to).to eq [ApplicationMailer::NOREPLY_EMAIL]
end
it "includes the notification message" do
expect(@mail.body).to include("Your Gumroad account email is being changed")
expect(@mail.body).to include("We're contacting you to notify that your Gumroad account email is being changed from original@example.com to new@example.com.")
expect(@mail.body).to include("If you did not make this change, please contact support immediately by replying to this email.")
expect(@mail.body).to include("User ID: #{@user.external_id}")
end
end
describe "#reset_password_instructions" do
before do
user = create(:user)
@mail = described_class.reset_password_instructions(user, {})
end
it "sets the correct headers" do
expect(@mail.subject).to eq "Reset password instructions"
expect(@mail.from).to eq [ApplicationMailer::NOREPLY_EMAIL]
expect(@mail.reply_to).to eq [ApplicationMailer::NOREPLY_EMAIL]
end
it "includes the notification message" do
expect(@mail.body).to include("Forgotten password request")
expect(@mail.body).to include("It seems you forgot the password for your Gumroad account. You can change your password by clicking the button below:")
expect(@mail.body).to include("If you didn't request this, please ignore this email. You won't get another one!")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/service_mailer_spec.rb | spec/mailers/service_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ServiceMailer do
before do
@user = create(:user)
@black_recurring_service = create(:black_recurring_service, user: @user)
end
describe "service_charge_receipt" do
it "renders properly" do
service_charge = create(:service_charge, user: @user, recurring_service: @black_recurring_service)
mail = ServiceMailer.service_charge_receipt(service_charge.id)
expect(mail.subject).to eq "Gumroad — Receipt"
expect(mail.to).to eq [@user.email]
expect(mail.body).to include "Thanks for continuing to support Gumroad!"
expect(mail.body).to include "you'll be charged at the same rate."
end
it "renders properly with discount code" do
service_charge = create(:service_charge, discount_code: DiscountCode::INVITE_CREDIT_DISCOUNT_CODE, user: @user, recurring_service: @black_recurring_service)
mail = ServiceMailer.service_charge_receipt(service_charge.id)
expect(mail.subject).to eq "Gumroad — Receipt"
expect(mail.to).to eq [@user.email]
expect(mail.body).to include "Thanks for continuing to support Gumroad!"
expect(mail.body).to include "you'll be charged at the same rate."
expect(mail.body).to include "Credit applied:"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/contacting_creator_mailer_spec.rb | spec/mailers/contacting_creator_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ContactingCreatorMailer do
let(:custom_mailer_route_helper) do
Class.new(ActionMailer::Base) do
include CustomMailerRouteBuilder
end.new
end
it "uses SUPPORT_EMAIL_WITH_NAME as default from address" do
expect(described_class.default[:from]).to eq(ApplicationMailer::SUPPORT_EMAIL_WITH_NAME)
end
describe "cannot pay" do
before { @payment = create(:payment) }
it "sends notice to the payment user" do
mail = ContactingCreatorMailer.cannot_pay(@payment.id)
expect(mail.to).to eq [@payment.user.email]
expect(mail.subject).to eq("We were unable to pay you.")
expect(mail.from).to eq([ApplicationMailer::SUPPORT_EMAIL])
end
end
describe "purchase refunded" do
it "sends notification to the seller about refunded purchase" do
purchase = create(:purchase, link: create(:product, name: "Digital Membership"), email: "test@example.com", price_cents: 10_00)
mail = ContactingCreatorMailer.purchase_refunded(purchase.id)
expect(mail.to).to eq [purchase.seller.email]
expect(mail.subject).to eq("A sale has been refunded")
expect(mail.body.encoded).to include "test@example.com's purchase of Digital Membership for $10 has been refunded."
expect(mail.from).to eq([ApplicationMailer::SUPPORT_EMAIL])
end
end
describe "purchase refunded for fraud" do
it "sends notification to the seller about purchase refunded for fraud" do
purchase = create(:purchase, link: create(:product, name: "Digital Membership"), email: "test@example.com", price_cents: 10_00)
mail = ContactingCreatorMailer.purchase_refunded_for_fraud(purchase.id)
expect(mail.to).to eq [purchase.seller.email]
expect(mail.subject).to eq("Fraud was detected on your Gumroad account.")
expect(mail.body.encoded).to include "Our risk team has detected a fraudulent transaction on one of your products, using a stolen card."
expect(mail.body.encoded).to include "We have refunded test@example.com's purchase of Digital Membership for $10."
expect(mail.body.encoded).to include "We're doing our best to protect you, and no further action needs to be taken on your part."
expect(mail.from).to eq([ApplicationMailer::SUPPORT_EMAIL])
end
end
describe "chargeback notice" do
let(:seller) { create(:named_seller) }
context "for a dispute on Purchase" do
let(:purchase) { create(:purchase, link: create(:product, user: seller)) }
let(:dispute) { create(:dispute_formalized, purchase:) }
it "sends chargeback notice correctly" do
mail = ContactingCreatorMailer.chargeback_notice(dispute.id)
expect(mail.to).to eq [seller.email]
expect(mail.subject).to eq "A sale has been disputed"
expect(mail.body.encoded).to include "A customer of yours (#{purchase.email}) has disputed their purchase of #{purchase.link.name} for #{purchase.formatted_disputed_amount}."
expect(mail.body.encoded).to include "We have deducted the amount from your balance, and are looking into it for you."
expect(mail.body.encoded).to include "We fight every dispute. If we succeed, you will automatically be re-credited the full amount. This process takes up to 75 days."
expect(mail.body.encoded).not_to include "Any additional information you can provide"
end
context "when the seller is contacted to submit evidence" do
let!(:dispute_evidence) do
create(:dispute_evidence, dispute:)
end
it "includes copy to submit evidence" do
mail = ContactingCreatorMailer.chargeback_notice(dispute.id)
expect(mail.subject).to eq "🚨 Urgent: Action required for resolving disputed sale"
expect(mail.body.encoded).to include "A customer of yours (#{purchase.email}) has disputed their purchase of #{purchase.link.name} for #{purchase.formatted_disputed_amount}."
expect(mail.body.encoded).to include "Any additional information you can provide in the next 72 hours will help us win on your behalf."
expect(mail.body.encoded).to include "Submit additional information"
end
end
context "when the purchase was done via a PayPal Connect account" do
before do
purchase.update!(charge_processor_id: PaypalChargeProcessor.charge_processor_id)
end
it "includes copy about PayPal's dispute process" do
mail = ContactingCreatorMailer.chargeback_notice(dispute.id)
expect(mail.body.encoded).to include "A customer of yours (#{purchase.email}) has disputed their purchase of #{purchase.link.name} for #{purchase.formatted_disputed_amount}."
expect(mail.body.encoded).to include "Unfortunately, we’re unable to fight disputes on purchases via PayPal Connect since we don’t have access to your PayPal account."
end
end
end
context "for a dispute on Charge" do
let(:charge) do
charge = create(:charge, seller:)
charge.purchases << create(:purchase, link: create(:product, user: seller))
charge.purchases << create(:purchase, link: create(:product, user: seller))
charge.purchases << create(:purchase, link: create(:product, user: seller))
charge
end
let(:dispute) { create(:dispute_formalized_on_charge, purchase: nil, charge:) }
it "sends chargeback notice correctly" do
mail = ContactingCreatorMailer.chargeback_notice(dispute.id)
expect(mail.to).to eq [seller.email]
expect(mail.subject).to eq "A sale has been disputed"
expect(mail.body.encoded).to include "A customer of yours (#{charge.customer_email}) has disputed their purchase of the following items for #{charge.formatted_disputed_amount}."
charge.disputed_purchases.each do |purchase|
expect(mail.body.encoded).to include purchase.link.name
end
expect(mail.body.encoded).to include "We have deducted the amount from your balance, and are looking into it for you."
expect(mail.body.encoded).to include "We fight every dispute. If we succeed, you will automatically be re-credited the full amount. This process takes up to 75 days."
expect(mail.body.encoded).not_to include "Any additional information you can provide"
end
context "when the seller is contacted to submit evidence" do
let!(:dispute_evidence) do
create(:dispute_evidence_on_charge, dispute:)
end
it "includes copy to submit evidence" do
mail = ContactingCreatorMailer.chargeback_notice(dispute.id)
expect(mail.subject).to eq "🚨 Urgent: Action required for resolving disputed sale"
expect(mail.body.encoded).to include "A customer of yours (#{charge.customer_email}) has disputed their purchase of the following items for #{charge.formatted_disputed_amount}."
charge.disputed_purchases.each do |purchase|
expect(mail.body.encoded).to include purchase.link.name
end
expect(mail.body.encoded).to include "Any additional information you can provide in the next 72 hours will help us win on your behalf."
expect(mail.body.encoded).to include "Submit additional information"
end
end
context "when the purchase was done via a PayPal Connect account" do
before do
charge.update!(processor: PaypalChargeProcessor.charge_processor_id)
end
it "includes copy about PayPal's dispute process" do
mail = ContactingCreatorMailer.chargeback_notice(dispute.id)
expect(mail.body.encoded).to include "A customer of yours (#{charge.customer_email}) has disputed their purchase of the following items for #{charge.formatted_disputed_amount}."
charge.disputed_purchases.each do |purchase|
expect(mail.body.encoded).to include purchase.link.name
end
expect(mail.body.encoded).to include "Unfortunately, we’re unable to fight disputes on purchases via PayPal Connect since we don’t have access to your PayPal account."
end
end
end
end
describe "negative_revenue_sale_failure", :vcr do
before do
product = create(:product, price_cents: 100, user: create(:user, email: "seller@gr.co"))
affiliate = create(:direct_affiliate, affiliate_basis_points: 7500, products: [product])
allow_any_instance_of(Purchase).to receive(:determine_affiliate_balance_cents).and_return(90)
@purchase = create(:purchase, link: product, seller: product.user, affiliate:, save_card: false, chargeable: create(:chargeable))
@purchase.process!
end
it "sends the correct sale failure email" do
mail = ContactingCreatorMailer.negative_revenue_sale_failure(@purchase.id)
expect(mail.to).to eq ["seller@gr.co"]
expect(mail.subject).to eq "A sale failed because of negative net revenue"
expect(mail.body.encoded).to include "A customer (#{@purchase.email}) attempted to purchase your product (#{@purchase.link.name}) for #{@purchase.formatted_display_price}."
expect(mail.body.encoded).to include "But the purchase was blocked because your net revenue from it was not positive."
expect(mail.body.encoded).to include "You should either increase the sale price of your product, or reduce the applicable discount and/or affiliate commission."
end
end
describe "preorder_release_reminder" do
let(:preorder_link) { create(:preorder_link) }
let(:product) { preorder_link.link }
let(:seller) { product.user }
context "for a physical product" do
before do
product.update!(is_physical: true, require_shipping: true)
end
it "sends the email with the the correct text" do
email = ContactingCreatorMailer.preorder_release_reminder(product.id)
expect(email.to).to eq [seller.form_email]
expect(email.subject).to eq "Your pre-order will be released shortly"
expect(email.body.encoded).to include "Your pre-order, #{product.name} will be released on"
expect(email.body.encoded).to include "Charges will occur at that time."
expect(email.body.encoded).to include "Your customers will be excited for #{product.name} to ship shortly after they are charged."
expect(email.body.encoded).to_not include "You will need to upload a file before its release, or we won't be able to release the product and charge your customers"
end
end
context "for a non-physical product" do
context "when the product does not have delivery content saved" do
before do
allow_any_instance_of(Link).to receive(:has_content?).and_return(false)
end
it "sends the email with the the correct text" do
email = ContactingCreatorMailer.preorder_release_reminder(product.id)
expect(email.to).to eq [seller.form_email]
expect(email.subject).to eq "Your pre-order will be released shortly"
expect(email.body.encoded).to include "Your pre-order, #{product.name} is scheduled for a release on"
expect(email.body.encoded).to include "You will need to"
expect(email.body.encoded).to include "upload files or specify a redirect URL"
expect(email.body.encoded).to include "before its release, or we won't be able to release the product and charge your customers."
end
end
context "when the product has delivery content saved" do
before do
allow_any_instance_of(Link).to receive(:has_content?).and_return(true)
end
it "sends the email with the the correct text" do
email = ContactingCreatorMailer.preorder_release_reminder(product.id)
expect(email.to).to eq [seller.form_email]
expect(email.subject).to eq "Your pre-order will be released shortly"
expect(email.body.encoded).to include "Your pre-order, #{product.name} will be released on"
expect(email.body.encoded).to include "Once released all credit cards will be charged."
expect(email.body.encoded).to_not include "You will need to upload a file before its release, or we won't be able to release the product and charge your customers"
end
end
end
end
describe "remind" do
before do
@user = create(:user, email: "blah@example.com")
allow_any_instance_of(User).to receive(:secure_external_id).and_return("sample-secure-id")
end
it "sends out a reminder" do
mail = ContactingCreatorMailer.remind(@user.id)
expect(mail.to).to eq ["blah@example.com"]
expect(mail.subject).to eq "Please add a payment account to Gumroad."
expect(mail.body.encoded).to include user_unsubscribe_url(id: "sample-secure-id", email_type: :product_update)
end
end
describe "seller_update" do
before do
@user = create(:user)
allow_any_instance_of(User).to receive(:secure_external_id).and_return("sample-secure-id")
end_of_period = Date.today.beginning_of_week(:sunday).to_datetime
@start_of_period = end_of_period - 7.days
end
it "sends an update to the seller" do
mail = ContactingCreatorMailer.seller_update(@user.id)
expect(mail.subject).to eq "Your last week."
expect(mail.to).to eq [@user.email]
expect(mail.body.encoded).to include user_unsubscribe_url(id: "sample-secure-id", email_type: :seller_update)
end
describe "subscriptions" do
before do
@user = create(:user)
@product = create(:subscription_product, user: @user)
@product_subscription1 = create(:subscription, link: @product)
end
it "renders properly" do
@product_subscription2 = create(:subscription, link: @product)
link2 = create(:subscription_product, user: @user)
link2_subscription1 = create(:subscription, link: link2)
create(:purchase, subscription_id: @product_subscription1.id, is_original_subscription_purchase: true, link: @product, created_at: @start_of_period + 1.hour)
create(:purchase, subscription_id: @product_subscription2.id, is_original_subscription_purchase: true, link: @product, created_at: @start_of_period + 1.hour)
create(:purchase, subscription_id: link2_subscription1.id, is_original_subscription_purchase: true, link: link2, created_at: 17.days.ago)
create(:purchase, subscription_id: link2_subscription1.id, is_original_subscription_purchase: false, link: link2, created_at: @start_of_period + 1.hour)
mail = ContactingCreatorMailer.seller_update(@user.id)
expect(mail.subject).to eq "Your last week."
expect(mail.to).to eq [@user.email]
expect(mail.body).to include @product.name
expect(mail.body).to include "2 new subscriptions"
expect(mail.body).to include link2.name
expect(mail.body).to include "1 existing subscription"
end
it "does not show any new subscriptions" do
create(:purchase, subscription_id: @product_subscription1.id, is_original_subscription_purchase: true, link: @product, created_at: 19.days.ago)
create(:purchase, subscription_id: @product_subscription1.id, is_original_subscription_purchase: false, link: @product, created_at: @start_of_period + 1.hour)
mail = ContactingCreatorMailer.seller_update(@user.id)
expect(mail.subject).to eq "Your last week."
expect(mail.to).to eq [@user.email]
expect(mail.body).to include @product.name
expect(mail.body).to include "1 existing subscription"
expect(mail.body).to_not include "new subscription"
end
end
describe "sales" do
before do
@user = create(:user)
@product = create(:product, user: @user, is_recurring_billing: false, created_at: @start_of_period - 2.hours)
@product2 = create(:product, user: @user, is_recurring_billing: false, created_at: @start_of_period - 2.hours)
2.times { create(:purchase, link: @product, created_at: @start_of_period + 1.hour) }
create(:purchase, link: @product, created_at: 5.minutes.ago)
create(:purchase, link: @product2, created_at: @start_of_period + 1.hour)
create(:purchase, link: @product2, created_at: @start_of_period + 1.hour, chargeback_date: DateTime.current)
end
it "renders properly" do
mail = ContactingCreatorMailer.seller_update(@user.id)
expect(mail.subject).to eq "Your last week."
expect(mail.to).to eq [@user.email]
expect(mail.body).to include "$0.21" # 3 not-chargebacked purchases * 7¢ each.
expect(mail.body).to include @product.name
expect(mail.body).to include "2 sales"
expect(mail.body).to include @product2.name
expect(mail.body).to include "1 sale"
end
end
end
describe "credit_notification" do
before do
@user = create(:user)
end
it "notifies user about credit to their account" do
mail = ContactingCreatorMailer.credit_notification(@user.id, 200)
expect(mail.to).to eq [@user.email]
expect(mail.subject).to eq "You've received Gumroad credit!"
expect(mail.body.encoded).to include "$2"
end
end
describe "gumroad_day_credit_notification" do
before do
@user = create(:user)
end
it "notifies user about credit to their account" do
mail = ContactingCreatorMailer.gumroad_day_credit_notification(@user.id, 200)
expect(mail.to).to eq [@user.email]
expect(mail.subject).to eq "You've received Gumroad credit!"
expect(mail.body.encoded).to include "$2"
end
end
describe "notify" do
let(:seller) { create(:user, email: "seller@example.com") }
let(:buyer) { create(:user, email: "buyer@example.com") }
let(:product) { create(:product, user: seller) }
let(:purchase) { create(:purchase, link: product, seller: product.user) }
before do
Feature.activate(:send_sales_notifications_to_creator_app)
end
def expect_push_alert(seller_id, text)
expect(PushNotificationWorker).to have_enqueued_sidekiq_job(seller_id,
Device::APP_TYPES[:creator],
text, nil, {}, "chaching.wav")
end
it "uses SUPPORT_EMAIL as from address" do
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.from).to eq([ApplicationMailer::SUPPORT_EMAIL])
end
it "works normally" do
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.subject).to eq "New sale of #{product.name} for #{purchase.formatted_total_price}"
expect(mail.to).to eq([seller.email])
expect_push_alert(seller.id, mail.subject)
end
it "works for $0 purchases" do
product = create(:product, user: seller, price_cents: 0, customizable_price: true)
purchase = create(:purchase, link: product, seller: product.user, stripe_transaction_id: nil, stripe_fingerprint: nil)
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.subject).to eq "New download of #{product.name}"
expect_push_alert(seller.id, mail.subject)
end
it "works without a purchaser" do
purchase.create_url_redirect!
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.subject).to eq "New sale of #{product.name} for #{purchase.formatted_total_price}"
expect_push_alert(seller.id, mail.subject)
end
it "does not work without a buyer email" do
seller = create(:user, email: "bob@gumroad.com")
buyer = create(:user, email: "bob2@gumroad.com")
link = create(:product, user: seller)
purchase = create(:purchase, link:, purchaser: buyer, seller: link.user)
expect(purchase.update(email: nil)).to be(false)
end
it "includes discover notice and sets the referrer to Gumroad Discover" do
seller = create(:user, email: "bob@gumroad.com")
buyer = create(:user, email: "bob2@gumroad.com")
link = create(:physical_product, user: seller)
purchase = create(:physical_purchase, link:, purchaser: buyer, seller: link.user, was_discover_fee_charged: true, referrer: UrlService.discover_domain_with_protocol)
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.body.encoded).to include "Referrer"
expect(mail.body.encoded).to include "<a href=\"#{UrlService.discover_domain_with_protocol}\" target=\"_blank\">Gumroad Discover</a>"
expect_push_alert(seller.id, mail.subject)
end
it "sets the referrer to Direct when the referrer URL equals 'direct'" do
seller = create(:user, email: "bob@gumroad.com")
product = create(:product, user: seller)
purchase = create(:purchase, link: product, email: "ibuy@gumroad.com", referrer: "direct")
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.body.encoded).to include "Referrer"
expect(mail.body.encoded).to include "Direct"
expect_push_alert(seller.id, mail.subject)
end
it "sets the referrer to Profile when the referrer URL is from the seller's profile" do
seller = create(:user, email: "bob@gumroad.com")
product = create(:product, user: seller)
purchase = create(:purchase, link: product, email: "ibuy@gumroad.com", referrer: "https://#{seller.username}.gumroad.com")
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.body.encoded).to include "Referrer"
expect(mail.body.encoded).to include "<a href=\"https://#{seller.username}.gumroad.com\" target=\"_blank\">Profile</a>"
expect_push_alert(seller.id, mail.subject)
end
it "sets the referrer to Twitter when the referrer URL is from twitter" do
seller = create(:user, email: "bob@gumroad.com")
product = create(:product, user: seller)
purchase = create(:purchase, link: product, email: "ibuy@gumroad.com", referrer: "https://twitter.com/")
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.body.encoded).to include "Referrer"
expect(mail.body.encoded).to include '<a href="https://twitter.com/" target="_blank">Twitter</a>'
expect_push_alert(seller.id, mail.subject)
end
it "includes quantity if greater than 1" do
seller = create(:user, email: "bob@gumroad.com")
buyer = create(:user, email: "bob2@gumroad.com")
link = create(:physical_product, user: seller)
purchase = create(:physical_purchase, link:, purchaser: buyer, seller: link.user, quantity: 3)
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.subject).to eq "New sale of #{link.name} for #{purchase.formatted_total_price}"
expect(mail.body.encoded).to include "Quantity"
expect(mail.body.encoded).to include "3"
expect_push_alert(seller.id, mail.subject)
end
it "includes product price, shipping cost, and total transaction" do
seller = create(:user, email: "bob@gumroad.com")
buyer = create(:user, email: "bob2@gumroad.com")
link = create(:physical_product, user: seller)
purchase = create(:physical_purchase, link:, purchaser: buyer, seller: link.user, quantity: 3, shipping_cents: 400, price_cents: 500)
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.subject).to eq "New sale of #{link.name} for #{purchase.formatted_total_price}"
expect(mail.body.encoded).to include "Product price"
expect(mail.body.encoded).to include "$1"
expect(mail.body.encoded).to include "Shipping"
expect(mail.body.encoded).to include "$4"
expect(mail.body.encoded).to include "Order total"
expect(mail.body.encoded).to include "$5"
expect(mail.body.encoded).to include "Shipping address"
expect(mail.body.encoded).to include "barnabas"
expect(mail.body.encoded).to include "123 barnabas street"
expect(mail.body.encoded).to include "barnabasville, CA 94114"
expect(mail.body.encoded).to include "United States"
expect_push_alert(seller.id, mail.subject)
end
it "includes product price, nonzero tax, and total transaction" do
seller = create(:user, email: "bob@gumroad.com")
buyer = create(:user, email: "bob2@gumroad.com")
link = create(:product, user: seller)
purchase = create(:purchase,
link:,
purchaser: buyer,
seller: link.user,
quantity: 1,
tax_cents: 40,
price_cents: 140,
was_purchase_taxable: true,
was_tax_excluded_from_price: true,
zip_tax_rate: create(:zip_tax_rate))
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.subject).to eq "New sale of #{link.name} for #{purchase.formatted_total_price}"
expect(mail.body.encoded).to include "Product price"
expect(mail.body.encoded).to include "$1"
expect(mail.body.encoded).to include "Sales tax"
expect(mail.body.encoded).to include "$0.40"
expect(mail.body.encoded).to include "Order total"
expect(mail.body.encoded).to include "$1.40"
expect_push_alert(seller.id, mail.subject)
end
it "includes product price, nonzero VAT, and total transaction" do
seller = create(:user, email: "bob@gumroad.com")
buyer = create(:user, email: "bob2@gumroad.com")
link = create(:product, user: seller)
purchase = create(:purchase,
link:,
purchaser: buyer,
seller: link.user,
quantity: 1,
tax_cents: 40,
price_cents: 140,
was_purchase_taxable: true,
was_tax_excluded_from_price: true,
zip_tax_rate: create(:zip_tax_rate, country: "DE"))
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.subject).to eq "New sale of #{link.name} for #{purchase.formatted_total_price}"
expect(mail.body.encoded).to include "Product price"
expect(mail.body.encoded).to include "$1"
expect(mail.body.encoded).to include "EU VAT"
expect(mail.body.encoded).to include "$0.40"
expect(mail.body.encoded).to include "Order total"
expect(mail.body.encoded).to include "$1.40"
expect_push_alert(seller.id, mail.subject)
end
it "includes product price, nonzero VAT inclusive, and total transaction" do
seller = create(:user, email: "bob@gumroad.com")
buyer = create(:user, email: "bob2@gumroad.com")
link = create(:product, user: seller)
purchase = create(:purchase,
link:,
purchaser: buyer,
seller: link.user,
quantity: 1,
tax_cents: 40,
price_cents: 140,
was_purchase_taxable: true,
was_tax_excluded_from_price: false,
zip_tax_rate: create(:zip_tax_rate, country: "DE"))
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.subject).to eq "New sale of #{link.name} for #{purchase.formatted_total_price}"
expect(mail.body.encoded).to include "Product price"
expect(mail.body.encoded).to include "$1"
expect(mail.body.encoded).to include "EU VAT (included)"
expect(mail.body.encoded).to include "$0.40"
expect(mail.body.encoded).to include "Order total"
expect(mail.body.encoded).to include "$1.40"
expect_push_alert(seller.id, mail.subject)
end
it "does not include tax if it is 0" do
seller = create(:user, email: "bob@gumroad.com")
buyer = create(:user, email: "bob2@gumroad.com")
link = create(:product, user: seller)
purchase = create(:purchase,
link:,
purchaser: buyer,
seller: link.user,
quantity: 1,
tax_cents: 0,
price_cents: 100,
was_purchase_taxable: true,
was_tax_excluded_from_price: true,
zip_tax_rate: create(:zip_tax_rate))
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.subject).to eq "New sale of #{link.name} for #{purchase.formatted_total_price}"
expect(mail.body.encoded).to include "Product price"
expect(mail.body.encoded).to include "$1"
expect(mail.body.encoded).to_not include "Sales tax"
expect(mail.body.encoded).to include "Order total"
expect(mail.body.encoded).to include "$1"
expect_push_alert(seller.id, mail.subject)
end
it "includes product price, shipping cost, and total transaction for jpy" do
seller = create(:user, email: "bob@gumroad.com")
buyer = create(:user, email: "bob2@gumroad.com")
link = create(:physical_product, user: seller, price_currency_type: "jpy")
purchase = create(:physical_purchase, link:, purchaser: buyer, seller: link.user, shipping_cents: 400, price_cents: 528, displayed_price_cents: 100, displayed_price_currency_type: "jpy")
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.subject).to eq "New sale of #{link.name} for #{purchase.formatted_total_price}"
expect(mail.body.encoded).to include "Product price"
expect(mail.body.encoded).to include "¥100"
expect(mail.body.encoded).to include "Shipping"
expect(mail.body.encoded).to include "¥314"
expect(mail.body.encoded).to include "Order total"
expect(mail.body.encoded).to include "¥414"
expect_push_alert(seller.id, mail.subject)
end
it "includes discount information" do
seller = create(:user, email: "bob@gumroad.com")
product = create(:product, user: seller, price_cents: 500)
offer_code = create(:percentage_offer_code, products: [product], name: "Black Friday", amount_percentage: 10)
purchase = create(:purchase, link: product, email: "ibuy@gumroad.com", offer_code:)
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.body.encoded).to include "Discount"
expect(mail.body.encoded).to include "Black Friday (10% off)"
expect_push_alert(seller.id, mail.subject)
end
it "includes upsell information without offer code" do
seller = create(:user, email: "bob@gumroad.com")
product = create(:product_with_digital_versions, user: seller)
upsell = create(:upsell, product:, name: "Complete course", seller:)
upsell_variant = create(:upsell_variant, upsell:, selected_variant: product.alive_variants.first, offered_variant: product.alive_variants.second)
upsell_purchase = create(:upsell_purchase, upsell:, upsell_variant:)
mail = ContactingCreatorMailer.notify(upsell_purchase.purchase.id)
expect(mail.body.encoded).to include "Upsell"
expect(mail.body.encoded).to include "Complete course"
expect_push_alert(seller.id, mail.subject)
end
it "includes upsell information with offer code" do
seller = create(:user, email: "bob@gumroad.com")
product = create(:product_with_digital_versions, user: seller, price_cents: 1000)
offer_code = create(:percentage_offer_code, user: seller, products: [product], amount_percentage: 20)
upsell = create(:upsell, product:, name: "Complete course", seller:, offer_code:)
upsell_variant = create(:upsell_variant, upsell:, selected_variant: product.alive_variants.first, offered_variant: product.alive_variants.second)
upsell_purchase = create(:upsell_purchase, upsell:, upsell_variant:)
mail = ContactingCreatorMailer.notify(upsell_purchase.purchase.id)
expect(mail.body.encoded).to include "Upsell"
expect(mail.body.encoded).to include "Complete course (20% off)"
expect_push_alert(seller.id, mail.subject)
end
it "includes variant information" do
seller = create(:user, email: "bob@gumroad.com")
product = create(:product_with_digital_versions, user: seller)
variant = product.variant_categories_alive.first.variants.first
purchase = create(:purchase, link: product, email: "ibuy@gumroad.com", variant_attributes: [variant])
mail = ContactingCreatorMailer.notify(purchase.id)
expect(mail.body.encoded).to include "Variant"
expect(mail.body.encoded).to include "(Untitled 1)"
expect_push_alert(seller.id, mail.subject)
end
context "when the product is a membership product" do
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/follower_mailer_spec.rb | spec/mailers/follower_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe FollowerMailer do
describe "#confirm_follower" do
let(:followee) { create(:user) }
let(:unconfirmed_follower) { create(:follower, user: followee) }
it "sends email to follower to confirm the follow" do
mail = FollowerMailer.confirm_follower(followee.id, unconfirmed_follower.id)
expect(mail.from).to eq ["noreply@staging.followers.gumroad.com"]
expect(mail.to).to eq [unconfirmed_follower.email]
expect(mail.subject).to eq("Please confirm your follow request.")
confirm_follow_route = Rails.application.routes.url_helpers.confirm_follow_url(unconfirmed_follower.external_id, host: "#{PROTOCOL}://#{DOMAIN}")
expect(mail.body.encoded).to include confirm_follow_route
end
it "sets the correct SendGrid account" do
stub_const(
"EMAIL_CREDENTIALS",
{
MailerInfo::EMAIL_PROVIDER_SENDGRID => {
followers: {
address: SENDGRID_SMTP_ADDRESS,
username: "apikey",
password: "sendgrid-api-secret",
domain: FOLLOWER_CONFIRMATION_MAIL_DOMAIN,
}
}
}
)
mail = FollowerMailer.confirm_follower(followee.id, unconfirmed_follower.id)
expect(mail.delivery_method.settings[:user_name]).to eq "apikey"
expect(mail.delivery_method.settings[:password]).to eq "sendgrid-api-secret"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/accounting_mailer_spec.rb | spec/mailers/accounting_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe AccountingMailer, :vcr do
describe "#vat_report" do
let(:dummy_s3_link) { "https://test_vat_link.at.s3" }
before do
@mail = AccountingMailer.vat_report(3, 2015, dummy_s3_link)
end
it "has the s3 link in the body" do
expect(@mail.body).to include("VAT report Link: #{dummy_s3_link}")
end
it "indicates the quarter and year of reporting period in the subject" do
expect(@mail.subject).to eq("VAT report for Q3 2015")
end
it "is to team" do
expect(@mail.to).to eq([ApplicationMailer::PAYMENTS_EMAIL])
end
end
describe "#gst_report" do
let(:dummy_s3_link) { "https://test_vat_link.at.s3" }
before do
@mail = AccountingMailer.gst_report("AU", 3, 2015, dummy_s3_link)
end
it "contains the s3 link in the body" do
expect(@mail.body).to include("GST report Link: #{dummy_s3_link}")
end
it "indicates the quarter and year of reporting period in the subject" do
expect(@mail.subject).to eq("Australia GST report for Q3 2015")
end
it "sends to team" do
expect(@mail.to).to eq([ApplicationMailer::PAYMENTS_EMAIL])
end
end
describe "#funds_received_report" do
it "sends and email" do
last_month = Time.current.last_month
email = AccountingMailer.funds_received_report(last_month.month, last_month.year)
expect(email.body.parts.size).to eq(2)
expect(email.body.parts.collect(&:content_type)).to match_array(["text/html; charset=UTF-8", "text/csv; filename=funds-received-report-#{last_month.month}-#{last_month.year}.csv"])
html_body = email.body.parts.find { |part| part.content_type.include?("html") }.body
expect(html_body).to include("Funds Received Report")
expect(html_body).to include("Sales")
expect(html_body).to include("total_transaction_cents")
end
end
describe "#deferred_refunds_report" do
it "sends and email" do
last_month = Time.current.last_month
email = AccountingMailer.deferred_refunds_report(last_month.month, last_month.year)
expect(email.body.parts.size).to eq(2)
expect(email.body.parts.collect(&:content_type)).to match_array(["text/html; charset=UTF-8", "text/csv; filename=deferred-refunds-report-#{last_month.month}-#{last_month.year}.csv"])
html_body = email.body.parts.find { |part| part.content_type.include?("html") }.body
expect(html_body).to include("Deferred Refunds Report")
expect(html_body).to include("Sales")
expect(html_body).to include("total_transaction_cents")
end
end
describe "#stripe_currency_balances_report" do
it "sends an email with balances report attached as csv" do
last_month = Time.current.last_month
balances_csv = "Currency,Balance\nusd,997811.63\n"
email = AccountingMailer.stripe_currency_balances_report(balances_csv)
expect(email.body.parts.size).to eq(2)
expect(email.body.parts.collect(&:content_type)).to match_array(["text/html; charset=UTF-8", "text/csv; filename=stripe_currency_balances_#{last_month.month}_#{last_month.year}.csv"])
html_body = email.body.parts.find { |part| part.content_type.include?("html") }.body
expect(html_body).to include("Stripe currency balances CSV is attached.")
expect(html_body).to include("These are the currency balances for Gumroad's Stripe platform account.")
end
end
describe "email_outstanding_balances_csv" do
before do
# Paypal
create(:balance, amount_cents: 200, user: create(:user))
create(:balance, amount_cents: 300, user: create(:tos_user))
create(:balance, amount_cents: 500, user: create(:tos_user))
# Stripe by Gumroad
bank_account = create(:ach_account_stripe_succeed)
bank_account_for_suspended_user = create(:ach_account_stripe_succeed, user: create(:tos_user))
create(:balance, amount_cents: 400, user: bank_account.user)
create(:balance, amount_cents: 500, user: bank_account.user, date: 1.day.ago)
create(:balance, amount_cents: 500, user: bank_account_for_suspended_user.user)
# Stripe by Creator
merchant_account = create(:merchant_account_stripe, user: create(:user, payment_address: nil))
create(:balance, amount_cents: 400, merchant_account:, user: merchant_account.user)
@mail = AccountingMailer.email_outstanding_balances_csv
end
it "goes to payments and accounting" do
expect(@mail.to).to eq [ApplicationMailer::PAYMENTS_EMAIL]
expect(@mail.cc).to eq %w{solson@earlygrowthfinancialservices.com ndelgado@earlygrowthfinancialservices.com}
end
it "includes the outstanding balance totals" do
expect(@mail.body.encoded).to include "Total Outstanding Balances for Paypal: Active $2.0, Suspended $8.0"
expect(@mail.body.encoded).to include "Total Outstanding Balances for Stripe(Held by Gumroad): Active $9.0"
expect(@mail.body.encoded).to include "Total Outstanding Balances for Stripe(Held by Stripe): Active $4.0"
end
end
describe "ytd_sales_report" do
let(:csv_data) { "country,state,sales\\nUSA,CA,100\\nUSA,NY,200" }
let(:recipient_email) { "test@example.com" }
let(:mail) { AccountingMailer.ytd_sales_report(csv_data, recipient_email) }
it "sends the email to the correct recipient" do
expect(mail.to).to eq([recipient_email])
end
it "has the correct subject" do
expect(mail.subject).to eq("Year-to-Date Sales Report by Country/State")
end
it "attaches the CSV file" do
expect(mail.attachments.length).to eq(1)
attachment = mail.attachments[0]
expect(attachment.filename).to eq("ytd_sales_by_country_state.csv")
expect(attachment.content_type).to eq("text/csv; filename=ytd_sales_by_country_state.csv")
expect(Base64.decode64(attachment.body.encoded)).to eq(csv_data)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/admin_mailer_spec.rb | spec/mailers/admin_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe AdminMailer do
describe "#chargeback_notify" do
context "for a dispute on Purchase" do
let!(:purchase) { create(:purchase) }
let!(:dispute) { create(:dispute_formalized, purchase:) }
let!(:mail) { described_class.chargeback_notify(dispute.id) }
it "emails payments" do
expect(mail.to).to eq [ApplicationMailer::RISK_EMAIL]
end
it "has the id of the seller" do
expect(mail.body).to include(dispute.disputable.seller.id)
end
it "has the details of the purchase" do
expect(mail.subject).to eq "[test] Chargeback for #{purchase.formatted_disputed_amount} on #{purchase.link.name}"
expect(mail.body.encoded).to include purchase.link.name
expect(mail.body.encoded).to include purchase.formatted_disputed_amount
end
end
context "for a dispute on Charge", :vcr do
let!(:charge) do
charge = create(:charge, seller: create(:user), amount_cents: 15_00)
charge.purchases << create(:purchase, link: create(:product, user: charge.seller), total_transaction_cents: 2_50)
charge.purchases << create(:purchase, link: create(:product, user: charge.seller), total_transaction_cents: 5_00)
charge.purchases << create(:purchase, link: create(:product, user: charge.seller), total_transaction_cents: 7_50)
charge
end
let!(:dispute) { create(:dispute_formalized_on_charge, purchase: nil, charge:) }
let!(:mail) { described_class.chargeback_notify(dispute.id) }
it "emails payments" do
expect(mail.to).to eq [ApplicationMailer::RISK_EMAIL]
end
it "has the id of the seller" do
expect(mail.body).to include(dispute.disputable.seller.id)
end
it "has the details of all included purchases" do
selected_purchase = charge.purchase_for_dispute_evidence
expect(mail.subject).to eq "[test] Chargeback for #{charge.formatted_disputed_amount} on #{selected_purchase.link.name} and 2 other products"
charge.disputed_purchases.each do |purchase|
expect(mail.body.encoded).to include purchase.external_id
expect(mail.body.encoded).to include purchase.link.name
end
end
end
end
describe "#low_balance_notify", :sidekiq_inline, :elasticsearch_wait_for_refresh do
before do
@user = create(:user, name: "Test Creator", unpaid_balance_cents: -600_00)
@last_refunded_purchase = create(:purchase)
@mail = AdminMailer.low_balance_notify(@user.id, @last_refunded_purchase.id)
end
it "has 'to' field set to risk@gumroad.com" do
expect(@mail.to).to eq([ApplicationMailer::RISK_EMAIL])
end
it "has the correct subject" do
expect(@mail.subject).to eq "[test] Low balance for creator - Test Creator ($-600)"
end
it "includes user balance in mail body" do
expect(@mail.body).to include("Balance: $-600")
end
it "includes admin purchase link" do
expect(@mail.body).to include(admin_purchase_url(@last_refunded_purchase))
end
it "includes admin product link" do
expect(@mail.body).to include(admin_product_url(@last_refunded_purchase.link.unique_permalink))
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/merchant_registration_mailer_spec.rb | spec/mailers/merchant_registration_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe MerchantRegistrationMailer do
describe "#account_deauthorized_to_user" do
let(:user) { create(:user) }
let(:user_id) { user.id }
let(:charge_processor_id) { StripeChargeProcessor.charge_processor_id }
let(:mail) do
described_class.account_deauthorized_to_user(
user_id,
charge_processor_id
)
end
it do
expect(mail.subject).to(include("Payments account disconnected - #{user.external_id}"))
expect(mail.body.encoded).to(include(charge_processor_id.capitalize))
expect(mail.body.encoded).to(include("Stripe account disconnected"))
expect(mail.body.encoded).to(include(settings_payments_url))
end
it "shows message for unavailable products" do
allow_any_instance_of(User).to receive(:can_publish_products?).and_return(false)
expect(mail.body.encoded).to include("Because both credit cards and PayPal are now turned off for your account," \
" we've disabled your products for sale. You will have to republish them to" \
" enable sales.")
end
end
describe "#account_needs_registration_to_user" do
let(:charge_processor_id) { StripeChargeProcessor.charge_processor_id }
context "for an affiliate" do
let(:affiliate) { create(:direct_affiliate) }
let(:mail) do
described_class.account_needs_registration_to_user(
affiliate.id,
charge_processor_id
)
end
it "advises the affiliate to connect their account" do
expect(mail.body.encoded).to(include("You are an affiliate for a creator that has made recent sales"))
expect(mail.body.encoded).to(include("connected a #{charge_processor_id.capitalize} account"))
end
end
context "for a collaborator" do
let(:collaborator) { create(:collaborator) }
let(:mail) do
described_class.account_needs_registration_to_user(
collaborator.id,
charge_processor_id
)
end
it "advises the collaborator to connect their account" do
expect(mail.body.encoded).to(include("You are a collaborator for a creator that has made recent sales"))
expect(mail.body.encoded).to(include("connected a #{charge_processor_id.capitalize} account"))
end
end
end
describe "stripe_charges_disabled" do
it "alerts the user that payments have been disabled" do
user = create(:user)
mail = described_class.stripe_charges_disabled(user.id)
expect(mail.subject).to eq("Action required: Your sales have stopped")
expect(mail.to).to include(user.email)
expect(mail.from).to eq([ApplicationMailer::NOREPLY_EMAIL])
expect(mail.body.encoded).to include("We have temporarily disabled payments on your account because our payments processor requires more information about you. Since we're subject to their policies, we need to ask you to submit additional documentation.")
expect(mail.body.encoded).to include("To resume sales:")
expect(mail.body.encoded).to include("Submit the required documentation")
expect(mail.body.encoded).to include("We'll review your information")
expect(mail.body.encoded).to include("Once the verification is successful, which takes around one week, we'll immediately start processing your payments again.")
expect(mail.body.encoded).to include("Thank you for your patience and understanding.")
end
end
describe "stripe_payouts_disabled" do
it "notifies the user that their payouts have been paused" do
user = create(:user)
mail = described_class.stripe_payouts_disabled(user.id)
expect(mail.subject).to eq("Action required: Your payouts are paused")
expect(mail.to).to include(user.email)
expect(mail.from).to eq([ApplicationMailer::NOREPLY_EMAIL])
expect(mail.body.encoded).to include("We have temporarily paused payouts on your account because our payments processor requires more information about you.")
expect(mail.body.encoded).to include("To resume payouts:")
expect(mail.body.encoded).to include("Submit the required documentation")
expect(mail.body.encoded).to include("We'll review your information")
expect(mail.body.encoded).to include("Once the verification is successful, we'll immediately start processing your payouts again.")
expect(mail.body.encoded).to include("Thank you for your patience and understanding.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/creator_mailer_spec.rb | spec/mailers/creator_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CreatorMailer do
describe "#gumroad_day_fee_saved" do
it "includes details of fee saved on Gumroad day" do
seller = create(:user, gumroad_day_timezone: "Mumbai")
create(:purchase,
price_cents: 40620,
link: create(:product, user: seller),
created_at: DateTime.new(2024, 4, 4, 12, 0, 0, "+05:30"))
mail = CreatorMailer.gumroad_day_fee_saved(seller_id: seller.id)
expect(mail.subject).to eq("You saved $40.62 in fees on Gumroad Day!")
body = mail.body.encoded
expect(body).to have_text("You saved $40.62 in fees on Gumroad Day!")
expect(body).to have_text("Thanks for being a part of #GumroadDay2024!")
expect(body).to have_text("As a reminder, April 4, 2024 was Gumroad's 13th birthday and we celebrated by lowering Gumroad fees to 0% flat, saving you a total of $40.62 in Gumroad fees.")
expect(body).to have_text("See you next year!")
expect(body).to have_text("Best,")
expect(body).to have_text("Sahil and the Gumroad team")
expect(body).to have_text("PS. View the #GumroadDay2024 hashtag on Twitter and Instagram for inspiration for next year.")
end
end
describe "#bundles_marketing" do
let(:seller) { create(:user) }
let(:bundles) do
[
{
type: Product::BundlesMarketing::BEST_SELLING_BUNDLE,
price: 199_99,
discounted_price: 99_99,
products: [
{ id: 1, url: "https://example.com/product1", name: "Best Seller 1" },
{ id: 2, url: "https://example.com/product2", name: "Best Seller 2" }
]
},
{
type: Product::BundlesMarketing::YEAR_BUNDLE,
price: 299_99,
discounted_price: 149_99,
products: [
{ id: 3, url: "https://example.com/product3", name: "Year Highlight 1" },
{ id: 4, url: "https://example.com/product4", name: "Year Highlight 2" }
]
},
{
type: Product::BundlesMarketing::EVERYTHING_BUNDLE,
price: 499_99,
discounted_price: 249_99,
products: [
{ id: 5, url: "https://example.com/product5", name: "Everything Product 1" },
{ id: 6, url: "https://example.com/product6", name: "Everything Product 2" }
]
}
]
end
it "includes the correct text and product links" do
mail = CreatorMailer.bundles_marketing(seller_id: seller.id, bundles: bundles)
expect(mail.subject).to eq("Join top creators who have sold over $300,000 of bundles")
body = mail.body.encoded
expect(body).to have_text("We've put together some awesome bundles of your top products - they're ready and waiting for you. Gumroad creators have already made over $300,000 selling bundles. Launch your bundles now with just a few clicks!")
expect(body).to have_text("Best Selling Bundle")
expect(body).to have_link("Best Seller 1", href: "https://example.com/product1")
expect(body).to have_link("Best Seller 2", href: "https://example.com/product2")
expect(body).to have_text("$199.99")
expect(body).to have_text("$99.99")
expect(body).to have_link("Edit and launch", href: create_from_email_bundles_url(type: Product::BundlesMarketing::BEST_SELLING_BUNDLE, price: 99_99, products: [1, 2]))
expect(body).to have_text("#{1.year.ago.year} Bundle")
expect(body).to have_link("Year Highlight 1", href: "https://example.com/product3")
expect(body).to have_link("Year Highlight 2", href: "https://example.com/product4")
expect(body).to have_text("$299.99")
expect(body).to have_text("$149.99")
expect(body).to have_link("Edit and launch", href: create_from_email_bundles_url(type: Product::BundlesMarketing::YEAR_BUNDLE, price: 149_99, products: [3, 4]))
expect(body).to have_text("Everything Bundle")
expect(body).to have_link("Everything Product 1", href: "https://example.com/product5")
expect(body).to have_link("Everything Product 2", href: "https://example.com/product6")
expect(body).to have_text("$499.99")
expect(body).to have_text("$249.99")
expect(body).to have_link("Edit and launch", href: create_from_email_bundles_url(type: Product::BundlesMarketing::EVERYTHING_BUNDLE, price: 249_99, products: [5, 6]))
end
end
describe "#year_in_review" do
let(:seller) { create(:user) }
let(:year) { 2024 }
let(:analytics_data) do
{
total_views_count: 144,
total_sales_count: 12,
top_selling_products: seller&.products&.last(5)&.map do |product|
ProductPresenter.card_for_email(product:).merge(
{
stats: [
rand(1000..5000),
rand(10000..50000),
rand(100000..500000000),
]
}
)
end,
total_products_sold_count: 5,
total_amount_cents: 5000,
by_country: ["🇪🇸 Spain", "🇷🇴 Romania", "🇦🇪 United Arab Emirates", "🇺🇸 United States", "🌎 Elsewhere"].index_with do
[
5,
1_500,
10,
]
end.sort_by { |_, (_, _, total)| -total },
total_countries_with_sales_count: 5,
total_unique_customers_count: 8
}
end
context "when the seller is earning in USD" do
it "includes the correct text and product links" do
mail = CreatorMailer.year_in_review(seller:, year:, analytics_data:)
expect(mail.subject).to eq("Your 2024 in review")
body = mail.body.encoded
expect(body).to have_text("Your year on Gumroad in review")
expect(body).to have_text("You sold products in 5 countries")
expect(body).to have_text("Sales 12", normalize_ws: true)
expect(body).to have_text("Views 144", normalize_ws: true)
expect(body).to have_text("Unique customers 8", normalize_ws: true)
expect(body).to have_text("Products sold 5", normalize_ws: true)
expect(body).to have_text("United States 5 1.5K $10", normalize_ws: true)
expect(body).to have_text("Spain 5 1.5K $10", normalize_ws: true)
expect(body).to have_text("Romania 5 1.5K $10", normalize_ws: true)
expect(body).to have_text("United Arab Emirates 5 1.5K $10", normalize_ws: true)
expect(body).to have_text("Elsewhere 5 1.5K $10", normalize_ws: true)
expect(body).to have_text("You earned a total of $50", normalize_ws: true)
end
end
context "when the seller is earning in GBP" do
before do
seller.update!(currency_type: "gbp")
end
it "converts the total amount to GBP" do
mail = CreatorMailer.year_in_review(seller:, year:, analytics_data:)
expect(mail.subject).to eq("Your 2024 in review")
body = mail.body.encoded
expect(body).to have_text("United States 5 1.5K £6.5", normalize_ws: true)
expect(body).to have_text("Spain 5 1.5K £6.5", normalize_ws: true)
expect(body).to have_text("Romania 5 1.5K £6.5", normalize_ws: true)
expect(body).to have_text("United Arab Emirates 5 1.5K £6.5", normalize_ws: true)
expect(body).to have_text("Elsewhere 5 1.5K £6.5", normalize_ws: true)
expect(body).to have_text("You earned a total of £32", normalize_ws: true)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/customer_low_priority_mailer_spec.rb | spec/mailers/customer_low_priority_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CustomerLowPriorityMailer do
describe "subscription_autocancelled" do
context "memberships" do
before do
@product = create(:subscription_product, name: "fan club")
@subscription = create(:subscription, link: @product)
@purchase = create(:purchase, is_original_subscription_purchase: true, link: @product, subscription: @subscription)
end
it "notifies user of subscription cancellation" do
mail = CustomerLowPriorityMailer.subscription_autocancelled(@subscription.id)
expect(mail.subject).to eq "Your subscription has been canceled."
expect(mail.body.encoded).to match("Your subscription to fan club has been automatically canceled due to multiple failed payments")
end
it "sets the correct SendGrid account with creator's mailer_level" do
stub_const(
"EMAIL_CREDENTIALS",
{
MailerInfo::EMAIL_PROVIDER_SENDGRID => {
customers: {
levels: {
level_1: {
address: SENDGRID_SMTP_ADDRESS,
username: "apiKey_for_level_1",
password: "sendgrid-api-secret",
domain: CUSTOMERS_MAIL_DOMAIN,
}
}
}
}
}
)
mail = CustomerLowPriorityMailer.subscription_autocancelled(@subscription.id)
expect(mail.delivery_method.settings[:user_name]).to eq "apiKey_for_level_1"
expect(mail.delivery_method.settings[:password]).to eq "sendgrid-api-secret"
end
end
context "installment plans" do
let(:installment_plan_purchase) { create(:installment_plan_purchase) }
let(:subscription) { installment_plan_purchase.subscription }
it "notifies user of installment plan pause" do
mail = CustomerLowPriorityMailer.subscription_autocancelled(subscription.id)
expect(mail.subject).to eq "Your installment plan has been paused."
expect(mail.body.encoded).to include("your installment plan for #{subscription.link.name} has been paused")
end
end
end
describe "subscription_cancelled" do
before do
@product = create(:membership_product, name: "fan club", subscription_duration: "monthly")
end
it "confirms with user that they meant to cancel their subscription" do
subscription = create(:subscription, link: @product)
create(:purchase, is_original_subscription_purchase: true, link: @product, subscription:)
mail = CustomerLowPriorityMailer.subscription_cancelled(subscription.id)
expect(mail.body.encoded).to match(/You have canceled your subscription to fan club\. You will .* your billing cycle/)
end
end
describe "subscription_cancelled_by_seller" do
context "memberships" do
before do
@product = create(:membership_product, name: "fan club", subscription_duration: "monthly")
@subscription = create(:subscription, link: @product)
@purchase = create(:purchase, is_original_subscription_purchase: true, link: @product, subscription: @subscription)
end
it "notifies customer that seller cancelled their subscription" do
mail = CustomerLowPriorityMailer.subscription_cancelled_by_seller(@subscription.id)
expect(mail.subject).to eq "Your subscription has been canceled."
expect(mail.body.encoded).to match(/Your subscription to fan club has been canceled by the creator\. You will .* your billing cycle/)
end
end
context "installment plans" do
let(:installment_plan_purchase) { create(:installment_plan_purchase) }
let(:subscription) { installment_plan_purchase.subscription }
it "notifies customer that seller cancelled their installment plan" do
mail = CustomerLowPriorityMailer.subscription_cancelled_by_seller(subscription.id)
expect(mail.subject).to eq "Your installment plan has been canceled."
expect(mail.body.encoded).to match(/Your installment plan for #{subscription.link.name} has been canceled by the creator/)
end
end
end
describe "subscription_card_declined" do
it "lets user know their card was declined" do
subscription = create(:subscription, link: create(:product))
create(:purchase, is_original_subscription_purchase: true, link: subscription.link, subscription:)
mail = CustomerLowPriorityMailer.subscription_card_declined(subscription.id)
expect(mail.subject).to eq "Your card was declined."
expect(mail.body.encoded).to include subscription.link.name
expect(mail.body.encoded).to include "/subscriptions/#{subscription.external_id}/manage?declined=true&token=#{subscription.reload.token}"
end
end
describe "subscription_card_declined_warning" do
it "reminds user their card was declined" do
subscription = create(:subscription, link: create(:product))
create(:purchase, is_original_subscription_purchase: true, link: subscription.link, subscription:)
mail = CustomerLowPriorityMailer.subscription_card_declined_warning(subscription.id)
expect(mail.subject).to eq "Your card was declined."
expect(mail.body.encoded).to include subscription.link.name
expect(mail.body.encoded).to include "This is a reminder"
expect(mail.body.encoded).to include "/subscriptions/#{subscription.external_id}/manage?declined=true&token=#{subscription.reload.token}"
end
end
describe "subscription_renewal_reminder" do
context "memberships" do
it "reminds the user they will be charged for their subscription soon", :vcr do
purchase = create(:membership_purchase)
subscription = purchase.subscription
mail = CustomerLowPriorityMailer.subscription_renewal_reminder(subscription.id)
expect(mail.subject).to eq "Upcoming automatic membership renewal"
expect(mail.body.encoded).to include "This is a reminder that your membership to \"#{purchase.link.name}\" will automatically renew on"
expect(mail.body.encoded).to include "You're paying"
expect(mail.body.encoded).to include "Questions about your product?"
expect(mail.reply_to).to eq [purchase.link.user.email]
end
end
context "installment plans" do
let(:installment_plan_purchase) { create(:installment_plan_purchase) }
let(:subscription) { installment_plan_purchase.subscription }
it "reminds the user they will be charged for their installment payment soon" do
mail = CustomerLowPriorityMailer.subscription_renewal_reminder(subscription.id)
expect(mail.subject).to eq "Upcoming installment payment reminder"
expect(mail.body.encoded).to include "This is a reminder that your next installment payment"
expect(mail.reply_to).to eq [subscription.link.user.email]
end
end
end
describe "subscription_price_change_notification" do
let(:purchase) { create(:membership_purchase, price_cents: 5_00) }
let(:subscription) { purchase.subscription }
let(:tier) { purchase.tier }
let(:new_price) { purchase.displayed_price_cents + 4_99 }
let(:effective_date) { 1.month.from_now.to_date }
before do
tier.update!(apply_price_changes_to_existing_memberships: true, subscription_price_change_effective_date: effective_date)
tier.prices.find_by(recurrence: "monthly").update!(price_cents: new_price)
end
it "notifies the subscriber the price will be changing soon" do
mail = CustomerLowPriorityMailer.subscription_price_change_notification(subscription_id: subscription.id, new_price:)
expect(mail.subject).to eq "Important changes to your membership"
expect(mail.body.encoded).to include "The price of your membership to \"#{purchase.link.name}\" is changing on #{effective_date.strftime("%B %e, %Y")}."
expect(mail.body.encoded).to include "$5 a month"
expect(mail.body.encoded).to include "$9.99 a month"
expect(mail.body.encoded).to include subscription.end_time_of_subscription.strftime("%B %e, %Y")
expect(mail.body.encoded).not_to include "plus taxes"
end
it "includes tax details if applicable" do
purchase.update!(was_purchase_taxable: true)
mail = CustomerLowPriorityMailer.subscription_price_change_notification(subscription_id: subscription.id, new_price:)
expect(mail.body.encoded).to include "$5 a month (plus taxes)"
expect(mail.body.encoded).to include "$9.99 a month (plus taxes)"
end
it "includes custom message if set" do
tier.update!(subscription_price_change_message: "<p>hi!</p>")
mail = CustomerLowPriorityMailer.subscription_price_change_notification(subscription_id: subscription.id, new_price:)
expect(mail.body.encoded).to include "hi!"
expect(mail.body.encoded).not_to include "The price of your membership"
end
it "uses the correct tense if effective date is in the past" do
travel_to effective_date + 1.day
mail = CustomerLowPriorityMailer.subscription_price_change_notification(subscription_id: subscription.id, new_price:)
expect(mail.body.encoded).to include "The price of your membership to \"#{purchase.link.name}\" changed on #{effective_date.to_date.strftime("%B %e, %Y")}."
expect(mail.body.encoded).to include "You will be charged the new price starting with your next billing period."
end
end
describe "chargeback_notice_to_customer" do
let(:seller) { create(:user) }
context "for a dispute on Purchase" do
let(:product) { create(:product, user: seller) }
let!(:purchase) { create(:purchase, seller:, link: product) }
let(:dispute) { create(:dispute_formalized, purchase:) }
it "has the correct text" do
mail = CustomerLowPriorityMailer.chargeback_notice_to_customer(dispute.id)
expect(mail.subject).to eq "Regarding your recent dispute."
expect(mail.body.encoded).to include "You recently filed a dispute for your purchase of "\
"<a href=\"#{product.long_url}\">#{product.name}</a> for #{purchase.formatted_disputed_amount}. " \
"A receipt was sent to #{purchase.email} — please check your Spam folder if you are unable to locate it."
expect(mail.body.encoded).to include "If you filed this dispute because you didn't recognize \"Gumroad\" on your account statement, " \
"you can contact your bank or PayPal to cancel the dispute."
end
end
context "for a dispute on Charge" do
let(:charge) do
charge = create(:charge, seller:)
charge.purchases << create(:purchase, seller:, link: create(:product, user: seller))
charge.purchases << create(:purchase, seller:, link: create(:product, user: seller))
charge.purchases << create(:purchase, seller:, link: create(:product, user: seller))
charge
end
let(:dispute) { create(:dispute_formalized_on_charge, purchase: nil, charge:) }
it "has the correct text" do
mail = CustomerLowPriorityMailer.chargeback_notice_to_customer(dispute.id)
expect(mail.subject).to eq "Regarding your recent dispute."
expect(mail.body.encoded).to include "You recently filed a dispute for your purchase of "\
"the following items for #{charge.formatted_disputed_amount}. " \
"A receipt was sent to #{charge.customer_email} — please check your Spam folder if you are unable to locate it."
expect(mail.body.encoded).to include "If you filed this dispute because you didn't recognize \"Gumroad\" on your account statement, " \
"you can contact your bank or PayPal to cancel the dispute."
end
end
end
describe "sample_subscription_price_change_notification" do
let(:effective_date) { 1.month.from_now.to_date }
let(:product) { create(:membership_product) }
let(:tier) { product.default_tier }
it "sends the user a sample price change notification" do
mail = CustomerLowPriorityMailer.sample_subscription_price_change_notification(user: product.user, tier:, effective_date:, recurrence: "yearly", new_price: 20_00)
expect(mail.subject).to eq "Important changes to your membership"
expect(mail.body.encoded).to include "The price of your membership to \"#{product.name}\" is changing on #{effective_date.strftime("%B %e, %Y")}."
expect(mail.body.encoded).to include "$16 a year"
expect(mail.body.encoded).to include "$20 a year"
expect(mail.body.encoded).to include (effective_date + 4.days).to_date.strftime("%B %e, %Y")
expect(mail.body.encoded).not_to include "plus taxes"
end
it "includes a custom message, if present" do
mail = CustomerLowPriorityMailer.sample_subscription_price_change_notification(user: product.user, tier:, effective_date:, recurrence: "yearly", new_price: 20_00, custom_message: "<p>hi!</p>")
expect(mail.body.encoded).to include "hi!"
expect(mail.body.encoded).not_to include "The price of your membership"
end
it "includes the charge count for a fixed-length membership" do
product.update!(duration_in_months: 12)
tier.reload
mail = CustomerLowPriorityMailer.sample_subscription_price_change_notification(user: product.user, tier:, effective_date:, recurrence: "monthly", new_price: 20_00)
expect(mail.body.encoded).to include "$16 a month x 12"
expect(mail.body.encoded).to include "$20 a month x 12"
end
end
describe "subscription_charge_failed" do
context "memberships" do
it "notifies the customer their charge failed" do
subscription = create(:subscription, link: create(:product))
create(:purchase, is_original_subscription_purchase: true, link: subscription.link, subscription:)
mail = CustomerLowPriorityMailer.subscription_charge_failed(subscription.id)
expect(mail.subject).to eq "Your recurring charge failed."
expect(mail.body.encoded).to include subscription.link.name
end
end
context "installment plans" do
let(:installment_plan_purchase) { create(:installment_plan_purchase) }
let(:subscription) { installment_plan_purchase.subscription }
it "notifies the customer their installment payment failed" do
mail = CustomerLowPriorityMailer.subscription_charge_failed(subscription.id)
expect(mail.subject).to eq "Your installment payment failed."
expect(mail.body.encoded).to include subscription.link.name
end
end
end
describe "subscription_ended" do
context "memberships" do
before do
@product = create(:membership_product, name: "fan club", subscription_duration: "monthly", duration_in_months: 6)
end
it "confirms with user that they meant to cancel their subscription" do
subscription = create(:subscription, link: @product, charge_occurrence_count: 6)
create(:purchase, is_original_subscription_purchase: true, link: @product, subscription:)
mail = CustomerLowPriorityMailer.subscription_ended(subscription.id)
expect(mail.subject).to eq "Your subscription has ended."
expect(mail.body.encoded).to match(/subscription to fan club has ended. You will no longer be charged/)
end
it "has the correct text for a membership ending" do
@product.block_access_after_membership_cancellation = true
@product.save
subscription = create(:subscription, link: @product, charge_occurrence_count: 6)
create(:purchase, is_original_subscription_purchase: true, link: @product, subscription:)
mail = CustomerLowPriorityMailer.subscription_ended(subscription.id)
expect(mail.body.encoded).to match(/subscription to fan club has ended. You will no longer be charged/)
end
end
context "installment plans" do
let(:installment_plan_purchase) { create(:installment_plan_purchase) }
let(:subscription) { installment_plan_purchase.subscription }
it "notifies the customer their installment plan has been paid in full" do
mail = CustomerLowPriorityMailer.subscription_ended(subscription.id)
expect(mail.subject).to eq "Your installment plan has been paid in full."
expect(mail.body.encoded).to include "You have completed all your installment payments for #{subscription.link.name}"
end
end
end
describe "#subscription_early_fraud_warning_notification" do
let(:purchase) do
create(
:membership_purchase,
email: "buyer@example.com",
price_cents: 500,
created_at: Date.parse("Nov 20, 2023")
)
end
before do
purchase.subscription.user.update!(email: "buyer@example.com")
end
it "notifies the buyer" do
mail = CustomerLowPriorityMailer.subscription_early_fraud_warning_notification(purchase.id)
expect(mail.subject).to eq "Regarding your recent purchase reported as fraud"
expect(mail.to).to eq ["buyer@example.com"]
expect(mail.reply_to).to eq [purchase.link.user.email]
expect(mail.body.encoded).to include "You recently reported as fraud the transaction for your purchase"
expect(mail.body.encoded).to include "A receipt was sent to buyer@example.com — please check your Spam folder if you are unable to locate it"
expect(mail.body.encoded).to include "Manage membership"
end
end
describe "#subscription_giftee_added_card", vcr: true do
let(:gift) { create(:gift, gift_note: "Gift note", giftee_email: "giftee@example.com") }
let(:product) { create(:membership_product) }
let(:subscription) { create(:subscription, link: product, user: nil, credit_card: create(:credit_card)) }
let!(:original_purchase) { create(:membership_purchase, gift_given: gift, is_gift_sender_purchase: true, is_original_subscription_purchase: true, subscription:) }
let!(:purchase) { create(:membership_purchase, gift_received: gift, is_gift_receiver_purchase: true, is_original_subscription_purchase: false, subscription:) }
it "notifies the giftee" do
mail = CustomerLowPriorityMailer.subscription_giftee_added_card(subscription.id)
expect(mail.subject).to eq "You've added a payment method to your membership"
expect(mail.to).to eq ["giftee@example.com"]
expect(mail.body.sanitized).to include product.name
expect(mail.body.sanitized).to include "You will be charged once a month. If you would like to manage your membership you can visit"
expect(mail.body.sanitized).to include "First payment #{subscription.formatted_end_time_of_subscription}"
expect(mail.body.sanitized).to include "Payment method VISA *4242"
end
end
describe "order_shipped" do
before do
@seller = create(:user, name: "Edgar")
@product = create(:physical_product, user: @seller)
@purchase = create(:physical_purchase, link: @product)
end
describe "without tracking" do
before do
@shipment = create(:shipment, purchase: @purchase, ship_state: :shipped)
end
it "mails to and reply-to the correct email" do
mail = CustomerLowPriorityMailer.order_shipped(@shipment.id)
expect(mail.to).to eq [@purchase.email]
expect(mail.reply_to).to eq [@product.user.email]
end
it "has correct subject" do
mail = CustomerLowPriorityMailer.order_shipped(@shipment.id)
expect(mail.subject).to eq "Your order has shipped!"
end
it "has the link name in the body" do
mail = CustomerLowPriorityMailer.order_shipped(@shipment.id)
expect(mail.body.encoded).to include @product.name
end
end
describe "with tracking" do
before do
@shipment = create(:shipment, purchase: @purchase, ship_state: :shipped, tracking_url: "https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=1234567890")
end
it "mails to and reply-to the correct email" do
mail = CustomerLowPriorityMailer.order_shipped(@shipment.id)
expect(mail.to).to eq [@purchase.email]
expect(mail.reply_to).to eq [@product.user.email]
end
it "has correct subject" do
mail = CustomerLowPriorityMailer.order_shipped(@shipment.id)
expect(mail.subject).to eq "Your order has shipped!"
end
it "has the correct link name in the body" do
mail = CustomerLowPriorityMailer.order_shipped(@shipment.id)
expect(mail.body.encoded).to include @product.name
end
it "has the tracking url in the body" do
mail = CustomerLowPriorityMailer.order_shipped(@shipment.id)
expect(mail.body.encoded).to include @shipment.tracking_url
end
end
end
describe "free_trial_expiring_soon" do
it "notifies the customer that their free trial is expiring soon" do
purchase = create(:free_trial_membership_purchase)
mail = CustomerLowPriorityMailer.free_trial_expiring_soon(purchase.subscription_id)
expect(mail.subject).to eq "Your free trial is ending soon"
expect(mail.body.encoded).to include "Your free trial to #{purchase.link.name} is expiring on #{purchase.subscription.free_trial_end_date_formatted}, at which point you will be charged. If you wish to cancel your membership, you can do so at any time"
expect(mail.body.encoded).to include "/subscriptions/#{purchase.subscription.external_id}/manage?token=#{purchase.subscription.reload.token}"
end
end
describe "expiring credit card membership", :vcr do
it "notifies the customer that their credit card is expiring" do
expiring_cc_user = create(:user, credit_card: create(:credit_card))
subscription = create(:subscription, user: expiring_cc_user, credit_card_id: expiring_cc_user.credit_card_id)
create(:purchase, is_original_subscription_purchase: true, subscription:)
mail = CustomerLowPriorityMailer.credit_card_expiring_membership(subscription.id)
expect(mail.subject).to eq "Payment method for #{subscription.link.name} is about to expire"
expect(mail.body.encoded).to include "To continue your <strong>#{subscription.link.name}</strong> subscription, please update your card information."
end
end
describe "preorder_card_declined" do
it "notifies the customer that the preorder charge was declined" do
product = create(:product)
preorder_link = create(:preorder_link, link: product)
preorder = preorder_link.build_preorder(create(:preorder_authorization_purchase, link: product))
preorder.save!
mail = CustomerLowPriorityMailer.preorder_card_declined(preorder.id)
expect(mail.subject).to eq "Could not charge your credit card for #{product.name}"
expect(mail.body.encoded).to include preorder.link.name
expect(mail.body.encoded).to have_link("here", href: preorder.link.long_url)
end
end
describe "#bundle_content_updated" do
let(:purchase) { create(:purchase) }
before { purchase.seller.update!(name: "Seller") }
it "notifies the customer that the bundle content has been updated" do
mail = CustomerLowPriorityMailer.bundle_content_updated(purchase.id)
expect(mail.subject).to eq "Seller just added content to The Works of Edgar Gumstein"
expect(mail.body.encoded).to have_text("Seller just added content to The Works of Edgar Gumstein")
expect(mail.body.encoded).to have_text("Get excited! Seller just added new content to The Works of Edgar Gumstein. You can access it by visiting your library or clicking the button below.")
expect(mail.body.encoded).to have_link("View content", href: library_url({ bundles: purchase.link.external_id }))
end
end
describe "#purchase_review_reminder" do
let(:purchase) { create(:purchase, full_name: "Buyer") }
context "purchase does not have review" do
it "sends an email" do
mail = CustomerLowPriorityMailer.purchase_review_reminder(purchase.id)
expect(mail.subject).to eq("Liked The Works of Edgar Gumstein? Give it a review!")
expect(mail.body.encoded).to have_text("Liked The Works of Edgar Gumstein? Give it a review!")
expect(mail.body.encoded).to have_text("Hi Buyer,")
expect(mail.body.encoded).to have_text("Hope you're getting great value from #{purchase.link.name}.")
expect(mail.body.encoded).to have_text("We'd love to hear your thoughts on it. When you have a moment, could you drop us a quick review?")
expect(mail.body.encoded).to have_text("Thank you for your contribution!")
expect(mail.body.encoded).to have_link("Leave a review", href: purchase.link.long_url)
expect(mail.body.encoded).not_to have_link("Unsubscribe")
end
context "purchase does not have name" do
before { purchase.update!(full_name: nil) }
context "purchaser's account has name" do
before { purchase.update!(purchaser: create(:user, name: "Purchaser")) }
it "uses the purchaser's account name" do
expect(CustomerLowPriorityMailer.purchase_review_reminder(purchase.id).body.encoded).to have_text("Hi Purchaser,")
end
end
context "purchaser's account does not has name" do
it "excludes the name" do
expect(CustomerLowPriorityMailer.purchase_review_reminder(purchase.id).body.encoded).to have_text("Hi,")
end
end
end
context "purchase has a UrlRedirect" do
before { purchase.create_url_redirect! }
it "uses the download page URL" do
mail = CustomerLowPriorityMailer.purchase_review_reminder(purchase.id)
expect(mail.body.encoded).to have_link("Leave a review", href: purchase.url_redirect.download_page_url)
end
end
context "purchaser has an account" do
before { purchase.update!(purchaser: create(:user, name: "Purchaser")) }
it "includes unsubscribe link" do
expect(CustomerLowPriorityMailer.purchase_review_reminder(purchase.id).body.encoded).to have_link("Unsubscribe", href: user_unsubscribe_review_reminders_url)
end
end
end
context "purchase has review" do
before { purchase.create_product_review }
it "does not send an email" do
expect do
CustomerLowPriorityMailer.purchase_review_reminder(purchase.id)
end.to_not change { ActionMailer::Base.deliveries.count }
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
CustomerLowPriorityMailer.purchase_review_reminder(purchase.id)
end.to_not change { ActionMailer::Base.deliveries.count }
end
end
context "bundle purchase" do
before { purchase.update!(is_bundle_purchase: true) }
it "uses the library bundle URL" do
mail = CustomerLowPriorityMailer.purchase_review_reminder(purchase.id)
expect(mail.body.encoded).to have_link("Leave a review", href: library_url(bundles: purchase.link.external_id))
end
end
context "bundle product purchase" do
before { purchase.update!(is_bundle_product_purchase: true) }
it "does not send an email" do
expect do
CustomerLowPriorityMailer.purchase_review_reminder(purchase.id)
end.to_not change { ActionMailer::Base.deliveries.count }
end
end
end
describe "#order_review_reminder" do
let(:purchase) { create(:purchase, full_name: "Buyer") }
let(:order) { create(:order, purchases: [purchase]) }
it "sends an email" do
mail = CustomerLowPriorityMailer.order_review_reminder(order.id)
expect(mail.subject).to eq("Liked your order? Leave some reviews!")
expect(mail.body.encoded).to have_text("Liked your order? Leave some reviews!")
expect(mail.body.encoded).to have_text("Hi Buyer,")
expect(mail.body.encoded).to have_text("Hope you're getting great value from your order.")
expect(mail.body.encoded).to have_text("We'd love to hear your thoughts on it. When you have a moment, could you drop us some reviews?")
expect(mail.body.encoded).to have_text("Thank you for your contribution!")
expect(mail.body.encoded).to have_link("Leave reviews", href: reviews_url)
expect(mail.body.encoded).to have_link("Unsubscribe")
end
context "purchase does not have name" do
before { purchase.update!(full_name: nil) }
context "purchaser's account has name" do
before { order.update!(purchaser: create(:user, name: "Purchaser")) }
it "uses the purchaser's account name" do
expect(CustomerLowPriorityMailer.order_review_reminder(order.id).body.encoded).to have_text("Hi Purchaser,")
end
end
context "purchaser's account does not has name" do
it "excludes the name" do
expect(CustomerLowPriorityMailer.order_review_reminder(order.id).body.encoded).to have_text("Hi,")
end
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
CustomerLowPriorityMailer.order_review_reminder(order.id)
end.to_not change { ActionMailer::Base.deliveries.count }
end
end
end
describe "#wishlist_updated" do
let(:wishlist) { create(:wishlist, user: create(:user, name: "Wishlist Creator")) }
let!(:wishlist_product) { create(:wishlist_product, wishlist:) }
let(:wishlist_follower) { create(:wishlist_follower, wishlist:) }
it "sends an email" do
mail = CustomerLowPriorityMailer.wishlist_updated(wishlist_follower.id, 1)
expect(mail.subject).to eq("Wishlist Creator recently added a new product to their wishlist!")
expect(mail.body.encoded).to have_text("Wishlist Creator recently added a new product to their wishlist!")
expect(mail.body.encoded).to have_image(src: wishlist_product.product.for_email_thumbnail_url)
expect(mail.body.encoded).to have_link(wishlist.name, href: wishlist_url(wishlist.url_slug, host: wishlist.user.subdomain_with_protocol))
expect(mail.body.encoded).to have_link("View content", href: wishlist_url(wishlist.url_slug, host: wishlist.user.subdomain_with_protocol))
expect(mail.body.encoded).to have_link("Unsubscribe", href: unsubscribe_wishlist_followers_url(wishlist.url_slug, follower_id: wishlist_follower.external_id))
end
context "when the follower has just unsubscribed" do
before { wishlist_follower.mark_deleted! }
it "does not send an email" do
expect do
CustomerLowPriorityMailer.wishlist_updated(wishlist_follower.id, 1)
end.to_not change { ActionMailer::Base.deliveries.count }
end
end
end
describe "subscription_product_deleted" do
context "memberships" do
let(:purchase) { create(:membership_purchase) }
let(:subscription) { purchase.subscription }
let(:product) { subscription.link }
it "notifies the customer their subscription has been canceled" do
mail = CustomerLowPriorityMailer.subscription_product_deleted(subscription.id)
expect(mail.subject).to eq "Your subscription has been canceled."
expect(mail.body.encoded).to include "Your subscription to #{product.name} has been canceled"
expect(mail.body.encoded).to include "due to the creator deleting the product"
end
end
context "installment plans" do
let(:installment_plan_purchase) { create(:installment_plan_purchase) }
let(:subscription) { installment_plan_purchase.subscription }
let(:product) { subscription.link }
it "notifies the customer their installment plan has been canceled" do
mail = CustomerLowPriorityMailer.subscription_product_deleted(subscription.id)
expect(mail.subject).to eq "Your installment plan has been canceled."
expect(mail.body.encoded).to include "Your installment plan for #{product.name} has been canceled"
expect(mail.body.encoded).to include "due to the creator deleting the product"
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/customer_mailer_spec.rb | spec/mailers/customer_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CustomerMailer do
describe "receipt" do
subject(:mail) do
user = create(:user, email: "bob@gumroad.com", name: "bob walsh")
link = create(:product, user:)
@purchase = create(:purchase, link:, seller: link.user, email: "to@example.org")
@purchase.create_url_redirect!
user_2 = create(:user, email: "bobby@gumroad.com")
link_2 = create(:product, user: user_2)
@purchase_2 = create(:purchase, link: link_2, seller: link_2.user)
@purchase_2.create_url_redirect!
CustomerMailer.receipt(@purchase.id)
end
it "renders the headers for a receipt" do
expect(mail.subject).to eq "You bought #{@purchase.link.name}!"
expect(mail.to).to eq(["to@example.org"])
expect(mail[:from].value).to eq("#{@purchase.link.user.name} <noreply@#{CUSTOMERS_MAIL_DOMAIN}>")
expect(mail[:reply_to].value).to eq("bob@gumroad.com")
end
context "when support email exists" do
subject(:mail) do
user = create(:user, email: "bob@gumroad.com", name: "bob walsh")
link = create(:product, user:, support_email: "support@example.com")
@purchase = create(:purchase, link:, seller: link.user, email: "to@example.org")
@purchase.create_url_redirect!
CustomerMailer.receipt(@purchase.id)
end
it "uses correct support email" do
expect(mail[:reply_to].value).to eq("support@example.com")
end
end
it "renders the headers with UrlRedirect" do
user = create(:user, email: "bob@gumroad.com", name: "bob walsh, LLC")
link = create(:product, user:)
purchase = create(:purchase, link:, seller: link.user)
purchase.create_url_redirect!
mail = CustomerMailer.receipt(purchase.id)
expect(mail[:from].value).to eq("\"#{user.name}\" <noreply@#{CUSTOMERS_MAIL_DOMAIN}>")
expect(mail[:reply_to].value).to eq("bob@gumroad.com")
end
context "when user name contains special characters" do
before do
@user = create(:user)
@product = create(:product, user: @user)
@purchase = create(:purchase, link: @product, seller: @product.user)
@purchase.create_url_redirect!
end
context "with Spanish letters" do
it "sets the FROM name to the creator's name" do
@user.update!(name: "Juan Girão")
mail = CustomerMailer.receipt(@purchase.id)
expect(mail.header.to_s).to include(Mail::Address.new("#{@user.name} <noreply@staging.customers.gumroad.com>").encoded)
end
context "and symbols" do
it "sets the FROM name to 'Gumroad'" do
@user.update!(name: "Juan Girão @ Gumroad")
mail = CustomerMailer.receipt(@purchase.id)
expect(mail.header.to_s).to include("From: Gumroad <noreply@staging.customers.gumroad.com>")
end
end
end
context "with Romanian letters" do
it "sets the FROM name to the creator's name" do
@user.update!(name: "Ștefan Opriță")
mail = CustomerMailer.receipt(@purchase.id)
expect(mail.header.to_s).to include(Mail::Address.new("#{@user.name} <noreply@staging.customers.gumroad.com>").encoded)
end
context "and symbols" do
it "sets the FROM name to 'Gumroad'" do
@user.update!(name: "Ștefan Opriță @ Gumroad")
mail = CustomerMailer.receipt(@purchase.id)
expect(mail.header.to_s).to include("From: Gumroad <noreply@staging.customers.gumroad.com>")
end
end
end
context "with Asian letters" do
it "sets the FROM name to the creator's name" do
@user.update!(name: "ゆうさん")
mail = CustomerMailer.receipt(@purchase.id)
expect(mail.header.to_s).to include(Mail::Address.new("#{@user.name} <noreply@staging.customers.gumroad.com>").encoded)
end
context "and symbols" do
it "sets the FROM name to the creator's name" do
@user.update!(name: "ゆうさん @ Gumroad")
mail = CustomerMailer.receipt(@purchase.id)
expect(mail.header.to_s).to include(Mail::Address.new("#{@user.name} <noreply@staging.customers.gumroad.com>").encoded)
end
end
end
context "with ASCII symbols" do
it "wraps creator name in quotes" do
@user.update!(name: "Gumbot @ Gumroad")
mail = CustomerMailer.receipt(@purchase.id)
expect(mail.header.to_s).to include("From: \"Gumbot @ Gumroad\" <noreply@staging.customers.gumroad.com>")
end
end
context "with new line characters and leading blank spaces" do
it "deletes the new lines and strips whitespaces from the creator name" do
@user.update!(name: " \nGumbot\n Generalist @ Gumroad ")
mail = CustomerMailer.receipt(@purchase.id)
expect(mail.header.to_s).to include("From: \"Gumbot Generalist @ Gumroad\" <noreply@staging.customers.gumroad.com>")
end
end
end
it "has no-reply when creator uses messaging" do
product = create(:product, user: create(:user))
mail = CustomerMailer.receipt(create(:purchase, link: product).id)
expect(mail[:from].value).to match("noreply@#{CUSTOMERS_MAIL_DOMAIN}")
end
it "renders the body" do
expect(mail.body.sanitized).to match(@purchase.link_name)
expect(mail.body.sanitized).to have_text(
"All charges are processed in United States Dollars. " +
"Your bank or financial institution may apply their own fees for currency conversion."
)
expect(mail.body.sanitized).to have_text("The charge will be listed as GUMRD.COM* on your credit card statement.")
end
it "has the right subject for a purchase" do
expect(mail.subject).to match(/^You bought /)
end
context "when the purchase is free" do
let(:seller) { create(:user, email: "alice@gumroad.com", name: "alice nguyen") }
let(:product) { create(:product, user: seller, price_cents: 0) }
let(:purchase) do
create(:purchase, link: product, seller:, email: "buyer@example.com", price_cents: 0, stripe_transaction_id: nil, stripe_fingerprint: nil, purchaser: create(:user))
end
before do
purchase.create_url_redirect!
end
it "has the right subject" do
expect(CustomerMailer.receipt(purchase.id).subject).to match(/^You got /)
end
it "does not include generate invoice section" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.encoded).not_to have_link("Generate invoice")
end
end
it "has the right subject for a rental purchase" do
user = create(:user, email: "alice@gumroad.com", name: "alice nguyen")
link = create(:product_with_video_file, user:, purchase_type: :buy_and_rent, price_cents: 500, rental_price_cents: 0)
purchase = create(:purchase, link:, seller: user, email: "somewhere@gumroad.com", price_cents: 0, stripe_transaction_id: nil,
stripe_fingerprint: nil, is_rental: true)
purchase.create_url_redirect!
expect(CustomerMailer.receipt(purchase.id).subject).to match(/^You rented /)
end
it "has the right subject for an original subscription purchase" do
purchase = create(:membership_purchase)
purchase.create_url_redirect!
expect(CustomerMailer.receipt(purchase.id).subject).to match(/^You've subscribed to /)
end
context "when the purchase is for a recurring subscription" do
let(:purchase) { create(:recurring_membership_purchase) }
subject(:mail) { CustomerMailer.receipt(purchase.id) }
before do
purchase.create_url_redirect!
end
it "has the right subject for a recurring subscription purchase" do
expect(mail.subject).to match(/^Recurring charge for /)
end
it "has the right subject for a subscription upgrade purchase" do
purchase.is_upgrade_purchase = true
purchase.save!
expect(mail.subject).to match(/^You've upgraded your membership for /)
end
it "includes recurring subscription specific content" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Thank you for your payment!")
expect(mail.body.sanitized).to include(
"We have successfully processed the payment for your recurring subscription to"
)
expect(mail.body.sanitized).to have_text(
"You will be charged once a month. " \
"If you would like to manage your membership you can visit subscription settings."
)
end
end
it "does not have the download link in the receipt if link has no content" do
user = create(:user)
link = create(:product, user:)
purchase = create(:purchase, link:, seller: link.user)
purchase.url_redirect = UrlRedirect.create!(purchase:, link:)
purchase.save
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to_not match("Download")
end
describe "Recommended products section" do
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller, name: "Digital product") }
let(:purchase) do
create(
:purchase,
link: product,
seller:,
price_cents: 14_99,
created_at: DateTime.parse("January 1, 2023")
)
end
context "when there are no recommended products" do
it "doesn't include recommended products section" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).not_to have_text("Customers who bought this item also bought")
end
end
context "when there are recommended products" do
let(:recommendable_product) do
create(:product, :recommendable, name: "Recommended product", price_cents: 9_99)
end
let!(:affiliate) do
create(
:direct_affiliate,
seller: recommendable_product.user,
products: [recommendable_product], affiliate_user: create(:user)
)
end
before do
purchase.update!(purchaser: create(:user))
seller.update!(recommendation_type: User::RecommendationType::GUMROAD_AFFILIATES_PRODUCTS)
end
it "includes recommended products section" do
expect(RecommendedProductsService).to receive(:fetch).with(
{
model: "sales",
ids: [purchase.link.id],
exclude_ids: [purchase.link.id],
number_of_results: RecommendedProducts::BaseService::NUMBER_OF_RESULTS,
user_ids: nil,
}
).and_return(Link.where(id: [recommendable_product.id]))
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Customers who bought this item also bought")
expect(mail.body.sanitized).to have_text("$9.99")
end
end
end
context "with membership purchase" do
let(:product) { create(:membership_product) }
let(:purchase) do
create(
:membership_purchase,
link: product,
price_cents: 1998,
created_at: DateTime.parse("January 1, 2023"),
)
end
before do
purchase.create_url_redirect!
end
it "has the view content link in the receipt for a membership product" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to match("View content")
end
context "when is original purchase" do
before do
purchase.update!(is_original_subscription_purchase: true)
end
it "has the view content button and details" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to match("View content")
end
end
it "renders subscription receipt" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text(
"All charges are processed in United States Dollars. " +
"Your bank or financial institution may apply their own fees for currency conversion."
)
expect(mail.body.sanitized).to have_text("The charge will be listed as GUMRD.COM* on your credit card statement.")
expect(mail.body.sanitized).to have_text("Today's payment The Works of Edgar Gumstein $19.98 Generate invoice")
expect(mail.body.encoded).to have_link("Generate invoice")
expect(mail.body.sanitized).to have_text("Upcoming payment The Works of Edgar Gumstein $19.98 on Feb 1, 2023")
expect(mail.body.sanitized).to have_text("Payment method VISA *4062")
expect(mail.body.encoded).to have_link("View content")
expect(mail.body.sanitized).to have_text("You will be charged once a month. If you would like to manage your membership you can visit subscription settings.")
expect(mail.body.encoded).to have_link("Generate invoice")
end
context "with tax charge" do
before do
purchase.update!(was_purchase_taxable: true, tax_cents: 254, price_cents: 1_744, displayed_price_cents: 1_744)
end
it "renders tax amount" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Today's payment The Works of Edgar Gumstein $17.44")
expect(mail.body.sanitized).to have_text("Sales tax (included) $2.54")
expect(mail.body.sanitized).to have_text("Amount paid $19.98")
expect(mail.body.encoded).to have_link("Generate invoice")
expect(mail.body.sanitized).to have_text("Upcoming payment The Works of Edgar Gumstein $19.98 on Feb 1, 2023")
expect(mail.body.sanitized).to have_text("Payment method VISA *4062")
end
context "with shipping charge" do
before do
purchase.update!(
shipping_cents: 499,
total_transaction_cents: purchase.total_transaction_cents + 499
)
end
it "renders shipping amount" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Today's payment The Works of Edgar Gumstein $17.44")
expect(mail.body.sanitized).to have_text("Shipping $4.99")
expect(mail.body.sanitized).to have_text("Sales tax (included) $2.54")
expect(mail.body.sanitized).to have_text("Amount paid $24.97")
expect(mail.body.encoded).to have_link("Generate invoice")
expect(mail.body.sanitized).to have_text("The Works of Edgar Gumstein $24.97 on Feb 1, 2023")
end
context "when purchase is in EUR" do
before do
purchase.link.default_price.update!(currency: Currency::EUR)
purchase.link.update!(price_currency_type: Currency::EUR)
purchase.update!(
displayed_price_currency_type: Currency::EUR,
rate_converted_to_usd: 1.07,
displayed_price_cents: 1_866 # 17.44 * 1.07
)
end
it "renders correct amounts" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Today's payment The Works of Edgar Gumstein $17.44")
expect(mail.body.sanitized).to have_text("Shipping $4.99")
expect(mail.body.sanitized).to have_text("Sales tax (included) $2.54")
expect(mail.body.sanitized).to have_text("Amount paid $24.97")
expect(mail.body.encoded).to have_link("Generate invoice")
expect(mail.body.sanitized).to have_text("The Works of Edgar Gumstein €26.72 on Feb 1, 2023") # 24.97 * 1.07
end
end
end
end
context "with free trial membership purchase" do
let(:purchase) do
create(
:free_trial_membership_purchase,
price_cents: 3_00,
created_at: Date.new(2023, 1, 1),
)
end
it "renders payment details" do
purchase.subscription.update!(free_trial_ends_at: Date.new(2023, 1, 8))
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Your free trial has begun!")
expect(mail.body.sanitized).to have_text("Today's payment The Works of Edgar Gumstein $0")
expect(mail.body.sanitized).to have_text("Upcoming payment The Works of Edgar Gumstein $3 on Jan 8, 2023")
expect(mail.body.encoded).not_to have_link("Generate invoice")
end
end
context "when the purchase has fixed length" do
context "when there is at least one more remaining charge" do
before do
purchase.subscription.update!(charge_occurrence_count: 2)
end
it "renders upcoming payment information" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Upcoming payment The Works of Edgar Gumstein: 2 of 2 $19.98 on Feb 1, 2023")
end
end
context "when there are no more remaining charges" do
before do
purchase.subscription.update!(charge_occurrence_count: 1)
end
it "does not render upcoming payment information" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).not_to have_text("Upcoming payment")
end
end
end
context "when the product is licensed" do
let!(:license) { create(:license, purchase:, link: purchase.link) }
before do
purchase.link.update!(is_licensed: true)
end
it "includes license details" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to include license.serial
end
context "when is not the original purchase" do
let(:recurring_membership_purchase) { create(:recurring_membership_purchase, :with_license) }
before do
recurring_membership_purchase.create_url_redirect!
end
it "does not include license details" do
mail = CustomerMailer.receipt(recurring_membership_purchase.id)
expect(mail.body.sanitized).not_to include license.serial
end
end
context "when is a multi-seat license" do
before do
purchase.update!(
is_multiseat_license: true,
quantity: 2
)
end
it "includes number of seats" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text "Number of seats 2"
end
end
end
context "when the purchase has custom fields" do
before do
purchase.purchase_custom_fields << [
build(:purchase_custom_field, name: "Field 1", value: "FIELD1_VALUE"),
build(:purchase_custom_field, name: "Field 2", value: "FIELD2_VALUE"),
]
end
it "includes custom fields details" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text "Field 1 FIELD1_VALUE"
expect(mail.body.sanitized).to have_text "Field 2 FIELD2_VALUE"
end
end
context "when the product requires shipping" do
let(:shipping_details) do
{
full_name: "Edgar Gumstein",
street_address: "123 Gum Road",
country: "United States",
state: "CA",
zip_code: "94107",
city: "San Francisco",
}
end
before do
purchase.link.update!(require_shipping: true)
purchase.update!(**shipping_details)
end
it "includes shipping details" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to include "Shipping info"
expect(mail.body.sanitized).to include "Shipping address"
expect(mail.body.sanitized).to include "Edgar Gumstein"
expect(mail.body.sanitized).to include "123 Gum Road"
expect(mail.body.sanitized).to include "San Francisco, CA 94107"
expect(mail.body.sanitized).to include "United States"
end
end
end
it "shows the custom view content text in the receipt" do
product = create(:product_with_pdf_file)
product.custom_view_content_button_text = "Custom Text"
product.save!
purchase = create(:purchase, link: product, purchaser: @user)
create(:url_redirect, purchase:)
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to match("Custom Text")
end
it "shows the view content link in the receipt for a product having rich content" do
product = create(:product)
purchase = create(:purchase, link: product, purchaser: @user)
create(:url_redirect, purchase:)
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to include("View content")
end
it "discloses sales tax when it was taxed" do
user = create(:user)
link = create(:product, user:)
zip_tax_rate = create(:zip_tax_rate)
purchase = create(:purchase, link:, seller: link.user, zip_tax_rate:)
purchase.was_purchase_taxable = true
purchase.tax_cents = 1_50
purchase.save
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to match("Sales tax")
end
it "does not render tax or total fields if purchas was not taxed" do
user = create(:user)
link = create(:product, user:)
purchase = create(:purchase, link:, seller: link.user)
purchase.was_purchase_taxable = false
purchase.save
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to_not match("Sales tax")
expect(mail.body.sanitized).to_not match("Order total")
end
it "correctly renders variants" do
user = create(:user)
link = create(:product, user:)
purchase = create(:purchase, link:, seller: link.user)
category = create(:variant_category, title: "sizes", link:)
variant = create(:variant, name: "small", price_difference_cents: 300, variant_category: category)
category2 = create(:variant_category, title: "colors", link:)
variant2 = create(:variant, name: "red", price_difference_cents: 300, variant_category: category2)
purchase.variant_attributes << variant
purchase.variant_attributes << variant2
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to match("small, red")
end
context "when is a test purchase" do
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller, name: "Test product") }
let(:purchase) { create(:purchase, link: product, seller:, purchaser: seller) }
it "renders the receipt" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to match(product.name)
expect(mail.body.sanitized.include?("This was a test purchase — you have not been charged")).to be(true)
expect(mail.subject).to eq "You bought #{product.name}!"
end
end
describe "shipping display" do
describe "product with shipping" do
let(:product) { create(:physical_product) }
let(:purchase) { create(:physical_purchase, link: product) }
before do
purchase.shipping_cents = 20_00
purchase.save!
end
it "shows the shipping line item in the receipt" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to match("Shipping")
end
end
describe "product without shipping" do
let(:product) { create(:product) }
let(:purchase) { create(:purchase, link: product) }
it "does not show the shipping line item in the receipt" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to_not match("Shipping")
end
end
end
context "when the purchase has a refund policy" do
let(:purchase) { create(:purchase) }
before do
purchase.create_purchase_refund_policy!(
title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30],
max_refund_period_in_days: 30,
fine_print: "This is the fine print.",
)
end
it "includes the refund policy" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to include("30-day money back guarantee")
expect(mail.body.sanitized).to include("This is the fine print.")
end
end
describe "subscription with limited duration discount" do
let(:purchase) do
create(
:membership_purchase,
price_cents: 500,
created_at: DateTime.parse("January 1, 2023"),
)
end
before do
purchase.create_purchase_offer_code_discount(
offer_code: create(:offer_code, user: purchase.seller, products: [purchase.link]),
offer_code_amount: 100,
offer_code_is_percent: false,
pre_discount_minimum_price_cents: 600,
duration_in_billing_cycles: 1
)
purchase.create_url_redirect!
end
context "when the discount's duration has elapsed" do
it "includes the correct payment amounts" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Today's payment")
expect(mail.body.sanitized).to have_text("The Works of Edgar Gumstein $5")
expect(mail.body.sanitized).to have_text("Upcoming payment")
expect(mail.body.sanitized).to have_text("The Works of Edgar Gumstein $6 on Feb 1, 2023")
end
context "when the purchase includes tax" do
before do
allow_any_instance_of(SalesTaxCalculator).to receive_message_chain(:calculate, :tax_cents).and_return(100)
end
it "includes the correct payment amounts" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Today's payment")
expect(mail.body.sanitized).to have_text("The Works of Edgar Gumstein $5")
expect(mail.body.sanitized).to have_text("Upcoming payment")
expect(mail.body.sanitized).to have_text("The Works of Edgar Gumstein $7 on Feb 1, 2023")
end
end
end
context "when the discount's duration has not elapsed" do
before do
purchase.purchase_offer_code_discount.update!(duration_in_billing_cycles: 2)
end
it "includes the correct payment amounts" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Today's payment")
expect(mail.body.sanitized).to have_text("The Works of Edgar Gumstein $5")
expect(mail.body.sanitized).to have_text("Upcoming payment")
expect(mail.body.sanitized).to have_text("The Works of Edgar Gumstein $5 on Feb 1, 2023")
end
end
end
context "commission deposit purchase", :vcr do
let(:purchase) { create(:commission_deposit_purchase) }
before { purchase.create_artifacts_and_send_receipt! }
it "includes the correct payment amounts" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Product price $2")
expect(mail.body.sanitized).to have_text("Today's payment")
expect(mail.body.sanitized).to have_text("The Works of Edgar Gumstein $1")
expect(mail.body.sanitized).to have_text("Upcoming payment")
expect(mail.body.sanitized).to have_text("The Works of Edgar Gumstein $1 on completion")
end
end
context "commission completion purchase", :vcr do
let(:commission) { create(:commission) }
before do
commission.create_completion_purchase!
commission.deposit_purchase.create_url_redirect!
end
it "includes the correct subject and view content link" do
mail = CustomerMailer.receipt(commission.completion_purchase.id)
expect(mail.subject).to eq("The Works of Edgar Gumstein is ready for download!")
expect(mail.body.encoded).to have_link("View content", href: commission.deposit_purchase.url_redirect.download_page_url)
end
end
context "purchase with a tip" do
let(:purchase) { create(:purchase, price_cents: 1000) }
before { purchase.create_tip!(value_cents: 500) }
it "includes the tip info in the receipt" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Product price $5")
expect(mail.body.sanitized).to have_text("Tip $5")
expect(mail.body.sanitized).to have_text("The Works of Edgar Gumstein $10")
end
end
context "call purchase" do
let(:purchase) { create(:call_purchase, variant_attributes: [create(:variant, name: "1 hour")]) }
before { purchase.create_artifacts_and_send_receipt! }
it "includes the correct attributes" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to include("Call schedule #{purchase.call.formatted_time_range} #{purchase.call.formatted_date_range}")
expect(mail.body.sanitized).to include("Duration 1 hour")
expect(mail.body.sanitized).to include("Product price $1")
expect(mail.body.sanitized).to_not have_text("Variant")
end
end
context "bundle purchase" do
let(:purchase) { create(:purchase, link: create(:product, :bundle)) }
before do
purchase.seller.update!(name: "Seller")
purchase.create_artifacts_and_send_receipt!
end
it "includes information for all of the bundle products" do
mail = CustomerMailer.receipt(purchase.id)
expect(mail.body.sanitized).to have_text("Bundle Product 1")
expect(mail.body.encoded).to have_link("View content", href: purchase.product_purchases.first.url_redirect.download_page_url)
expect(mail.body.sanitized).to have_text("Bundle Product 2")
expect(mail.body.encoded).to have_link("View content", href: purchase.product_purchases.second.url_redirect.download_page_url)
expect(mail.body.sanitized).to have_text("Questions about your products? Contact Seller by replying to this email.")
end
end
context "product_questions_note" do
let(:purchase) { create(:purchase) }
subject(:mail) { CustomerMailer.receipt(purchase.id) }
before do
purchase.seller.update!(name: "Seller")
purchase.create_url_redirect!
end
it "generates questions note with reply" do
expect(mail.body.sanitized).to have_text("Questions about your product? Contact Seller by replying to this email.")
end
context "when for_email is set to false" do
subject(:mail) { CustomerMailer.receipt(purchase.id, for_email: false) }
it "generates questions note with email" do
expect(mail.body.sanitized).to have_text("Questions about your product? Contact Seller at #{purchase.seller.email}.")
end
end
end
describe "gift_receiver_receipt" do
let(:product) { create(:product, name: "Digital product") }
let(:gift) { create(:gift, gift_note: "Happy birthday!", giftee_email: "giftee@example.com", gifter_email: "gifter@example.com", link: product) }
let!(:gift_sender_purchase) { create(:purchase, link: product, gift_given: gift, is_gift_sender_purchase: true, email: "gifter@example.com") }
let(:purchase) { create(:purchase, link: product, gift_received: gift, is_gift_receiver_purchase: true, email: "giftee@example.com") }
let(:seller) { product.user }
before do
purchase.create_url_redirect!
seller.update!(name: "Seller")
end
subject(:mail) do
CustomerMailer.receipt(purchase.id)
end
it "renders the headers for a receipt" do
expect(mail.subject).to eq("gifter@example.com bought Digital product for you!")
expect(mail.to).to eq(["giftee@example.com"])
expect(mail[:from].value).to eq("Seller <noreply@#{CUSTOMERS_MAIL_DOMAIN}>")
expect(mail[:reply_to].value).to eq(seller.email)
end
it "renders the body" do
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/one_off_mailer_spec.rb | spec/mailers/one_off_mailer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe OneOffMailer do
let(:email) { "seller@example.com" }
let(:reply_to) { ApplicationMailer::NOREPLY_EMAIL_WITH_NAME }
describe "#email" do
let(:subject) { "Email subject" }
let(:body) { "Email body" }
it "doesn't send attempt to email if both email and id are not provided" do
mail = described_class.email(subject:, body:)
expect(mail.message).to be_a(ActionMailer::Base::NullMail)
end
it "doesn't send email if user has been marked as deleted" do
deleted_user = create(:user, :deleted)
mail = described_class.email(user_id: deleted_user.id, subject:, body:)
expect(mail.message).to be_a(ActionMailer::Base::NullMail)
end
it "doesn't send email if user is suspended" do
suspended_user = create(:tos_user)
mail = described_class.email(user_id: suspended_user.id, subject:, body:)
expect(mail.message).to be_a(ActionMailer::Base::NullMail)
end
it "doesn't send email if email address provided is invalid" do
mail = described_class.email(email: "notvalid", subject:, body:)
expect(mail.message).to be_a(ActionMailer::Base::NullMail)
end
it "sets correct attributes" do
mail = described_class.email(email:, subject:, body:)
expect(mail.from).to include("hi@#{CUSTOMERS_MAIL_DOMAIN}")
expect(mail.subject).to eq(subject)
expect(mail.body.encoded).to include(body)
expect(mail.reply_to).to be(nil)
end
it "allows safe html tags and strips unsafe ones" do
mail = described_class.email(email:, subject:, body: "<a href=\"http://example.com\">link</a><script>alert('hello')</script>")
expect(mail.body.encoded).to include("<a href=\"http://example.com\">link</a>")
expect(mail.body.encoded).not_to include("<script>")
end
it "sets reply_to header if provided" do
mail = described_class.email(email:, subject:, body:, reply_to:)
expect(mail.reply_to).to include(ApplicationMailer::NOREPLY_EMAIL)
mail = described_class.email(email:, subject:, body:)
expect(mail.reply_to).to be(nil)
end
it "uses default from email when from parameter is not provided" do
mail = described_class.email(email:, subject:, body:)
expect(mail.from).to eq(["hi@#{CUSTOMERS_MAIL_DOMAIN}"])
end
it "uses custom from email when from parameter is provided" do
custom_from = "Custom Name <custom@#{CREATOR_CONTACTING_CUSTOMERS_MAIL_DOMAIN}>"
mail = described_class.email(email:, subject:, body:, from: custom_from, sender_domain: "creators")
expect(mail.from).to eq(["custom@#{CREATOR_CONTACTING_CUSTOMERS_MAIL_DOMAIN}"])
end
it "uses default sender_domain (customers) when sender_domain parameter is not provided" do
expect(MailerInfo).to receive(:random_delivery_method_options).with(domain: :customers).and_call_original
described_class.email(email:, subject:, body:).deliver_now
end
it "uses custom sender_domain when sender_domain parameter is provided" do
expect(MailerInfo).to receive(:random_delivery_method_options).with(domain: :creators).and_call_original
custom_from = "Custom Name <custom@#{CREATOR_CONTACTING_CUSTOMERS_MAIL_DOMAIN}>"
described_class.email(email:, subject:, body:, from: custom_from, sender_domain: "creators").deliver_now
end
end
describe "#email_using_installment" do
let(:installment) { create(:installment, name: "My first installment", allow_comments: false) }
let(:installment_external_id) { installment.external_id }
it "doesn't send the email if neither recipient user ID nor recipient email is provided" do
mail = described_class.email_using_installment(subject:, installment_external_id:)
expect(mail.message).to be_a(ActionMailer::Base::NullMail)
end
it "doesn't send the email if the recipient user has been marked as deleted" do
deleted_user = create(:user, :deleted)
mail = described_class.email_using_installment(user_id: deleted_user.id, installment_external_id:)
expect(mail.message).to be_a(ActionMailer::Base::NullMail)
end
it "doesn't send the email if the recipient user is suspended" do
suspended_user = create(:tos_user)
mail = described_class.email_using_installment(user_id: suspended_user.id, installment_external_id:)
expect(mail.message).to be_a(ActionMailer::Base::NullMail)
end
it "doesn't send the email if the provided recipient email address is invalid" do
mail = described_class.email_using_installment(email: "notvalid", installment_external_id:)
expect(mail.message).to be_a(ActionMailer::Base::NullMail)
end
it "uses the provided installment's name to set the subject" do
mail = described_class.email_using_installment(email:, installment_external_id:)
expect(mail.subject).to eq("My first installment")
end
it "allows overriding the subject" do
subject = "Another subject"
mail = described_class.email_using_installment(email:, installment_external_id:, subject:)
expect(mail.subject).to eq(subject)
end
it "generates the email body from the installment" do
mail = described_class.email_using_installment(email:, installment_external_id:)
expect(mail.body.encoded).to include(installment.message)
end
it "sets reply_to header if provided" do
mail = described_class.email_using_installment(email:, subject:, installment_external_id:, reply_to:)
expect(mail.reply_to).to include(ApplicationMailer::NOREPLY_EMAIL)
mail = described_class.email(email:, subject:, body:)
expect(mail.reply_to).to be(nil)
end
it "does not show the unsubscribe link" do
mail = described_class.email_using_installment(email:, installment_external_id:)
expect(mail.body.encoded).not_to include("Unsubscribe")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/concerns/rescue_smtp_errors_spec.rb | spec/mailers/concerns/rescue_smtp_errors_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RescueSmtpErrors do
let(:mailer_class) do
Class.new(ActionMailer::Base) do
include RescueSmtpErrors
def welcome
# We need a body to not render views
mail(from: "foo@bar.com", body: "")
end
end
end
describe "rescue from SMTP exceptions" do
let(:user) { create(:user) }
context "when exception class is ArgumentError" do
it "raises on messages other than blank-to-address" do
allow_any_instance_of(mailer_class).to receive(:welcome).and_raise(ArgumentError)
expect { mailer_class.welcome.deliver_now }.to raise_error(ArgumentError)
end
it "does not raise on blank smtp to address" do
allow_any_instance_of(mailer_class).to receive(:welcome).and_raise(ArgumentError.new("SMTP To address may not be blank"))
expect { mailer_class.welcome.deliver_now }.to_not raise_error
end
end
it "does not raise Net::SMTPSyntaxError" do
allow_any_instance_of(mailer_class).to receive(:welcome).and_raise(Net::SMTPSyntaxError.new(nil))
expect { mailer_class.welcome.deliver_now }.to_not raise_error
end
it "does not raise Net::SMTPAuthenticationError" do
allow_any_instance_of(mailer_class).to receive(:welcome).and_raise(Net::SMTPAuthenticationError.new(nil))
expect { mailer_class.welcome.deliver_now }.to_not raise_error
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/mailers/concerns/custom_mailer_route_builder_spec.rb | spec/mailers/concerns/custom_mailer_route_builder_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CustomMailerRouteBuilder do
let(:mailer_class) do
Class.new(ActionMailer::Base) do
include CustomMailerRouteBuilder
end
end
before do
@mail = mailer_class.new
@user = create(:user, username: "creatordude")
@post = create(:installment, seller: @user)
@purchase = create(:purchase, link: @post.link)
end
describe "#build_mailer_post_route" do
subject { @mail.build_mailer_post_route(post: @post) }
context "when slug is missing" do
before do
@post.update!(slug: nil)
end
it { is_expected.to be_nil }
end
context "when slug is present" do
context "when not shown on the profile" do
it { is_expected.to be_nil }
end
context "when shown on the profile" do
before do
@post.update!(shown_on_profile: true)
end
shared_examples "common route behavior" do
it { is_expected.to eq(url) }
context "when purchase is present" do
subject { @mail.build_mailer_post_route(post: @post, purchase: @purchase) }
it "sends the purchase id as parameter" do
is_expected.to eq("#{url}?#{{ purchase_id: @purchase.external_id }.to_query}")
end
end
end
context "when user does not use custom domains" do
let(:url) { "#{UrlService.domain_with_protocol}/#{@user.username}/p/#{@post.slug}" }
include_examples "common route behavior"
context "when user's username is missing" do
let(:url) { "#{UrlService.domain_with_protocol}/#{@user.external_id}/p/#{@post.slug}" }
before do
@user.update!(username: nil)
end
it "passes the external_id as the username parameter" do
is_expected.to eq(url)
end
end
end
context "when user is using custom domains" do
let!(:custom_domain) { create(:custom_domain, domain: "example.com", user: @user) }
let(:url) { "http://#{custom_domain.domain}/p/#{@post.slug}" }
include_examples "common route behavior"
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/channels/community_channel_spec.rb | spec/channels/community_channel_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe CommunityChannel do
let(:user) { create(:user) }
let(:seller) { create(:user) }
let(:product) { create(:product, community_chat_enabled: true, user: seller) }
let!(:community) { create(:community, seller: seller, resource: product) }
before do
Feature.activate_user(:communities, seller)
end
def subscribe_to_channel
subscribe(community_id: community.external_id)
end
describe "#subscribed" do
context "when user is not authenticated" do
before do
stub_connection current_user: nil
end
it "rejects subscription" do
subscribe_to_channel
expect(subscription).to be_rejected
end
end
context "when user is authenticated" do
before do
stub_connection current_user: user
end
context "when community_id is not provided" do
it "rejects subscription" do
subscribe community_id: nil
expect(subscription).to be_rejected
end
end
context "when community is not found" do
it "rejects subscription" do
subscribe community_id: "non_existent_id"
expect(subscription).to be_rejected
end
end
context "when user does not have access to community" do
it "rejects subscription" do
subscribe_to_channel
expect(subscription).to be_rejected
end
end
context "when user has access to community" do
let!(:purchase) { create(:purchase, link: product, seller:, purchaser: user) }
it "subscribes to the community channel" do
subscribe_to_channel
expect(subscription).to be_confirmed
expect(subscription).to have_stream_from("community:community_#{community.external_id}")
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/channels/connection_spec.rb | spec/channels/connection_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe ApplicationCable::Connection, type: :channel do
let!(:user) { create(:user) }
let!(:gumroad_admin_user) { create(:user, is_team_member: true) }
let!(:impersonated_user) { create(:user) }
def connect_with_user(user)
if user
session = { "warden.user.user.key" => [[user.id], nil] }
else
session = {}
end
connect session: session
end
describe "#connect" do
it "connects with valid user" do
connect_with_user(user)
expect(connection.current_user).to eq(user)
end
context "when user is a gumroad admin" do
it "connects with gumroad admin when impersonation is not set" do
connect_with_user(gumroad_admin_user)
expect(connection.current_user).to eq(gumroad_admin_user)
end
it "connects with impersonated user when set" do
$redis.set(RedisKey.impersonated_user(gumroad_admin_user.id), impersonated_user.id)
connect_with_user(gumroad_admin_user)
expect(connection.current_user).to eq(impersonated_user)
end
it "connects with gumroad admin when impersonated user is not found" do
$redis.set(RedisKey.impersonated_user(gumroad_admin_user.id), -1)
connect_with_user(gumroad_admin_user)
expect(connection.current_user).to eq(gumroad_admin_user)
end
it "connects with gumroad admin when impersonated user is not active" do
impersonated_user.update!(user_risk_state: "suspended_for_fraud")
$redis.set(RedisKey.impersonated_user(gumroad_admin_user.id), impersonated_user.id)
connect_with_user(gumroad_admin_user)
expect(connection.current_user).to eq(gumroad_admin_user)
end
end
it "rejects connection when user is not found" do
expect { connect_with_user(nil) }.to have_rejected_connection
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/channels/user_channel_spec.rb | spec/channels/user_channel_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe UserChannel do
let(:user) { create(:user) }
let(:seller) { create(:user) }
let(:product) { create(:product, community_chat_enabled: true, user: seller) }
let!(:community) { create(:community, seller: seller, resource: product) }
before do
Feature.activate_user(:communities, seller)
end
describe "#subscribed" do
context "when user is not authenticated" do
before do
stub_connection current_user: nil
end
it "rejects subscription" do
subscribe
expect(subscription).to be_rejected
end
end
context "when user is authenticated" do
before do
stub_connection current_user: user
end
it "subscribes to the user channel" do
subscribe
expect(subscription).to be_confirmed
expect(subscription).to have_stream_from("user:user_#{user.external_id}")
end
end
end
describe "#receive" do
before do
stub_connection current_user: user
subscribe
end
context "when type is 'latest_community_info'" do
let(:type) { described_class::LATEST_COMMUNITY_INFO_TYPE }
context "when community_id is not provided" do
it "rejects the message" do
perform :receive, { type: }
expect(subscription).to be_rejected
end
end
context "when community is not found" do
it "rejects the message" do
perform :receive, { type:, community_id: "non_existent_id" }
expect(subscription).to be_rejected
end
end
context "when user does not have access to community" do
it "rejects the message" do
perform :receive, { type:, community_id: community.external_id }
expect(subscription).to be_rejected
end
end
context "when user has access to community" do
let!(:purchase) { create(:purchase, link: product, seller:, purchaser: user) }
it "broadcasts community info" do
expect do
perform :receive, { type:, community_id: community.external_id }
end.to have_broadcasted_to("user:user_#{user.external_id}").with(
type:,
data: include(
id: community.external_id,
name: community.name,
thumbnail_url: community.thumbnail_url,
seller: include(
id: community.seller.external_id,
name: community.seller.display_name,
avatar_url: community.seller.avatar_url
),
last_read_community_chat_message_created_at: nil,
unread_count: 0
)
)
expect(subscription).to be_confirmed
end
end
end
context "when type is unknown" do
it "does nothing" do
expect do
perform :receive, { type: "unknown_type" }
end.not_to have_broadcasted_to("user:user_#{user.external_id}")
expect(subscription).to be_confirmed
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/product_custom_domain_constraint.rb | lib/product_custom_domain_constraint.rb | # frozen_string_literal: true
class ProductCustomDomainConstraint
def self.matches?(request)
CustomDomain.find_by_host(request.host)&.product.present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/custom_rouge_theme.rb | lib/custom_rouge_theme.rb | # frozen_string_literal: true
# Overrides the 'bg0' pallete of Rouge's Gruvbox light theme
# https://github.com/rouge-ruby/rouge/blob/43d346cceb1123510de67ec58a2fa1e29d22cc7b/lib/rouge/themes/gruvbox.rb
class CustomRougeTheme < Rouge::Themes::Gruvbox
def self.make_light!
super
palette bg0: "#fff"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/api_domain_constraint.rb | lib/api_domain_constraint.rb | # frozen_string_literal: true
class ApiDomainConstraint
def self.matches?(request)
Rails.env.development? || VALID_API_REQUEST_HOSTS.include?(request.host)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/discover_domain_constraint.rb | lib/discover_domain_constraint.rb | # frozen_string_literal: true
class DiscoverDomainConstraint
def self.matches?(request)
request.host == VALID_DISCOVER_REQUEST_HOST
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/catch_bad_request_errors.rb | lib/catch_bad_request_errors.rb | # frozen_string_literal: true
class CatchBadRequestErrors
def initialize(app)
@app = app
end
def call(env)
@app.call(env)
rescue ActionController::BadRequest
if env["HTTP_ACCEPT"].include?("application/json")
[400, { "Content-Type" => "application/json" }, [{ success: false }.to_json]]
else
[400, { "Content-Type" => "text/html" }, []]
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/user_custom_domain_constraint.rb | lib/user_custom_domain_constraint.rb | # frozen_string_literal: true
class UserCustomDomainConstraint
def self.matches?(request)
Subdomain.find_seller_by_request(request).present? ||
CustomDomain.find_by_host(request.host)&.user&.username.present? ||
SubdomainRedirectorService.new.redirect_url_for(request).present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/discover_taxonomy_constraint.rb | lib/discover_taxonomy_constraint.rb | # frozen_string_literal: true
class DiscoverTaxonomyConstraint
def self.matches?(request)
valid_taxonomy_paths.include?(request.path)
end
def self.valid_taxonomy_paths
@valid_taxonomy_paths ||= Taxonomy.eager_load(:self_and_ancestors)
.order("taxonomy_hierarchies.generations" => :asc)
.map { |t| t.ancestry_path.unshift("").join("/") }
.freeze
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/gumroad_domain_constraint.rb | lib/gumroad_domain_constraint.rb | # frozen_string_literal: true
class GumroadDomainConstraint
def self.matches?(request)
VALID_REQUEST_HOSTS.include?(request.host)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/errors/gumroad_runtime_error.rb | lib/errors/gumroad_runtime_error.rb | # frozen_string_literal: true
class GumroadRuntimeError < RuntimeError
def initialize(message = nil, original_error: nil)
super(message || original_error)
set_backtrace(original_error.backtrace) if original_error
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/validators/hex_color_validator.rb | lib/validators/hex_color_validator.rb | # frozen_string_literal: true
class HexColorValidator < ActiveModel::EachValidator
HEX_COLOR_REGEX = /^#[0-9a-f]{6}$/i
def validate_each(record, attribute, value)
return if self.class.matches?(value)
record.errors.add(attribute, (options[:message] || "is not a valid hexadecimal color"))
end
def self.matches?(value)
value.present? && HEX_COLOR_REGEX.match(value).present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/sidekiq_utility.rb | lib/utilities/sidekiq_utility.rb | # frozen_string_literal: true
class SidekiqUtility
INSTANCE_ID_ENDPOINT = "http://169.254.169.254/latest/meta-data/instance-id"
def initialize
@process_set = Sidekiq::ProcessSet.new
graceful_shutdown_timeout = ENV.fetch("SIDEKIQ_GRACEFUL_SHUTDOWN_TIMEOUT", 4).to_i.hours
@timeout_at = Time.current + graceful_shutdown_timeout
end
def stop_process
# Set process to quiet mode.
sidekiq_process.quiet!
wait_for_sidekiq_to_process_existing_jobs
proceed_with_instance_termination
end
private
def wait_for_sidekiq_to_process_existing_jobs
while sidekiq_process["busy"].nonzero? do
# Break the loop and proceed with termination if waiting times out.
break if timeout_exceeded?
# Fix for stuck HandleSendgridEventJob jobs
# TODO: Remove this once we fix the root cause of the stuck jobs
workers = Sidekiq::Workers.new.select do |process_id, _, _|
process_id == sidekiq_process["identity"]
end
ignored_classes = ["HandleSendgridEventJob", "SaveToMongoWorker"]
if workers.any? && workers.all? { |_, _, work| ignored_classes.include?(JSON.parse(work["payload"])["class"]) }
Rails.logger.info("[SidekiqUtility] #{ignored_classes.join(", ")} jobs are stuck. Proceeding with instance termination.")
break
end
asg_client.record_lifecycle_action_heartbeat(lifecycle_params)
sleep 60
end
end
def timeout_exceeded?
Time.current > @timeout_at
end
def proceed_with_instance_termination
asg_client.complete_lifecycle_action(lifecycle_params.merge(lifecycle_action_result: "CONTINUE"))
end
def instance_id
@_instance_id ||= Net::HTTP.get(URI.parse(INSTANCE_ID_ENDPOINT))
end
def hostname
@_hostname ||= Socket.gethostname
end
def asg_client
@_asg_client ||= begin
aws_credentials = Aws::InstanceProfileCredentials.new
Aws::AutoScaling::Client.new(credentials: aws_credentials)
end
end
def sidekiq_process
@process_set.find { |process| process["hostname"] == hostname }
end
def lifecycle_params
{
lifecycle_hook_name: ENV["SIDEKIQ_LIFECYCLE_HOOK_NAME"],
auto_scaling_group_name: ENV["SIDEKIQ_ASG_NAME"],
instance_id:,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/ffprobe.rb | lib/utilities/ffprobe.rb | # frozen_string_literal: true
class Ffprobe
attr_reader :path
def initialize(path)
@path = File.expand_path(path)
end
def parse
raise ArgumentError, "File not found #{path}" unless File.exist?(path)
OpenStruct.new(first_stream)
end
private
def calculate_framerate(r_frame_rate)
rfr = r_frame_rate.split("/")
# framerate is typically in "24/1" string format
rfr[1].to_i == 0 ? rfr[0] : (rfr[0].to_i / rfr[1].to_i)
end
def first_stream
video_information["streams"].first.tap do |stream|
stream.merge!(framerate: calculate_framerate(stream["r_frame_rate"]))
end
end
def video_information
@video_information ||= begin
result = `#{command}`
parse_json(result)
end
end
def parse_json(result)
JSON.parse(result)
end
def command
%(ffprobe -print_format json -show_streams -select_streams v:0 "#{path}" 2> /dev/null)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/d3.rb | lib/utilities/d3.rb | # frozen_string_literal: true
##
# A collection of D3 related helper methods.
##
class D3
class << self
def formatted_date(date, today_date: Date.today)
date == today_date ? "Today" : date.strftime("%b %e, %Y")
end
def formatted_date_with_timezone(time, timezone)
today_date = Time.current.in_time_zone(timezone).to_date
date = time.in_time_zone(timezone).to_date
formatted_date(date, today_date:)
end
def full_date_domain(dates)
(0..dates.to_a.length - 1).map do |i|
date = (dates.first + i)
date.strftime("%B %e, %Y")
end
end
def date_domain(dates)
(0..dates.to_a.length - 1).map do |i|
date = (dates.first + i)
ordinalized_day = date.day.ordinalize
date.strftime("%A, %B #{ordinalized_day}")
end
end
def date_month_domain(dates)
last_month = nil
month_index = -1
(0..dates.to_a.length - 1).map do |i|
date = (dates.first + i)
ordinalized_day = date.day.ordinalize
# The formatted month string, eg "July 2019"
month = date.strftime("%B %Y")
# Each time we hit a new month, we increment the month_index
if month != last_month
last_month = month
month_index = month_index + 1
end
{
date: date.strftime("%A, %B #{ordinalized_day}"),
month:,
month_index:
}
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/xml_helpers.rb | lib/utilities/xml_helpers.rb | # frozen_string_literal: true
# Public: Helper functions for working with the built in REXML parser.
module XmlHelpers
# Public: Gets the text contained within the element at the given
# xpath, and given a root element. The root element may be any
# XML element and does not need to be the root of the document as
# a whole.
#
# XPATH is formatted e.g. root/elemenetgroup/element
#
# Returns: A string containing the text content of the element at
# the xpath, or nil if the element cannot be found.
def self.text_at_xpath(root, xpath)
element = root.elements.each(xpath) { }.first
element&.text
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/global_config.rb | lib/utilities/global_config.rb | # frozen_string_literal: true
# GlobalConfig provides a centralized way to access environment variables and Rails credentials
class GlobalConfig
class << self
# Retrieve a value by its name from environment variables or Rails credentials
# @param name [String] The name of the environment variable
# @param default [Object] The default value to return if the value is not found in ENV or credentials
# @return [String, Object, nil] The value from environment variable, credentials, the default value, or nil if not found and no default provided
def get(name, default = :__no_default_provided__)
if default == :__no_default_provided__
value = ENV.fetch(name, fetch_from_credentials(name))
value.presence
else
ENV.fetch(name, fetch_from_credentials(name) || default)
end
end
# Retrieve a nested value by joining the parts with double underscores
# @param parts [Array<String>] The parts to join for the environment variable name
# @param default [Object] The default value to return if the value is not found
# @return [String, Object, nil] The value from environment variable, credentials, the default value, or nil if not found and no default provided
def dig(*parts, default: :__no_default_provided__)
name = parts.map(&:upcase).join("__")
if default == :__no_default_provided__
get(name)
else
get(name, default)
end
end
private
# Fetch a value from Rails credentials by converting the environment variable name to credential keys
# @param name [String] The name of the environment variable
# @return [Object, nil] The value from credentials or nil if not found
def fetch_from_credentials(name)
keys = name.downcase.split("__").map(&:to_sym)
Rails.application.credentials.dig(*keys)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/replica_lag_watcher.rb | lib/utilities/replica_lag_watcher.rb | # frozen_string_literal: true
## Will check replicas for lag every second, and sleep for a few seconds if they are.
#
# Typical usage:
# Model.find_each do |record|
# ReplicaLagWatcher.watch
# record.update!(field: new_value)
# end
# Try to not update/delete more than ~1000 rows at once between checks,
# otherwise the check will happen too late to prevent a large lag.
# Example:
# Model.in_batches do |relation| # default batch size is 1_000
# ReplicaLagWatcher.watch
# relation.update_all(field: new_value)
# end
class ReplicaLagWatcher
DEFAULT_OPTIONS = {
check_every: 1, # prevents from spamming the replicas with queries checking their lag
sleep: 1, # duration of sleep when lagging
max_lag_allowed: 1, # if lag (always an integer) is superior to this, we will sleep
silence: false # outputs which replica is lagging, by how much, and how long we're sleeping for
}.freeze
class << self
def watch(options = nil)
# skip if there are no replicas to monitor
return if REPLICAS_HOSTS.empty?
options = options.nil? ? DEFAULT_OPTIONS : DEFAULT_OPTIONS.merge(options)
connect_to_replicas
while lagging?(options)
sleep_duration = options.fetch(:sleep)
puts("sleeping #{sleep_duration} #{"second".pluralize(sleep_duration)}") unless options[:silence]
sleep sleep_duration
end
end
def lagging?(options)
return unless check_for_lag?(options.fetch(:check_every))
self.last_checked_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
connections.each do |connection|
lag = connection.query("SHOW SLAVE STATUS").to_a[0]["Seconds_Behind_Master"]
raise("#{connection.query_options[:host]} lag = null. Is this replica available and replicating?") if lag.nil?
if lag > options.fetch(:max_lag_allowed)
puts("#{connection.query_options[:host]} lag = #{lag} #{"second".pluralize(lag)}") unless options[:silence]
return true
end
end
false
end
def check_for_lag?(check_every)
# check lag if this is the first time we run this
return true if last_checked_at.nil?
# check if grace period has expired
(last_checked_at + check_every) <= Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
def connect_to_replicas
# skip if we're already connected to replicas
return unless connections.nil?
self.connections = REPLICAS_HOSTS.map do |host|
common_options = ActiveRecord::Base.connection_db_config.configuration_hash.slice(:username, :password, :database)
Mysql2::Client.new(**common_options.merge(host:))
end
end
[:connections, :last_checked_at].each do |accessor_name|
define_method(accessor_name) do
Thread.current["#{name}.#{accessor_name}"]
end
define_method("#{accessor_name}=") do |new_value|
Thread.current["#{name}.#{accessor_name}"] = new_value
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/us_zip_codes.rb | lib/utilities/us_zip_codes.rb | # frozen_string_literal: true
module UsZipCodes
# Given a zip code in the United States, identifies the state code.
# 5-digit zip codes are supported.
# Zip+4 is also supported, but only the first 5 digits are used to determine the state.
# Accepts surrounding whitespace. Accepts a single whitespace or hyphen in between zip+4.
def self.identify_state_code(zip_code)
return if zip_code.blank?
zip_string = zip_code.to_s.strip
# Support a 5-digit zip, or zip+4.
valid_structure = (zip_string.length == 5 && zip_string !~ /\D/) ||
(zip_string.length == 9 && zip_string !~ /\D/) ||
(zip_string.length == 10 && !!(separator = [" ", "-"].find { |char| char == zip_string[5] }) && zip_string.split(separator).all? { |part| part !~ /\D/ })
return unless valid_structure
ZIP_CODE_TO_STATE[zip_string[0, 5]]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/feature.rb | lib/utilities/feature.rb | # frozen_string_literal: true
module Feature
extend self
def activate(feature_name)
Flipper.enable(feature_name)
end
def activate_user(feature_name, user)
Flipper.enable_actor(feature_name, user)
end
def deactivate(feature_name)
Flipper.disable(feature_name)
end
def deactivate_user(feature_name, user)
Flipper.disable_actor(feature_name, user)
end
def activate_percentage(feature_name, percentage)
Flipper.enable_percentage_of_actors(feature_name, percentage)
end
def deactivate_percentage(feature_name)
Flipper.disable_percentage_of_actors(feature_name)
end
def active?(feature_name, actor = nil)
Flipper.enabled?(feature_name, actor)
end
def inactive?(feature_name, actor = nil)
!Flipper.enabled?(feature_name, actor)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/dev_tools.rb | lib/utilities/dev_tools.rb | # frozen_string_literal: true
class DevTools
class << self
# Useful in admin for the same reasons as `delete_all_indices_and_reindex_all`, but when you
# don't want to index *everything* because you're connected to a copy of the production DB,
# which has too many records for that to be practical.
def reindex_all_for_user(user_id_or_record)
ActiveRecord::Base.connection.enable_query_cache!
user = user_id_or_record.is_a?(User) ? user_id_or_record : User.find(user_id_or_record)
without_loggers do
rel = Installment.where(seller_id: user.id)
print "Importing installments seller_id=#{user.id} => #{rel.count} records..."
es_import_with_time(rel)
rel = user.purchased_products
print "Importing purchased products of user with id #{user.id} => #{rel.count} records..."
es_import_with_time(rel)
rel = Purchase.where(purchaser_id: user.id)
print "Importing purchases where purchaser_id=#{user.id} => #{rel.count} records..."
es_import_with_time(rel)
rel = Purchase.where(purchaser_id: user.id)
print "Importing products from purchases where purchaser_id=#{user.id} => #{rel.count} records..."
es_import_with_time(rel)
rel = Purchase.where(seller_id: user.id)
print "Importing purchases where seller_id=#{user.id} => #{rel.count} records..."
es_import_with_time(rel)
rel = Purchase.joins(:affiliate_credit).where(affiliate_credit: { affiliate_user_id: user.id })
print "Importing purchases where affiliate_credit.affiliate_user_id=#{user.id} => #{rel.count} records..."
es_import_with_time(rel)
[Link, Balance].each do |model|
rel = model.where(user_id: user.id)
print "Importing #{model.name} user_id=#{user.id} => #{rel.count} records..."
es_import_with_time(rel)
end
end
nil
ensure
ActiveRecord::Base.connection.disable_query_cache!
end
# Useful in development to update your local indices if:
# - something changed in the ES indices setup
# - you manually changed something in your database
def delete_all_indices_and_reindex_all
if Rails.env.production? # safety first, in case the method name was not clear enough
raise "This method recreates existing ES indices, which should never happen in production."
end
ActiveRecord::Base.connection.enable_query_cache!
without_loggers do
[Purchase, Link, Balance, Installment].each do |model|
print "Recreating index and importing #{model.name} => #{model.count} records..."
es_import_with_time(model, force: true)
end
print "Recreating index #{ConfirmedFollowerEvent.index_name} and importing confirmed followers => #{Follower.active.count} records..."
do_with_time do
ConfirmedFollowerEvent.__elasticsearch__.create_index!(force: true)
Follower.active.group(:followed_id).each do |follower|
DevTools.reimport_follower_events_for_user!(follower.user)
end
end
[ProductPageView].each do |model|
print "Recreating index #{model.index_name}"
do_with_time do
model.__elasticsearch__.create_index!(force: true)
end
end
end
nil
ensure
ActiveRecord::Base.connection.disable_query_cache!
end
# Warning: This method is destructive and should only be used:
# - When importing existing data for the very first time for a user
# - In tests
# - If the existing data was somehow seriously corrupted
#
# It's destructive because we only store in the DB the last time a follower was either
# confirmed (`confirmed_at`) OR destroyed (`deleted_at`).
# If someone was followed and unfollowed by the same person, running this will lose that information,
# and both the follow and unfollow will disappear from the stats.
def reimport_follower_events_for_user!(user)
cut_off_time = Time.current # prevents a race-condition that would result in adding the same event twice
EsClient.delete_by_query(
index: ConfirmedFollowerEvent.index_name,
body: {
query: {
bool: {
filter: [{ term: { followed_user_id: user.id } }],
must: [{ range: { timestamp: { lte: cut_off_time } } }]
}
}
}
)
user.followers.active.where("confirmed_at < ?", cut_off_time).find_each do |follower|
EsClient.index(
index: ConfirmedFollowerEvent.index_name,
id: SecureRandom.uuid,
body: {
name: "added",
timestamp: follower.confirmed_at,
follower_id: follower.id,
followed_user_id: follower.followed_id,
follower_user_id: follower.follower_user_id,
email: follower.email,
}
)
end
end
# Useful for use inside and outside this class to process large amount of data without logs
def without_loggers
es_logger = EsClient.transport.logger
ar_logger = ActiveRecord::Base.logger
EsClient.transport.logger = Logger.new(File::NULL)
ActiveRecord::Base.logger = Logger.new(File::NULL)
yield
ensure
EsClient.transport.logger = es_logger
ActiveRecord::Base.logger = ar_logger
end
private
def do_with_time(&block)
duration = Benchmark.measure(&block).real.round(2)
puts " done in #{duration}s"
end
def es_import_with_time(rel, force: false)
do_with_time { rel.import(force:) }
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/referrer.rb | lib/utilities/referrer.rb | # frozen_string_literal: true
class Referrer
DEFAULT_VALUE = "direct"
def self.extract_domain(url)
return DEFAULT_VALUE if url.blank? || url == "direct"
domain = begin
url = URI::DEFAULT_PARSER.unescape(url)
url.encode!("UTF-8", "binary", invalid: :replace, undef: :replace, replace: "")
url.gsub!(/\s+/, "")
host = URI.parse(url).host.try(:downcase)
return DEFAULT_VALUE if host.blank?
host.start_with?("www.") ? host[4..-1] : host
rescue URI::InvalidURIError, Encoding::CompatibilityError
end
domain.presence || DEFAULT_VALUE
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/compliance.rb | lib/utilities/compliance.rb | # frozen_string_literal: true
module Compliance
module Countries
ISO3166::Country.all.each do |country|
self.const_set(country.alpha3, country)
end
def self.mapping
ISO3166::Country.all.to_h { |country| [country.alpha2, country.common_name] }
end
def self.find_by_name(country_name)
return if country_name.blank?
ISO3166::Country.find_country_by_any_name(country_name)
end
def self.historical_names(country_name)
country = find_by_name(country_name)
return [] if country.nil?
([country.common_name] + (country.data["gumroad_historical_names"] || [])).uniq
end
# This list would be updated according to changes in OFAC regulation.
BLOCKED_COUNTRY_CODES = [
AFG, # Afghanistan
CUB, # Cuba
COD, # Congo, the Democratic Republic of the
CIV, # Côte d'Ivoire
IRQ, # Iraq
IRN, # Iran
LBN, # Lebanon
LBR, # Liberia
LBY, # Libya
MMR, # Myanmar
PRK, # North Korea
SOM, # Somalia
SDN, # Sudan
SYR, # Syrian Arabic Republic
YEM, # Yemen
ZWE, # Zimbabwe
].map(&:alpha2).freeze
private_constant :BLOCKED_COUNTRY_CODES
def self.blocked?(alpha2)
BLOCKED_COUNTRY_CODES.include?(alpha2)
end
# There are high levels of fraud originating in these countries.
RISK_PHYSICAL_BLOCKED_COUNTRY_CODES = [
ALB, # Albania,
BGD, # Bangladesh,
DZA, # Algeria,
IDN, # Indonesia,
LTU, # Lithuania,
MAR, # Morocco,
MMR, # Myanmar,
PAN, # Panama,
TUN, # Tunisia,
VNM, # Vietnam
].map(&:alpha2).freeze
private_constant :RISK_PHYSICAL_BLOCKED_COUNTRY_CODES
def self.risk_physical_blocked?(alpha2)
RISK_PHYSICAL_BLOCKED_COUNTRY_CODES.include?(alpha2)
end
def self.for_select
ISO3166::Country.all.map do |country|
name = blocked?(country.alpha2) ? "#{country.common_name} (not supported)" : country.common_name
[country.alpha2, name]
end.sort_by { |pair| pair.last }
end
GLOBE_SHOWING_AMERICAS_EMOJI = [127758].pack("U*")
private_constant :GLOBE_SHOWING_AMERICAS_EMOJI
def self.country_with_flag_by_name(country)
country_code = Compliance::Countries.find_by_name(country)&.alpha2
country_code.present? ?
"#{country_code.codepoints.map { |char| 127397 + char }.pack('U*')} #{country}" :
Compliance::Countries.elsewhere_with_flag
end
def self.elsewhere_with_flag
"#{GLOBE_SHOWING_AMERICAS_EMOJI} Elsewhere"
end
def self.subdivisions_for_select(alpha2)
case alpha2
when Compliance::Countries::USA.alpha2
Compliance::Countries::USA
.subdivisions.values
.filter_map { |subdivision| [subdivision.code, subdivision.name] if ["state", "district"].include?(subdivision.type) }
.sort_by { |pair| pair.last }
when Compliance::Countries::CAN.alpha2
Compliance::Countries::CAN.subdivisions.values.map { |subdivision| [subdivision.code, subdivision.name] }.sort_by { |pair| pair.last }
when Compliance::Countries::AUS.alpha2
Compliance::Countries::AUS.subdivisions.values.map { |subdivision| [subdivision.code, subdivision.name] }.sort_by { |pair| pair.last }
when Compliance::Countries::ARE.alpha2
Compliance::Countries::ARE.subdivisions.values.map { |subdivision| [subdivision.code, subdivision.translations["en"]] }.sort_by { |pair| pair.last }
when Compliance::Countries::MEX.alpha2
Compliance::Countries::MEX.subdivisions.values.map { |subdivision| [subdivision.code, subdivision.name] }.sort_by { |pair| pair.last }
when Compliance::Countries::IRL.alpha2
Compliance::Countries::IRL.subdivisions.values
.filter_map { |subdivision| [subdivision.code, subdivision.name] if subdivision.type == "county" }
.sort_by { |pair| pair.last }
when Compliance::Countries::BRA.alpha2
Compliance::Countries::BRA.subdivisions.values.map { |subdivision| [subdivision.code, subdivision.name] }.sort_by { |pair| pair.last }
else
raise ArgumentError, "Country subdivisions not supported"
end
end
# Returns the subdivision code given a country's alpha2 and a subdivision string.
#
# subdivision_str can be a code (like "CA") or name (like "California").
# subdivision_str is case insensitive
def self.find_subdivision_code(alpha2, subdivision_str)
return nil if subdivision_str.nil?
iso_country = ISO3166::Country[alpha2]
return nil if iso_country.nil?
return subdivision_str if iso_country.subdivisions.values.map(&:code).include?(subdivision_str)
iso_country.subdivisions.values.find { |subdivision| [subdivision.name, subdivision.translations["en"]].map(&:downcase).include?(subdivision_str.downcase) }&.code
end
# As a Merchant of Record, Gumroad is required to collect sales tax in these US states.
TAXABLE_US_STATE_CODES = %w(AR AZ CO CT DC GA HI IA IL IN KS KY LA MA MD MI MN NC ND NE NJ NV NY OH OK PA RI SD TN TX UT VT WA WI WV WY).freeze
def self.taxable_state?(state_code)
TAXABLE_US_STATE_CODES.include?(state_code)
end
EU_VAT_APPLICABLE_COUNTRY_CODES = [
AUT, # Austria,
BEL, # Belgium,
BGR, # Bulgaria,
HRV, # Croatia,
CYP, # Cyprus,
CZE, # Czechia,
DNK, # Denmark,
EST, # Estonia,
FIN, # Finland,
FRA, # France,
DEU, # Germany,
GRC, # Greece,
HUN, # Hungary,
IRL, # Ireland,
ITA, # Italy,
LVA, # Latvia,
LTU, # Lithuania,
LUX, # Luxembourg,
MLT, # Malta,
NLD, # Netherlands,
POL, # Poland,
PRT, # Portugal,
ROU, # Romania,
SVK, # Slovakia,
SVN, # Slovenia,
ESP, # Spain,
SWE, # Sweden,
GBR, # United Kingdom
].map(&:alpha2).freeze
NORWAY_VAT_APPLICABLE_COUNTRY_CODES = [
NOR, # Norway
].map(&:alpha2).freeze
GST_APPLICABLE_COUNTRY_CODES = [
AUS, # Australia
SGP, # Singapore
].map(&:alpha2).freeze
OTHER_TAXABLE_COUNTRY_CODES = [
CAN, # Canada
].map(&:alpha2).freeze
COUNTRIES_THAT_COLLECT_TAX_ON_ALL_PRODUCTS = [
Compliance::Countries::ISL.alpha2, # Iceland
Compliance::Countries::JPN.alpha2, # Japan
Compliance::Countries::NZL.alpha2, # New Zealand
Compliance::Countries::ZAF.alpha2, # South Africa
Compliance::Countries::CHE.alpha2, # Switzerland
Compliance::Countries::ARE.alpha2, # United Arab Emirates
Compliance::Countries::IND.alpha2, # India
].freeze
COUNTRIES_THAT_COLLECT_TAX_ON_DIGITAL_PRODUCTS_WITH_TAX_ID_PRO_VALIDATION = [
Compliance::Countries::BLR.alpha2, # Belarus
Compliance::Countries::CHL.alpha2, # Chile
Compliance::Countries::COL.alpha2, # Colombia
Compliance::Countries::CRI.alpha2, # Costa Rica
Compliance::Countries::ECU.alpha2, # Ecuador
Compliance::Countries::EGY.alpha2, # Egypt
Compliance::Countries::GEO.alpha2, # Georgia
Compliance::Countries::KAZ.alpha2, # Kazakhstan
Compliance::Countries::MYS.alpha2, # Malaysia
Compliance::Countries::MEX.alpha2, # Mexico
Compliance::Countries::MDA.alpha2, # Moldova
Compliance::Countries::MAR.alpha2, # Morocco
Compliance::Countries::RUS.alpha2, # Russia
Compliance::Countries::SAU.alpha2, # Saudi Arabia
Compliance::Countries::SRB.alpha2, # Serbia
Compliance::Countries::KOR.alpha2, # South Korea
Compliance::Countries::THA.alpha2, # Thailand
Compliance::Countries::TUR.alpha2, # Turkey
Compliance::Countries::UKR.alpha2, # Ukraine
Compliance::Countries::UZB.alpha2, # Uzbekistan
Compliance::Countries::VNM.alpha2 # Vietnam
].freeze
COUNTRIES_THAT_COLLECT_TAX_ON_DIGITAL_PRODUCTS_WITHOUT_TAX_ID_PRO_VALIDATION = [
Compliance::Countries::BHR.alpha2, # Bahrain
Compliance::Countries::KEN.alpha2, # Kenya
Compliance::Countries::NGA.alpha2, # Nigeria
Compliance::Countries::OMN.alpha2, # Oman
Compliance::Countries::TZA.alpha2, # Tanzania
].freeze
COUNTRIES_THAT_COLLECT_TAX_ON_DIGITAL_PRODUCTS = COUNTRIES_THAT_COLLECT_TAX_ON_DIGITAL_PRODUCTS_WITH_TAX_ID_PRO_VALIDATION + COUNTRIES_THAT_COLLECT_TAX_ON_DIGITAL_PRODUCTS_WITHOUT_TAX_ID_PRO_VALIDATION
end
DEFAULT_TOS_VIOLATION_REASON = "intellectual property infringement"
EXPLICIT_NSFW_TOS_VIOLATION_REASON = "Sexually explicit or fetish-related"
TOS_VIOLATION_REASONS = {
"A consulting service" => "consulting services",
"Adult (18+) content" => "adult content",
"Cell phone and electronics" => "cell phone and electronics",
"Credit repair" => "credit repair",
"Financial instruments & currency" => "financial instruments, advice or currency",
"General non-compliance" => "products that breach our ToS",
"IT support" => "computer and internet support services",
"Intellectual Property" => DEFAULT_TOS_VIOLATION_REASON,
"Online gambling" => "online gambling",
"Pharmaceutical & Health products" => "pharmaceutical and health products",
"Service billing" => "payment for services rendered",
"Web hosting" => "web hosting"
}.freeze
VAT_EXEMPT_REGIONS = ["Canarias", "Canary Islands"].freeze
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/geo_ip.rb | lib/utilities/geo_ip.rb | # frozen_string_literal: true
module GeoIp
class Result
attr_reader :country_name, :country_code, :region_name, :city_name, :postal_code, :latitude, :longitude
def initialize(country_name:, country_code:, region_name:, city_name:, postal_code:, latitude:, longitude:)
@country_name = country_name
@country_code = country_code
@region_name = region_name
@city_name = city_name
@postal_code = postal_code
@latitude = latitude
@longitude = longitude
end
end
def self.lookup(ip)
result = GEOIP.city(ip) rescue nil
return nil if result.nil?
Result.new(
country_name: santitize_string(result.country.name),
country_code: santitize_string(result.country.iso_code),
# Note we seem to be returning code in the past here, not the name
region_name: santitize_string(result.most_specific_subdivision&.iso_code),
city_name: santitize_string(result.city.name),
postal_code: santitize_string(result.postal.code),
latitude: santitize_string(result.location.latitude),
longitude: santitize_string(result.location.longitude)
)
end
def self.santitize_string(value)
value.try(:encode, "UTF-8", invalid: :replace, replace: "?")
rescue Encoding::UndefinedConversionError
"INVALID"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/o_embed_finder.rb | lib/utilities/o_embed_finder.rb | # frozen_string_literal: true
class OEmbedFinder
SOUNDCLOUD_PARAMS = %w[auto_play show_artwork show_comments buying sharing download show_playcount show_user liking].freeze
# limited oembed urls for mobile (we don't know if mobile can support other urls)
MOBILE_URL_REGEXES = [%r{player.vimeo.com/video/\d+}, %r{https://w.soundcloud.com/player}, %r{https://www.youtube.com/embed}].freeze
def self.embeddable_from_url(new_url, maxwidth = AssetPreview::DEFAULT_DISPLAY_WIDTH)
OEmbed::Providers.register_all
wistia = OEmbed::Provider.new("http://fast.wistia.com/oembed")
wistia << "http://*.wistia.com/*"
wistia << "http://*.wistia.net/*"
wistia << "https://*.wistia.com/*"
wistia << "https://*.wistia.net/*"
OEmbed::Providers.register(wistia)
sketchfab = OEmbed::Provider.new("https://sketchfab.com/oembed")
sketchfab << "http://sketchfab.com/models/*"
sketchfab << "https://sketchfab.com/models/*"
OEmbed::Providers.register(sketchfab)
begin
res = OEmbed::Providers.get(new_url, maxwidth:)
rescue StandardError
return nil
end
if res.video? || res.rich?
html = res.html
if /api.soundcloud.com/.match?(html)
html = html.gsub("http://w.soundcloud.com", "https://w.soundcloud.com")
payload = SOUNDCLOUD_PARAMS.map { |k| "#{k}=false" }.join("&")
html = html.gsub(/show_artwork=true/, payload)
elsif %r{youtube.com/embed}.match?(html)
html = html.gsub("http://", "https://")
html = html.gsub(/feature=oembed/, "feature=oembed&showinfo=0&controls=0&rel=0")
elsif html.include?("wistia")
html = html.gsub("http://", "https://")
elsif html.include?("sketchfab")
html = html.gsub("http://", "https://")
elsif html.include?("vimeo")
html = html.gsub("http://", "https://")
end
info_fields = %w[width height thumbnail_url]
fields = res.fields.select { |k, _v| info_fields.include?(k) }
{ html:, info: fields }
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/lib/utilities/text_scrubber.rb | lib/utilities/text_scrubber.rb | # frozen_string_literal: true
class TextScrubber
def self.format(text, opts = {})
Loofah.fragment(text).to_text(opts).strip
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.