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/business/payments/integrations/paypal_partner_rest_credentials_spec.rb | spec/business/payments/integrations/paypal_partner_rest_credentials_spec.rb | # frozen_string_literal: true
describe PaypalPartnerRestCredentials do
describe "#auth_token" do
context "when a cached token is present" do
before do
@some_auth_token = "random token"
allow_any_instance_of(described_class).to receive(:load_token).and_return(@some_auth_token)
end
it "does not initiate an API call and returns the authorization token header value from the cache" do
expect_any_instance_of(described_class).to_not receive(:request_for_api_token)
auth_token = described_class.new.auth_token
expect(auth_token).to eq(@some_auth_token)
end
end
context "when a cached token is absent", :vcr do
before do
allow_any_instance_of(described_class).to receive(:load_token).and_return(nil)
end
it "initiates an API call and returns a valid authorization token header value" do
expect_any_instance_of(described_class).to receive(:request_for_api_token).and_call_original
auth_token = described_class.new.auth_token
expect(auth_token).to be_an_instance_of(String)
expect(auth_token).to match(/^[^\s]+ [^\s]+$/) # A concatenation of two strings with a space
end
it "raises an exception on API call failure" do
allow(described_class).to receive(:post).and_raise(SocketError)
expect do
described_class.new.auth_token
end.to raise_error(SocketError)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/merchant_registration/stripe/stripe_merchant_account_manager_spec.rb | spec/business/payments/merchant_registration/stripe/stripe_merchant_account_manager_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StripeMerchantAccountManager, :vcr do
include StripeMerchantAccountHelper
API_VERSION = Stripe.api_version
let(:user) { create(:user, unpaid_balance_cents: 10, email: "chuck@gum.com", username: "chuck") }
describe "#create_account" do
describe "all info provided of an individual" do
let(:user_compliance_info) { create(:user_compliance_info, user:) }
let(:bank_account) { create(:ach_account_stripe_succeed, user:) }
let(:tos_agreement) { create(:tos_agreement, user:) }
before do
user_compliance_info
bank_account
travel_to(Time.find_zone("UTC").local(2015, 4, 1)) do
tos_agreement
end
end
let(:expected_account_params) do
{
type: "custom",
metadata: {
user_id: user.external_id,
tos_agreement_id: tos_agreement.external_id,
user_compliance_info_id: user_compliance_info.external_id,
bank_account_id: bank_account.external_id
},
country: "US",
tos_acceptance: { date: 1427846400, ip: "54.234.242.13" },
business_type: "individual",
business_profile: {
name: user_compliance_info.legal_entity_name,
url: user.business_profile_url,
product_description: user_compliance_info.legal_entity_name
},
individual: {
address: {
line1: "address_full_match",
line2: nil,
city: "San Francisco",
state: "California",
postal_code: "94107",
country: "US"
},
id_number: "000000000",
dob: { day: 1, month: 1, year: 1901 },
first_name: "Chuck",
last_name: "Bartowski",
phone: "0000000000",
email: user.email,
},
default_currency: "usd",
bank_account: {
country: "US",
currency: "usd",
routing_number: "110000000",
account_number: "000123456789"
},
settings: {
payouts: {
schedule: {
interval: "manual"
},
debit_negative_balances: true
}
},
requested_capabilities: StripeMerchantAccountManager::REQUESTED_CAPABILITIES
}
end
it "creates an account at stripe with all the params" do
allow_any_instance_of(User).to receive(:external_id).and_return("4585558742839")
allow_any_instance_of(UserComplianceInfo).to receive(:external_id).and_return("G_-mnBf9b1j9A7a4ub4nFQ==")
allow_any_instance_of(TosAgreement).to receive(:external_id).and_return("G_-mnBf9b1j9A7a4ub4nFQ==")
allow_any_instance_of(BankAccount).to receive(:external_id).and_return("G_-mnBf9b1j9A7a4ub4nFQ==")
expect(Stripe::Account).to receive(:create).with(expected_account_params).and_call_original
merchant_account = subject.create_account(user, passphrase: "1234")
stripe_account = Stripe::Account.retrieve(merchant_account.charge_processor_merchant_id)
expect(stripe_account["metadata"]["user_id"]).to eq(user.external_id)
expect(stripe_account["metadata"]["user_compliance_info_id"]).to eq(user_compliance_info.external_id)
expect(stripe_account["metadata"]["tos_agreement_id"]).to eq(tos_agreement.external_id)
expect(stripe_account["metadata"]["bank_account_id"]).to eq(bank_account.external_id)
end
it "returns a merchant account" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id)
expect(merchant_account.charge_processor_merchant_id).to be_present
end
it "returns a merchant account with country set" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.country).to eq("US")
end
it "returns a merchant account with currency set" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.currency).to eq("usd")
end
it "saves the stripe connect account id on our bank account record" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_connect_account_id).to eq(merchant_account.charge_processor_merchant_id)
end
it "saves the stripe bank account id on our bank account record" do
subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_bank_account_id).to match(/ba_[a-zA-Z0-9]+/)
end
it "saves the stripe bank account fingerprint on our bank account record" do
subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_fingerprint).to match(/[a-zA-Z0-9]+/)
end
it "raises the Stripe::InvalidRequestError" do
error_message = "Invalid account number: must contain only digits, and be at most 12 digits long"
allow(Stripe::Account).to receive(:create).and_raise(Stripe::InvalidRequestError.new(error_message, nil))
expect do
subject.create_account(user, passphrase: "1234")
end.to raise_error(Stripe::InvalidRequestError)
end
context "when user compliance info contains whitespaces" do
let(:user_compliance_info) do
create(:user_compliance_info,
user:,
first_name: " Chuck ",
last_name: " Bartowski ",
street_address: " address_full_match",
zip_code: " 94107 ",
city: "San Francisco ")
end
it "strips out params whitespaces" do
expect(Stripe::Account).to receive(:create).with(expected_account_params).and_call_original
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id)
expect(merchant_account.charge_processor_merchant_id).to be_present
end
end
context "with stripe connect account" do
before do
allow_any_instance_of(MerchantAccount).to receive(:is_a_stripe_connect_account?).and_return(true)
end
it "generates default abandoned cart workflow" do
expect(DefaultAbandonedCartWorkflowGeneratorService).to receive(:new).with(seller: user).and_call_original
expect_any_instance_of(DefaultAbandonedCartWorkflowGeneratorService).to receive(:generate)
subject.create_account(user, passphrase: "1234")
end
end
context "with non-connect account" do
before do
allow_any_instance_of(MerchantAccount).to receive(:is_a_stripe_connect_account?).and_return(false)
end
it "does not generate abandoned cart workflow" do
expect(DefaultAbandonedCartWorkflowGeneratorService).not_to receive(:new)
subject.create_account(user, passphrase: "1234")
end
end
end
describe "all info provided of an individual with a US Debit card" do
let(:user_compliance_info) { create(:user_compliance_info, user:) }
let(:bank_account) { create(:card_bank_account, user:) }
let(:tos_agreement) { create(:tos_agreement, user:) }
before do
user_compliance_info
bank_account
travel_to(Time.find_zone("UTC").local(2015, 4, 1)) do
tos_agreement
end
end
let(:expected_account_params) do
{
type: "custom",
metadata: {
user_id: user.external_id,
tos_agreement_id: tos_agreement.external_id,
user_compliance_info_id: user_compliance_info.external_id
},
country: "US",
tos_acceptance: { date: 1427846400, ip: "54.234.242.13" },
business_type: "individual",
business_profile: {
name: user_compliance_info.legal_entity_name,
url: user.business_profile_url,
product_description: user_compliance_info.legal_entity_name
},
individual: {
address: {
line1: "address_full_match",
line2: nil,
city: "San Francisco",
state: "California",
postal_code: "94107",
country: "US"
},
id_number: "000000000",
dob: { day: 1, month: 1, year: 1901 },
first_name: "Chuck",
last_name: "Bartowski",
phone: "0000000000",
email: user.email,
},
default_currency: "usd",
requested_capabilities: StripeMerchantAccountManager::REQUESTED_CAPABILITIES
}
end
let(:expected_bank_account_params) do
{
metadata: {
bank_account_id: bank_account.external_id
},
bank_account: /^tok_/,
settings: {
payouts: {
schedule: {
interval: "manual"
},
debit_negative_balances: true
}
}
}
end
it "creates an account at stripe with all the account params" do
expect(Stripe::Account).to receive(:create).with(expected_account_params).and_call_original
subject.create_account(user, passphrase: "1234")
end
it "returns a merchant account" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id)
expect(merchant_account.charge_processor_merchant_id).to be_present
end
it "returns a merchant account with country set" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.country).to eq("US")
end
it "returns a merchant account with currency set" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.currency).to eq("usd")
end
end
describe "all info provided of an individual but their bank account doesn't match the default currency of the country" do
before do
allow(Rails.env).to receive(:production?).and_return(true)
end
let(:user_compliance_info) { create(:user_compliance_info, user:, country: "Canada") }
let(:bank_account) { create(:ach_account_stripe_succeed, user:) }
let(:tos_agreement) { create(:tos_agreement, user:) }
before do
user_compliance_info
bank_account
travel_to(Time.find_zone("UTC").local(2015, 4, 1)) do
tos_agreement
end
end
it "raises an error" do
expect { subject.create_account(user, passphrase: "1234") }.to raise_error(MerchantRegistrationUserNotReadyError)
end
end
describe "all info provided of an individual and empty string business fields" do
let(:user_compliance_info) { create(:user_compliance_info, user:, business_name: "", business_tax_id: "") }
let(:bank_account) { create(:ach_account_stripe_succeed, user:) }
let(:tos_agreement) { create(:tos_agreement, user:) }
before do
user_compliance_info
bank_account
travel_to(Time.find_zone("UTC").local(2015, 4, 1)) do
tos_agreement
end
end
let(:expected_account_params) do
{
type: "custom",
metadata: {
user_id: user.external_id,
tos_agreement_id: tos_agreement.external_id,
user_compliance_info_id: user_compliance_info.external_id,
bank_account_id: bank_account.external_id
},
country: "US",
tos_acceptance: { date: 1427846400, ip: "54.234.242.13" },
business_profile: {
name: user_compliance_info.legal_entity_name,
url: user.business_profile_url,
product_description: user_compliance_info.legal_entity_name
},
business_type: "individual",
individual: {
address: {
line1: "address_full_match",
line2: nil,
city: "San Francisco",
state: "California",
postal_code: "94107",
country: "US"
},
id_number: "000000000",
dob: { day: 1, month: 1, year: 1901 },
first_name: "Chuck",
last_name: "Bartowski",
phone: "0000000000",
email: user.email,
},
default_currency: "usd",
bank_account: {
country: "US",
currency: "usd",
routing_number: "110000000",
account_number: "000123456789"
},
settings: {
payouts: {
schedule: {
interval: "manual"
},
debit_negative_balances: true
}
},
requested_capabilities: StripeMerchantAccountManager::REQUESTED_CAPABILITIES
}
end
it "creates an account at stripe with all the params" do
expect(Stripe::Account).to receive(:create).with(expected_account_params).and_call_original
subject.create_account(user, passphrase: "1234")
end
it "returns a merchant account" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id)
expect(merchant_account.charge_processor_merchant_id).to be_present
end
it "returns a merchant account with country set" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.country).to eq("US")
end
it "returns a merchant account with currency set" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.currency).to eq("usd")
end
it "saves the stripe connect account id on our bank account record" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_connect_account_id).to eq(merchant_account.charge_processor_merchant_id)
end
it "saves the stripe bank account id on our bank account record" do
subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_bank_account_id).to match(/ba_[a-zA-Z0-9]+/)
end
it "saves the stripe bank account fingerprint on our bank account record" do
subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_fingerprint).to match(/[a-zA-Z0-9]+/)
end
end
describe "all info provided of a business" do
let(:user_compliance_info) { create(:user_compliance_info_business, user:) }
let(:bank_account) { create(:ach_account_stripe_succeed, user:) }
let(:tos_agreement) { create(:tos_agreement, user:) }
before do
user_compliance_info
bank_account
travel_to(Time.find_zone("UTC").local(2015, 4, 1)) do
tos_agreement
end
end
let(:expected_account_params) do
{
type: "custom",
metadata: {
user_id: user.external_id,
tos_agreement_id: tos_agreement.external_id,
user_compliance_info_id: user_compliance_info.external_id,
bank_account_id: bank_account.external_id
},
country: "US",
tos_acceptance: { date: 1427846400, ip: "54.234.242.13" },
business_profile: {
name: user_compliance_info.legal_entity_name,
url: user.business_profile_url,
product_description: user_compliance_info.legal_entity_name
},
business_type: "company",
company: {
name: "Buy More, LLC",
address: {
line1: "address_full_match",
line2: nil,
city: "Burbank",
state: "California",
postal_code: "91506",
country: "US"
},
tax_id: "000000000",
phone: "0000000000",
directors_provided: true,
executives_provided: true
},
default_currency: "usd",
bank_account: {
country: "US",
currency: "usd",
routing_number: "110000000",
account_number: "000123456789"
},
settings: {
payouts: {
schedule: {
interval: "manual"
},
debit_negative_balances: true
}
},
requested_capabilities: StripeMerchantAccountManager::REQUESTED_CAPABILITIES
}
end
let(:expected_person_params) do
{
address: {
line1: "address_full_match",
line2: nil,
city: "San Francisco",
state: "California",
postal_code: "94107",
country: "US"
},
id_number: "000000000",
dob: { day: 1, month: 1, year: 1901 },
first_name: "Chuck",
last_name: "Bartowski",
phone: "0000000000",
email: user.email,
relationship: { representative: true, owner: true, title: "CEO", percent_ownership: 100 }
}
end
it "creates an account at stripe with all the params" do
expect(Stripe::Account).to receive(:create).with(expected_account_params).and_call_original
expect(Stripe::Account).to receive(:create_person).with(anything, expected_person_params).and_call_original
subject.create_account(user, passphrase: "1234")
end
it "returns a merchant account" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id)
expect(merchant_account.charge_processor_merchant_id).to be_present
end
end
describe "all info provided of an individual (non-US)" do
let(:user_compliance_info) { create(:user_compliance_info, user:, zip_code: "M4C 1T2", city: "Toronto", state: nil, country: "Canada") }
let(:bank_account) { create(:ach_account_stripe_succeed, user:) }
let(:tos_agreement) { create(:tos_agreement, user:) }
before do
user_compliance_info
bank_account
travel_to(Time.find_zone("UTC").local(2015, 4, 1)) do
tos_agreement
end
end
let(:expected_account_params) do
{
type: "custom",
country: "CA",
metadata: {
user_id: user.external_id,
tos_agreement_id: tos_agreement.external_id,
user_compliance_info_id: user_compliance_info.external_id,
bank_account_id: bank_account.external_id
},
tos_acceptance: { date: 1427846400, ip: "54.234.242.13" },
default_currency: "cad",
business_type: "individual",
business_profile: {
name: user_compliance_info.legal_entity_name,
url: user.business_profile_url,
product_description: user_compliance_info.legal_entity_name,
support_phone: nil,
},
individual: {
address: {
line1: "address_full_match",
line2: nil,
city: "Toronto",
state: nil,
postal_code: "M4C 1T2",
country: "CA"
},
id_number: "000000000",
dob: { day: 1, month: 1, year: 1901 },
first_name: "Chuck",
last_name: "Bartowski",
phone: "0000000000",
email: user.email,
relationship: { title: "CEO" },
},
bank_account: {
country: "US",
currency: "usd",
routing_number: "110000000",
account_number: "000123456789"
},
settings: {
payouts: {
schedule: {
interval: "manual"
},
debit_negative_balances: true
}
},
requested_capabilities: StripeMerchantAccountManager::REQUESTED_CAPABILITIES
}
end
it "creates an account at stripe with all the params" do
expect(Stripe::Account).to receive(:create).with(expected_account_params).and_call_original
subject.create_account(user, passphrase: "1234")
end
it "returns a merchant account" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id)
expect(merchant_account.charge_processor_merchant_id).to be_present
end
it "returns a merchant account with country set" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.country).to eq("CA")
end
it "returns a merchant account with currency set" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.currency).to eq("cad")
end
it "saves the stripe connect account id on our bank account record" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_connect_account_id).to eq(merchant_account.charge_processor_merchant_id)
end
it "saves the stripe bank account id on our bank account record" do
subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_bank_account_id).to match(/ba_[a-zA-Z0-9]+/)
end
it "saves the stripe bank account fingerprint on our bank account record" do
subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_fingerprint).to match(/[a-zA-Z0-9]+/)
end
end
describe "all info provided of a business (non-US)" do
let(:user_compliance_info) do
create(:user_compliance_info_business, user:, business_type: "private_corporation",
city: "Toronto", state: nil, country: "Canada", zip_code: "M4C 1T2", business_zip_code: "M4C 1T2",
business_city: "Toronto", business_state: nil, business_country: "Canada")
end
let(:bank_account) { create(:ach_account_stripe_succeed, user:) }
let(:tos_agreement) { create(:tos_agreement, user:) }
before do
user_compliance_info
bank_account
travel_to(Time.find_zone("UTC").local(2015, 4, 1)) do
tos_agreement
end
end
let(:expected_account_params) do
{
type: "custom",
country: "CA",
metadata: {
user_id: user.external_id,
tos_agreement_id: tos_agreement.external_id,
user_compliance_info_id: user_compliance_info.external_id,
bank_account_id: bank_account.external_id
},
tos_acceptance: { date: 1427846400, ip: "54.234.242.13" },
default_currency: "cad",
business_type: "company",
business_profile: {
name: user_compliance_info.legal_entity_name,
url: user.business_profile_url,
product_description: user_compliance_info.legal_entity_name,
support_phone: "0000000000",
},
company: {
address: {
line1: "address_full_match",
line2: nil,
city: "Toronto",
state: nil,
postal_code: "M4C 1T2",
country: "CA"
},
name: "Buy More, LLC",
tax_id: "000000000",
phone: "0000000000",
structure: "private_corporation",
directors_provided: true,
executives_provided: true
},
bank_account: {
country: "US",
currency: "usd",
routing_number: "110000000",
account_number: "000123456789"
},
settings: {
payouts: {
schedule: {
interval: "manual"
},
debit_negative_balances: true
}
},
requested_capabilities: StripeMerchantAccountManager::REQUESTED_CAPABILITIES
}
end
let(:expected_person_params) do
{
id_number: "000000000",
dob: { day: 1, month: 1, year: 1901 },
first_name: "Chuck",
last_name: "Bartowski",
relationship: { representative: true, owner: true, percent_ownership: 100, title: "CEO" },
address:
{
line1: "address_full_match",
line2: nil,
city: "Toronto",
state: nil,
postal_code: "M4C 1T2",
country: "CA"
},
phone: "0000000000",
email: user.email,
}
end
it "creates an account at stripe with all the params" do
expect(Stripe::Account).to receive(:create).with(expected_account_params).and_call_original
expect(Stripe::Account).to receive(:create_person).with(anything, expected_person_params).and_call_original
subject.create_account(user, passphrase: "1234")
end
it "returns a merchant account" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id)
expect(merchant_account.charge_processor_merchant_id).to be_present
end
end
describe "all info provided of an individual (UK/EU)" do
let(:user_compliance_info) { create(:user_compliance_info, user:, city: "London", street_address: "A4", state: nil, zip_code: "WC2N 5DU", country: "United Kingdom") }
let(:bank_account) { create(:ach_account_stripe_succeed, user:) }
let(:tos_agreement) { create(:tos_agreement, user:) }
before do
user_compliance_info
bank_account
travel_to(Time.find_zone("UTC").local(2015, 4, 1)) do
tos_agreement
end
end
let(:expected_account_params) do
{
type: "custom",
country: "GB",
metadata: {
user_id: user.external_id,
tos_agreement_id: tos_agreement.external_id,
user_compliance_info_id: user_compliance_info.external_id,
bank_account_id: bank_account.external_id
},
tos_acceptance: { date: 1427846400, ip: "54.234.242.13" },
default_currency: "gbp",
business_type: "individual",
business_profile: {
name: user_compliance_info.legal_entity_name,
url: user.business_profile_url,
product_description: user_compliance_info.legal_entity_name
},
individual: {
address: {
line1: "A4",
line2: nil,
city: "London",
state: nil,
postal_code: "WC2N 5DU",
country: "GB"
},
id_number: "000000000",
dob: { day: 1, month: 1, year: 1901 },
first_name: "Chuck",
last_name: "Bartowski",
phone: "0000000000",
email: user.email,
},
bank_account: {
country: "US",
currency: "usd",
routing_number: "110000000",
account_number: "000123456789"
},
settings: {
payouts: {
schedule: {
interval: "manual"
},
debit_negative_balances: true
}
},
requested_capabilities: StripeMerchantAccountManager::REQUESTED_CAPABILITIES
}
end
it "creates an account at stripe with all the params" do
expect(Stripe::Account).to receive(:create).with(expected_account_params).and_call_original
subject.create_account(user, passphrase: "1234")
end
it "returns a merchant account" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id)
expect(merchant_account.charge_processor_merchant_id).to be_present
end
it "returns a merchant account with country set" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.country).to eq("GB")
end
it "returns a merchant account with currency set" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(merchant_account.currency).to eq("gbp")
end
it "saves the stripe connect account id on our bank account record" do
merchant_account = subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_connect_account_id).to eq(merchant_account.charge_processor_merchant_id)
end
it "saves the stripe bank account id on our bank account record" do
subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_bank_account_id).to match(/ba_[a-zA-Z0-9]+/)
end
it "saves the stripe bank account fingerprint on our bank account record" do
subject.create_account(user, passphrase: "1234")
expect(bank_account.reload.stripe_fingerprint).to match(/[a-zA-Z0-9]+/)
end
end
describe "all info provided of a business (UK/EU)" do
let(:user_compliance_info) do
create(:user_compliance_info_business, user:,
city: "London", state: nil, country: "United Kingdom", zip_code: "WC2N 5DU", business_zip_code: "WC2N 5DU",
business_city: "London", business_state: nil, business_country: "United Kingdom")
end
let(:bank_account) { create(:ach_account_stripe_succeed, user:) }
let(:tos_agreement) { create(:tos_agreement, user:) }
before do
user_compliance_info
bank_account
travel_to(Time.find_zone("UTC").local(2015, 4, 1)) do
tos_agreement
end
end
let(:expected_account_params) do
{
type: "custom",
country: "GB",
metadata: {
user_id: user.external_id,
tos_agreement_id: tos_agreement.external_id,
user_compliance_info_id: user_compliance_info.external_id,
bank_account_id: bank_account.external_id
},
tos_acceptance: { date: 1427846400, ip: "54.234.242.13" },
default_currency: "gbp",
business_type: "company",
business_profile: {
name: user_compliance_info.legal_entity_name,
url: user.business_profile_url,
product_description: user_compliance_info.legal_entity_name
},
company: {
name: "Buy More, LLC",
tax_id: "000000000",
address: {
line1: "address_full_match",
line2: nil,
city: "London",
state: nil,
postal_code: "WC2N 5DU",
country: "GB"
},
phone: "0000000000",
directors_provided: true,
executives_provided: true
},
bank_account: {
country: "US",
currency: "usd",
routing_number: "110000000",
account_number: "000123456789"
},
settings: {
payouts: {
schedule: {
interval: "manual"
},
debit_negative_balances: true
}
},
requested_capabilities: StripeMerchantAccountManager::REQUESTED_CAPABILITIES
}
end
let(:expected_person_params) do
{
id_number: "000000000",
dob: { day: 1, month: 1, year: 1901 },
first_name: "Chuck",
last_name: "Bartowski",
relationship: { representative: true, owner: true, percent_ownership: 100, title: "CEO" },
address: {
line1: "address_full_match",
line2: nil,
city: "London",
state: nil,
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/merchant_registration/paypal/paypal_merchant_account_manager_spec.rb | spec/business/payments/merchant_registration/paypal/paypal_merchant_account_manager_spec.rb | # frozen_string_literal: true
describe PaypalMerchantAccountManager, :vcr do
describe "#create_partner_referral" do
let(:user) { create(:user) }
context "when partner referral request is successful" do
before do
@response = described_class.new.create_partner_referral(user, "http://redirecturl.com")
end
it "returns success response data" do
expect(@response[:success]).to eq(true)
expect(@response[:redirect_url]).to match("www.sandbox.paypal.com")
end
end
context "when partner referral request fails" do
before do
allow_any_instance_of(described_class).to receive(:authorization_header).and_return(" ")
@response = described_class.new.create_partner_referral(user, "http://redirecturl.com")
end
it "returns failure response data" do
expect(@response[:success]).to eq(false)
expect(@response[:error_message]).to eq("Please try again later.")
end
end
end
describe "handle_paypal_event" do
context "when event type is #{PaypalEventType::MERCHANT_PARTNER_CONSENT_REVOKED}" do
let(:paypal_event) do { "id" => "WH-59L56223MP7193543-0JE01801LE024204Y", "event_version" => "1.0",
"create_time" => "2017-09-29T04:45:38.473Z", "resource_type" => "partner-consent", "event_type" => "MERCHANT.PARTNER-CONSENT.REVOKED", "summary" => "The Account setup consents has been revoked or the merchant account is closed", "resource" => { "merchant_id" => "FQ9WM47T82UAS", "tracking_id" => "7674947449674" }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-59L56223MP7193543-0JE01801LE024204Y", "rel" => "self", "method" => "GET" }, { "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-59L56223MP7193543-0JE01801LE024204Y/resend", "rel" => "resend", "method" => "POST" }], "foreign_webhook" => { "id" => "WH-59L56223MP7193543-0JE01801LE024204Y", "event_version" => "1.0", "create_time" => "2017-09-29T04:45:38.473Z", "resource_type" => "partner-consent", "event_type" => "MERCHANT.PARTNER-CONSENT.REVOKED", "summary" => "The Account setup consents has been revoked or the merchant account is closed", "resource" => { "merchant_id" => "FQ9WM47T82UAS", "tracking_id" => "7674947449674" }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-59L56223MP7193543-0JE01801LE024204Y", "rel" => "self", "method" => "GET" }, { "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-59L56223MP7193543-0JE01801LE024204Y/resend", "rel" => "resend", "method" => "POST" }] } } end
context "when merchant account is not present" do
it "does nothing" do
expect do
described_class.new.handle_paypal_event(paypal_event)
end.not_to raise_error
end
end
context "when merchant account is present" do
before do
@merchant_account = create(:merchant_account_paypal, charge_processor_merchant_id: paypal_event["resource"]["merchant_id"])
end
it "marks the merchant account as deleted" do
described_class.new.handle_paypal_event(paypal_event)
@merchant_account.reload
expect(@merchant_account.alive?).to be(false)
end
it "marks all the merchant accounts as deleted if there are more than one connected to the same paypal account" do
merchant_account_2 = create(:merchant_account_paypal, charge_processor_merchant_id: paypal_event["resource"]["merchant_id"])
described_class.new.handle_paypal_event(paypal_event)
expect(@merchant_account.reload.alive?).to be(false)
expect(merchant_account_2.reload.alive?).to be(false)
end
it "does nothing if there are no alive merchant accounts for the paypal account" do
@merchant_account.mark_deleted!
expect(@merchant_account.reload.alive?).to be(false)
expect_any_instance_of(MerchantAccount).not_to receive(:delete_charge_processor_account!)
expect(MerchantRegistrationMailer).not_to receive(:account_deauthorized_to_user)
described_class.new.handle_paypal_event(paypal_event)
end
context "when user is merchant migration enabled" do
before do
@user = @merchant_account.user
@user.update_attribute(:check_merchant_account_is_linked, true)
create(:user_compliance_info, user: @user)
@product = create(:product_with_pdf_file, purchase_disabled_at: Time.current, user: @user)
@product.publish!
end
it "marks the merchant account as deleted and disables sales" do
expect(MerchantRegistrationMailer).to receive(:account_deauthorized_to_user).with(
@user.id,
@merchant_account.charge_processor_id
).and_call_original
described_class.new.handle_paypal_event(paypal_event)
@product.reload
expect(@product.purchase_disabled_at).to be_nil
end
end
end
end
context "when event type is #{PaypalEventType::MERCHANT_ONBOARDING_COMPLETED}" do
context "when tracking_id is absent in the webhook payload" do
let(:paypal_event) { { "id" => "WH-4WS08821J7410062M-6JM26615AM999645H", "event_version" => "1.0", "create_time" => "2021-01-09T17:43:54.797Z", "resource_type" => "merchant-onboarding", "event_type" => "MERCHANT.ONBOARDING.COMPLETED", "summary" => "The merchant account setup is completed", "resource" => { "partner_client_id" => "AeuUyDUbnlHJnLRfnK2RUSl4BlaVSyRtBpoaak7YeCyZv1dcFjAAgWHUTiGAmRCDfkCwLaOrHgdT2Apv", "links" => [{ "method" => "GET", "rel" => "self", "description" => "Get the merchant status information of merchants onboarded by this partner", "href" => "https://api.paypal.com/v1/customer/partners/Y9TEHAMRZ4T7L/merchant-integrations/V74ZDABEJCZ7C" }], "merchant_id" => "V74ZDABEJCZ7C" }, "links" => [{ "href" => "https://api.paypal.com/v1/notifications/webhooks-events/WH-4WS08821J7410062M-6JM26615AM999645H", "rel" => "self", "method" => "GET" }, { "href" => "https://api.paypal.com/v1/notifications/webhooks-events/WH-4WS08821J7410062M-6JM26615AM999645H/resend", "rel" => "resend", "method" => "POST" }], "foreign_webhook" => { "id" => "WH-4WS08821J7410062M-6JM26615AM999645H", "event_version" => "1.0", "create_time" => "2021-01-09T17:43:54.797Z", "resource_type" => "merchant-onboarding", "event_type" => "MERCHANT.ONBOARDING.COMPLETED", "summary" => "The merchant account setup is completed", "resource" => { "partner_client_id" => "AeuUyDUbnlHJnLRfnK2RUSl4BlaVSyRtBpoaak7YeCyZv1dcFjAAgWHUTiGAmRCDfkCwLaOrHgdT2Apv", "links" => [{ "method" => "GET", "rel" => "self", "description" => "Get the merchant status information of merchants onboarded by this partner", "href" => "https://api.paypal.com/v1/customer/partners/Y9TEHAMRZ4T7L/merchant-integrations/V74ZDABEJCZ7C" }], "merchant_id" => "V74ZDABEJCZ7C" }, "links" => [{ "href" => "https://api.paypal.com/v1/notifications/webhooks-events/WH-4WS08821J7410062M-6JM26615AM999645H", "rel" => "self", "method" => "GET" }, { "href" => "https://api.paypal.com/v1/notifications/webhooks-events/WH-4WS08821J7410062M-6JM26615AM999645H/resend", "rel" => "resend", "method" => "POST" }] } } }
it "does nothing" do
expect do
described_class.new.handle_paypal_event(paypal_event)
end.not_to raise_error
end
end
context "when merchant account record is not present" do
let!(:user) { create(:user) }
let(:paypal_event) do { "event_type" => PaypalEventType::MERCHANT_ONBOARDING_COMPLETED,
"resource" => { "merchant_id" => "GSQ5PDPXZCWGW",
"tracking_id" => user.external_id } } end
it "does not create a new merchant account record" do
expect do
described_class.new.handle_paypal_event(paypal_event)
end.not_to change { MerchantAccount.count }
end
end
end
context "when event type is #{PaypalEventType::MERCHANT_CAPABILITY_UPDATED}" do
let(:paypal_event) do { "event_type" => PaypalEventType::MERCHANT_CAPABILITY_UPDATED,
"resource" => { "merchant_id" => "GSQ5PDPXZCWGW",
"tracking_id" => create(:user).external_id } } end
context "when merchant account record is not present" do
it "does not create a new merchant account record" do
expect do
described_class.new.handle_paypal_event(paypal_event)
end.not_to change { MerchantAccount.count }
end
end
context "when merchant account record is present" do
before do
@merchant_account = create(:merchant_account_paypal,
charge_processor_merchant_id: paypal_event["resource"]["merchant_id"],
user: User.find_by_external_id(paypal_event["resource"]["tracking_id"]))
@merchant_account.user.mark_compliant!(author_name: "Iffy")
allow_any_instance_of(User).to receive(:sales_cents_total).and_return(100_00)
create(:payment_completed, user: @merchant_account.user)
end
it "does not re-enable if merchant account is deleted" do
@merchant_account.mark_deleted!
expect(@merchant_account.reload.alive?).to be(false)
described_class.new.handle_paypal_event(paypal_event)
expect(@merchant_account.reload.alive?).to be(false)
end
it "updates the merchant account if it is not deleted" do
@merchant_account.charge_processor_deleted_at = 1.day.ago
@merchant_account.save!
expect(@merchant_account.alive?).to be(true)
expect(@merchant_account.charge_processor_alive?).to be(false)
described_class.new.handle_paypal_event(paypal_event)
@merchant_account.reload
expect(@merchant_account.alive?).to be(true)
expect(@merchant_account.charge_processor_alive?).to be(true)
end
end
end
context "when event type is #{PaypalEventType::MERCHANT_SUBSCRIPTION_UPDATED}" do
context "when merchant account record is not present" do
let(:paypal_event) do { "event_type" => PaypalEventType::MERCHANT_SUBSCRIPTION_UPDATED,
"resource" => { "merchant_id" => "FQ9WM47T82UAS",
"tracking_id" => create(:user).external_id } } end
it "does not create a new merchant account record" do
expect do
described_class.new.handle_paypal_event(paypal_event)
end.not_to change { MerchantAccount.count }
end
end
end
context "when event type is #{PaypalEventType::MERCHANT_EMAIL_CONFIRMED}" do
context "when merchant account record is not present" do
let(:paypal_event) do { "event_type" => PaypalEventType::MERCHANT_EMAIL_CONFIRMED,
"resource" => { "merchant_id" => "FQ9WM47T82UAS",
"tracking_id" => create(:user).external_id } } end
it "does not create a new merchant account record" do
expect do
described_class.new.handle_paypal_event(paypal_event)
end.not_to change { MerchantAccount.count }
end
end
end
context "when event type is #{PaypalEventType::MERCHANT_ONBOARDING_SELLER_GRANTED_CONSENT}" do
context "when merchant account record is not present" do
let(:paypal_event) do { "event_type" => PaypalEventType::MERCHANT_ONBOARDING_SELLER_GRANTED_CONSENT,
"resource" => { "merchant_id" => "FQ9WM47T82UAS",
"tracking_id" => create(:user).external_id } } end
it "does not create a new merchant account record" do
expect do
described_class.new.handle_paypal_event(paypal_event)
end.not_to change { MerchantAccount.count }
end
end
end
end
describe "#update_merchant_account" do
it "sends a confirmation email when the paypal connect account is updated" do
creator = create(:user)
creator.mark_compliant!(author_name: "Iffy")
allow_any_instance_of(User).to receive(:sales_cents_total).and_return(100_00)
create(:payment_completed, user: creator)
expect(MerchantRegistrationMailer).to receive(:paypal_account_updated).with(creator.id).and_call_original
expect do
subject.update_merchant_account(user: creator, paypal_merchant_id: "GSQ5PDPXZCWGW")
end.to change { creator.merchant_accounts.charge_processor_verified.paypal.count }.by(1)
end
it "does not send a confirmation email when the paypal connect account info is not changed" do
creator = create(:user)
create(:merchant_account_paypal, charge_processor_merchant_id: "GSQ5PDPXZCWGW", user: creator,
charge_processor_alive_at: 1.hour.ago, charge_processor_verified_at: 1.hour.ago)
expect(MerchantRegistrationMailer).not_to receive(:paypal_account_updated).with(creator.id)
expect do
subject.update_merchant_account(user: creator, paypal_merchant_id: "GSQ5PDPXZCWGW")
end.not_to change { MerchantAccount.count }
end
it "marks all other paypal merchant accounts of the creator as deleted" do
creator = create(:user)
creator.mark_compliant!(author_name: "Iffy")
allow_any_instance_of(User).to receive(:sales_cents_total).and_return(100_00)
create(:payment_completed, user: creator)
create(:merchant_account_paypal, user: creator)
create(:merchant_account_paypal, user: creator)
new_paypal_merchant_id = "GSQ5PDPXZCWGW"
old_records =
creator.merchant_accounts.alive.paypal.where.not(charge_processor_merchant_id: new_paypal_merchant_id)
expect(old_records.count).to eq(2)
subject.update_merchant_account(user: creator, paypal_merchant_id: new_paypal_merchant_id)
expect(old_records.count).to eq(0)
expect(creator.merchant_account("paypal").charge_processor_merchant_id).to eq(new_paypal_merchant_id)
end
context "when PayPal account belongs to a Kazakhstan seller" do
it "stores the country and currency from PayPal and verifies the account" do
creator = create(:user)
create(:user_compliance_info, user: creator, country: "Kazakhstan")
creator.mark_compliant!(author_name: "Iffy")
allow_any_instance_of(User).to receive(:sales_cents_total).and_return(150_00)
create(:payment_completed, user: creator)
mailer = instance_double(ActionMailer::MessageDelivery, deliver_later: true)
allow(MerchantRegistrationMailer).to receive(:paypal_account_updated).and_return(mailer)
paypal_details = {
"country" => "KZ",
"primary_currency" => "KZT",
"primary_email" => "kazakhstan@example.com",
"primary_email_confirmed" => true,
"payments_receivable" => true,
"oauth_integrations" => [
{
"integration_type" => "OAUTH_THIRD_PARTY",
"integration_method" => "PAYPAL",
"oauth_third_party" => [
{
"partner_client_id" => PAYPAL_PARTNER_CLIENT_ID
}
]
}
]
}
allow_any_instance_of(MerchantAccount).to receive(:paypal_account_details).and_return(paypal_details)
response = subject.update_merchant_account(user: creator, paypal_merchant_id: "KZPAYPAL123")
merchant_account = creator.merchant_account("paypal")
expect(response).to eq("You have successfully connected your PayPal account with Gumroad.")
expect(merchant_account.country).to eq("KZ")
expect(merchant_account.currency).to eq("kzt")
expect(merchant_account.charge_processor_verified?).to be(true)
expect(MerchantRegistrationMailer).to have_received(:paypal_account_updated).with(creator.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/business/payments/charging/charge_shared_examples.rb | spec/business/payments/charging/charge_shared_examples.rb | # frozen_string_literal: true
require "spec_helper"
shared_examples "a base processor charge" do
describe "#[]" do
before do
subject.id = "charge-id"
end
it "gives access to getting attributes" do
expect(subject[:id]).to eq("charge-id")
end
end
describe "#flow_of_funds" do
it "has a flow of funds" do
expect(subject.flow_of_funds).to be_present
end
it "has a flow of funds with a issued amount" do
expect(subject.flow_of_funds.issued_amount).to be_present
end
it "has a flow of funds with a settled amount" do
expect(subject.flow_of_funds.settled_amount).to be_present
end
it "has a flow of funds with a gumroad amount" do
expect(subject.flow_of_funds.gumroad_amount).to be_present
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/chargeable_protocol.rb | spec/business/payments/charging/chargeable_protocol.rb | # frozen_string_literal: true
require "spec_helper"
# A chargeable is anything that can be used to charge a credit card for a purchase, subscription, etc. It should be
# immutable except when the prepare function is called. This protocol is designed to be backed by any other object or
# remote system (i.e. a charge processor) which is why all data is exposed through functions.
shared_examples_for "a chargeable" do
# charge_processor_id: A string indicating the charge processor
describe "#charge_processor_id" do
it "is set" do
expect(chargeable.charge_processor_id).to be_kind_of(String)
expect(chargeable.charge_processor_id).to_not be_empty
end
end
# prepare: prepares the chargeable for charging. Other functions may not provide data until prepare is called.
describe "#prepare" do
it "returns true" do
expect(chargeable.prepare!).to be(true)
end
it "is callable multiple times" do
10.times { chargeable.prepare! }
end
end
# fingerprint: A unique fingerprint for the credit card this chargeable will charge.
describe "#fingerprint" do
describe "before prepare" do
it "is safe to call" do
chargeable.fingerprint
end
end
describe "after prepare" do
before { chargeable.prepare! }
it "is set" do
expect(chargeable.fingerprint).to_not be(nil)
end
end
end
# last4: The last 4 digits of the credit card the chargeable will charge.
describe "#last4" do
describe "before prepare" do
it "is 4 digits or nil" do
expect(chargeable.last4).to match(/^[0-9]{4}$/) if chargeable.last4.present?
end
end
describe "after prepare" do
before { chargeable.prepare! }
it "is 4 digits" do
expect(chargeable.last4).to match(/^[0-9]{4}$/)
end
end
end
# number_length: The length of the card number of the credit card the chargeable will charge.
describe "#number_length" do
describe "before prepare" do
it "is numeric length between 13 and 19 or nil" do
expect(chargeable.number_length).to be_between(13, 19) if chargeable.number_length.present?
end
end
describe "after prepare" do
before { chargeable.prepare! }
it "is numeric length between 13 and 19" do
expect(chargeable.number_length).to be_between(13, 19)
end
end
end
# expiry_month: The month portion of the expiry date of the credit card the chargeable will charge.
describe "#expiry_month" do
describe "before prepare" do
it "is a valid month as a 1 or 2 digit integer or nil" do
expect(chargeable.expiry_month).to be_between(1, 12) if chargeable.expiry_month.present?
end
end
describe "after prepare" do
before { chargeable.prepare! }
it "is a valid month as a 1 or 2 digit integer" do
expect(chargeable.expiry_month).to be_between(1, 12)
end
end
end
# expiry_year: The month portion of the expiry date of the credit card the chargeable will charge.
describe "#expiry_year" do
describe "before prepare" do
it "is a 2 or 4 digit integer" do
if chargeable.expiry_year.present?
expect(chargeable.expiry_year).to be_between(10, 9999)
expect(chargeable.expiry_year).to_not be_between(100, 999)
end
end
end
describe "after prepare" do
before { chargeable.prepare! }
it "is a 2 or 4 digit integer" do
expect(chargeable.expiry_year).to be_between(10, 9999)
expect(chargeable.expiry_year).to_not be_between(100, 999)
end
end
end
# zip_code: The zip code that will be verified against the credit card the chargeable will charge.
describe "#zip_code" do
describe "before prepare" do
it "is safe to call" do
chargeable.zip_code
end
end
describe "after prepare" do
before { chargeable.prepare! }
it "is safe to call" do
chargeable.zip_code
end
end
end
# card_type: The card type of the credit card the chargeable will charge.
describe "#card_type" do
describe "before prepare" do
it "is safe to call" do
chargeable.card_type
end
end
describe "after prepare" do
before { chargeable.prepare! }
it "is set" do
expect(chargeable.card_type).to_not be(nil)
end
end
end
# country: The issuing country of the credit card the chargeable will charge.
describe "#country" do
describe "before prepare" do
it "is safe to call" do
chargeable.country
end
end
describe "after prepare" do
before { chargeable.prepare! }
it "is set" do
expect(chargeable.country).to_not be(nil)
end
end
end
# reusable_token!: Creates a token (which is returned) which can be used repeatedly to reference the chargeable
# to charge, auth, etc. May optionally take a user id which may be stored at the processor if the processor
# supports it and only if the chargeable is not already persisted.
describe "#reusable_token!" do
describe "before prepare" do
it "is set" do
expect(chargeable.reusable_token!(nil)).to_not be(nil)
end
end
describe "after prepare" do
before { chargeable.prepare! }
it "is set" do
expect(chargeable.reusable_token!(nil)).to_not be(nil)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/charge_refund_shared_examples.rb | spec/business/payments/charging/charge_refund_shared_examples.rb | # frozen_string_literal: true
require "spec_helper"
shared_examples "a charge refund" do
describe "#flow_of_funds" do
it "has a flow of funds" do
expect(subject.flow_of_funds).to be_present
end
it "has a flow of funds with a issued amount" do
expect(subject.flow_of_funds.issued_amount).to be_present
end
it "has a flow of funds with a settled amount" do
expect(subject.flow_of_funds.settled_amount).to be_present
end
it "has a flow of funds with a gumroad amount" do
expect(subject.flow_of_funds.gumroad_amount).to be_present
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/chargeable_visual_spec.rb | spec/business/payments/charging/chargeable_visual_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ChargeableVisual do
describe "is_cc_visual" do
describe "visual is a credit card" do
let(:visual) { "**** **** **** 4242" }
it "returns true" do
expect(described_class.is_cc_visual(visual)).to eq(true)
end
end
describe "visual is a weird credit card" do
let(:visual) { "***A **** **** 4242" }
it "returns false" do
expect(described_class.is_cc_visual(visual)).to eq(false)
end
end
describe "visual is an email address" do
let(:visual) { "hi@gumroad.com" }
it "returns false" do
expect(described_class.is_cc_visual(visual)).to eq(false)
end
end
end
describe "build_visual" do
it "formats all types properly based on card number length" do
expect(described_class.build_visual("4242", 16)).to eq "**** **** **** 4242"
expect(described_class.build_visual("242", 16)).to eq "**** **** **** *242"
expect(described_class.build_visual("4000 0000 0000 4242", 16)).to eq "**** **** **** 4242"
expect(described_class.build_visual("4242", 15)).to eq "**** ****** *4242"
expect(described_class.build_visual("4242", 14)).to eq "**** ****** 4242"
expect(described_class.build_visual("4242", 20)).to eq "**** **** **** 4242"
end
it "filters out everything but numbers" do
expect(described_class.build_visual("-42-42", 16)).to eq "**** **** **** 4242"
expect(described_class.build_visual(" 4+2@4 2", 16)).to eq "**** **** **** 4242"
expect(described_class.build_visual("4%2$4!2", 16)).to eq "**** **** **** 4242"
expect(described_class.build_visual("4_2*4&2", 16)).to eq "**** **** **** 4242"
expect(described_class.build_visual("4%2B4a2", 16)).to eq "**** **** **** 4242"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/charge_refund_spec.rb | spec/business/payments/charging/charge_refund_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "business/payments/charging/charge_refund_shared_examples"
describe ChargeRefund do
let(:flow_of_funds) { FlowOfFunds.build_simple_flow_of_funds(Currency::USD, 1_00) }
let(:subject) do
charge_refund = ChargeRefund.new
charge_refund.flow_of_funds = flow_of_funds
charge_refund
end
it_behaves_like "a charge refund"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/base_processor_charge_spec.rb | spec/business/payments/charging/base_processor_charge_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "business/payments/charging/charge_shared_examples"
describe BaseProcessorCharge do
let(:flow_of_funds) { FlowOfFunds.build_simple_flow_of_funds(Currency::USD, 1_00) }
let(:subject) do
charge = BaseProcessorCharge.new
charge.flow_of_funds = flow_of_funds
charge
end
it_behaves_like "a base processor charge"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/charge_processor_spec.rb | spec/business/payments/charging/charge_processor_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ChargeProcessor do
describe ".get_chargeable_for_params" do
it "calls get_chargeable_for_params on the charge processors" do
expect_any_instance_of(StripeChargeProcessor).to receive(:get_chargeable_for_params).with({ param: "param" }, nil)
ChargeProcessor.get_chargeable_for_params({ param: "param" }, nil)
end
end
describe ".get_chargeable_for_data", :vcr do
it "calls get_chargeable_for_data on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:get_chargeable_for_data).with(
"customer-id",
"payment_method",
"fingerprint",
nil,
nil,
"4242",
16,
"**** **** **** 4242",
1,
2015,
CardType::VISA,
"US",
nil,
merchant_account: nil
).and_call_original
ChargeProcessor.get_chargeable_for_data(
{
StripeChargeProcessor.charge_processor_id => "customer-id"
},
"payment_method",
"fingerprint",
nil,
nil,
"4242",
16,
"**** **** **** 4242",
1,
2015,
CardType::VISA,
"US"
)
end
it "calls get_chargeable_for_data on the correct charge processor with zip if provided" do
expect_any_instance_of(StripeChargeProcessor).to receive(:get_chargeable_for_data).with(
"customer-id",
"payment_method",
"fingerprint",
nil,
nil,
"4242",
16,
"**** **** **** 4242",
1,
2015,
CardType::VISA,
"US",
"zip-code",
merchant_account: nil
).and_call_original
ChargeProcessor.get_chargeable_for_data(
{
StripeChargeProcessor.charge_processor_id => "customer-id"
},
"payment_method",
"fingerprint",
nil,
nil,
"4242",
16,
"**** **** **** 4242",
1,
2015,
CardType::VISA,
"US",
"zip-code"
)
end
end
describe ".get_charge" do
it "calls get_charge on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:get_charge).with("charge-id", merchant_account: nil)
ChargeProcessor.get_charge(StripeChargeProcessor.charge_processor_id, "charge-id")
end
end
describe ".create_payment_intent_or_charge!" do
let(:merchant_account) { create(:merchant_account) }
let(:stripe_chargeable) { double }
let(:chargeable) do
chargeable = double
allow(chargeable).to receive(:get_chargeable_for).and_return(stripe_chargeable)
chargeable
end
it "calls create_payment_intent_or_charge! on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:create_payment_intent_or_charge!).with(
merchant_account,
stripe_chargeable,
1_00,
0_30,
"reference",
"description",
metadata: nil,
statement_description: "statement-description",
transfer_group: nil,
off_session: true,
setup_future_charges: true,
mandate_options: nil
)
ChargeProcessor.create_payment_intent_or_charge!(
merchant_account,
chargeable,
1_00,
0_30,
"reference",
"description",
statement_description: "statement-description",
off_session: true,
setup_future_charges: true
)
end
it "passes mandate_options to create_payment_intent_or_charge! on the correct charge processor" do
mandate_options = {
payment_method_options: {
card: {
mandate_options: {
reference: StripeChargeProcessor::MANDATE_PREFIX + SecureRandom.hex,
amount_type: "maximum",
amount: 10_00,
start_date: Time.current.to_i,
interval: "month",
interval_count: 1,
supported_types: ["india"]
}
}
}
}
expect_any_instance_of(StripeChargeProcessor).to receive(:create_payment_intent_or_charge!).with(
merchant_account,
stripe_chargeable,
1_00,
0_30,
"reference",
"description",
metadata: nil,
statement_description: "statement-description",
transfer_group: nil,
off_session: true,
setup_future_charges: true,
mandate_options:
)
ChargeProcessor.create_payment_intent_or_charge!(
merchant_account,
chargeable,
1_00,
0_30,
"reference",
"description",
metadata: nil,
statement_description: "statement-description",
off_session: true,
setup_future_charges: true,
mandate_options:
)
end
end
describe ".get_charge_intent" do
let(:merchant_account) { create(:merchant_account, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:charge_intent_id) { "pi_123456" }
it "returns nil if blank charge intent ID is passed" do
expect_any_instance_of(StripeChargeProcessor).not_to receive(:get_charge_intent)
charge_intent = ChargeProcessor.get_charge_intent(merchant_account, nil)
expect(charge_intent).to be_nil
end
it "calls get_charge_intent on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:get_charge_intent).with(charge_intent_id, merchant_account:)
ChargeProcessor.get_charge_intent(merchant_account, charge_intent_id)
end
end
describe ".get_setup_intent" do
let(:merchant_account) { create(:merchant_account, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:setup_intent_id) { "seti_123456" }
it "returns nil if blank setup intent ID is passed" do
expect_any_instance_of(StripeChargeProcessor).not_to receive(:get_setup_intent)
setup_intent = ChargeProcessor.get_setup_intent(merchant_account, nil)
expect(setup_intent).to be_nil
end
it "calls get_charge_intent on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:get_setup_intent).with(setup_intent_id, merchant_account:)
ChargeProcessor.get_setup_intent(merchant_account, setup_intent_id)
end
end
describe ".confirm_payment_intent!" do
let(:merchant_account) { create(:merchant_account, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:charge_intent_id) { "pi_123456" }
it "calls confirm_payment_intent! on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:confirm_payment_intent!).with(
merchant_account,
charge_intent_id
)
ChargeProcessor.confirm_payment_intent!(merchant_account, charge_intent_id)
end
end
describe ".cancel_payment_intent!" do
let(:merchant_account) { create(:merchant_account, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:charge_intent_id) { "pi_123456" }
it "calls cancel_payment_intent! on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:cancel_payment_intent!).with(merchant_account, charge_intent_id)
ChargeProcessor.cancel_payment_intent!(merchant_account, charge_intent_id)
end
end
describe ".cancel_setup_intent!" do
let(:merchant_account) { create(:merchant_account, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:setup_intent_id) { "seti_123456" }
it "calls cancel_setup_intent! on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:cancel_setup_intent!).with(merchant_account, setup_intent_id)
ChargeProcessor.cancel_setup_intent!(merchant_account, setup_intent_id)
end
end
describe ".setup_future_charges!" do
let(:merchant_account) { create(:merchant_account, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:stripe_chargeable) { double }
let(:chargeable) { double }
before do
allow(chargeable).to receive(:get_chargeable_for).and_return(stripe_chargeable)
end
it "calls setup_future_charges! on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:setup_future_charges!).with(merchant_account, stripe_chargeable, mandate_options: nil)
ChargeProcessor.setup_future_charges!(merchant_account, chargeable)
end
it "passes mandate_options parameter to setup_future_charges! on the correct charge processor" do
mandate_options = {
payment_method_options: {
card: {
mandate_options: {
reference: StripeChargeProcessor::MANDATE_PREFIX + SecureRandom.hex,
amount_type: "maximum",
amount: 10_00,
start_date: Time.current.to_i,
interval: "month",
interval_count: 1,
supported_types: ["india"]
}
}
}
}
expect_any_instance_of(StripeChargeProcessor).to receive(:setup_future_charges!).with(merchant_account, stripe_chargeable, mandate_options:)
ChargeProcessor.setup_future_charges!(merchant_account, chargeable, mandate_options:)
end
end
describe ".refund!" do
describe "full refund" do
it "calls get_charge on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:refund!).with("charge-id", amount_cents: nil,
merchant_account: nil,
paypal_order_purchase_unit_refund: nil,
reverse_transfer: true,
is_for_fraud: nil)
ChargeProcessor.refund!(StripeChargeProcessor.charge_processor_id, "charge-id",)
end
end
describe "partial refund" do
it "calls get_charge on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:refund!).with("charge-id", amount_cents: 2_00,
merchant_account: nil,
paypal_order_purchase_unit_refund: nil,
reverse_transfer: true,
is_for_fraud: nil)
ChargeProcessor.refund!(StripeChargeProcessor.charge_processor_id, "charge-id", amount_cents: 2_00)
end
end
end
describe ".holder_of_funds" do
let(:merchant_account) { create(:merchant_account) }
it "calls holder_of_funds on the correct charge processor" do
expect_any_instance_of(StripeChargeProcessor).to receive(:holder_of_funds).with(merchant_account)
ChargeProcessor.holder_of_funds(merchant_account)
end
end
describe ".handle_event" do
let(:charge_event) { build(:charge_event_informational) }
before do
@subscriber = ActiveSupport::Notifications.subscribe(ChargeProcessor::NOTIFICATION_CHARGE_EVENT) do |_, _, _, _, payload|
expect(payload).to include(charge_event:)
end
end
after do
ActiveSupport::Notifications.unsubscribe(@subscriber)
end
it "posts a charge event to active support notifications" do
ChargeProcessor.handle_event(charge_event)
end
end
describe ".transaction_url" do
describe "in a non-production environment" do
it "returns a valid url for all charge processors" do
described_class.charge_processor_ids.each do |charge_processor_id|
transaction_url = ChargeProcessor.transaction_url(charge_processor_id, "dummy_charge_id")
expect(transaction_url).to be_a(String)
expect(URI.parse(transaction_url)).to be_a(URI)
end
end
end
describe "in a production environment" do
before do
allow(Rails.env).to receive(:production?).and_return(true)
end
it "returns a valid url for all charge processors" do
described_class.charge_processor_ids.each do |charge_processor_id|
transaction_url = ChargeProcessor.transaction_url(charge_processor_id, "dummy_charge_id")
expect(transaction_url).to be_a(String)
expect(URI.parse(transaction_url)).to be_a(URI)
end
end
end
end
describe ".transaction_url_for_seller" do
let(:charge_processor_id) { StripeChargeProcessor.charge_processor_id }
let(:charge_id) { "dummy_charge_id" }
it "returns nil if charge_processor_id is nil" do
url = ChargeProcessor.transaction_url_for_seller(nil, charge_id, false)
expect(url).to be(nil)
end
it "returns nil if charge_id is nil" do
url = ChargeProcessor.transaction_url_for_seller(charge_processor_id, nil, false)
expect(url).to be(nil)
end
it "returns nil if charged_using_gumroad_account" do
url = ChargeProcessor.transaction_url_for_seller(charge_processor_id, charge_id, true)
expect(url).to be(nil)
end
it "returns url if not charged_using_gumroad_account" do
url = ChargeProcessor.transaction_url_for_seller(charge_processor_id, charge_id, false)
expect(URI.parse(url)).to be_a(URI)
end
end
describe ".transaction_url_for_admin" do
let(:charge_processor_id) { StripeChargeProcessor.charge_processor_id }
let(:charge_id) { "dummy_charge_id" }
it "returns nil if charge_processor_id is nil" do
url = ChargeProcessor.transaction_url_for_admin(nil, charge_id, false)
expect(url).to be(nil)
end
it "returns nil if charge_id is nil" do
url = ChargeProcessor.transaction_url_for_admin(charge_processor_id, nil, false)
expect(url).to be(nil)
end
it "returns nil if not charged_using_gumroad_account" do
url = ChargeProcessor.transaction_url_for_admin(charge_processor_id, charge_id, false)
expect(url).to be(nil)
end
it "returns url if charged_using_gumroad_account" do
url = ChargeProcessor.transaction_url_for_admin(charge_processor_id, charge_id, true)
expect(URI.parse(url)).to be_a(URI)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/chargeable_spec.rb | spec/business/payments/charging/chargeable_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Chargeable do
let(:internal_chargeable_1) { double(charge_processor_id: "stripe") }
let(:internal_chargeable_2) { double(charge_processor_id: "braintree") }
let(:chargeable) { Chargeable.new([internal_chargeable_1, internal_chargeable_2]) }
describe "#charge_processor_ids" do
it "returns all internal chargeables processor ids" do
expect(chargeable.charge_processor_ids).to eq(%w[stripe braintree])
end
end
describe "#charge_processor_id" do
it "returns combination of all internal chargeables" do
expect(chargeable.charge_processor_id).to eq("stripe,braintree")
end
end
describe "#prepare!" do
it "passes through to first chargeable" do
expect(internal_chargeable_1).to receive(:prepare!).once.and_return(true)
expect(internal_chargeable_2).not_to receive(:prepare!)
expect(chargeable.prepare!).to eq(true)
end
end
describe "#fingerprint" do
it "passes through to first chargeable" do
expect(internal_chargeable_1).to receive(:fingerprint).once.and_return("a-fingerprint")
expect(internal_chargeable_2).not_to receive(:fingerprint)
expect(chargeable.fingerprint).to eq("a-fingerprint")
end
end
describe "#last4" do
it "passes through to first chargeable" do
expect(internal_chargeable_1).to receive(:last4).once.and_return("4242")
expect(internal_chargeable_2).not_to receive(:last4)
expect(chargeable.last4).to eq("4242")
end
end
describe "#number_length" do
it "passes through to first chargeable" do
expect(internal_chargeable_1).to receive(:number_length).once.and_return(16)
expect(internal_chargeable_2).not_to receive(:number_length)
expect(chargeable.number_length).to eq(16)
end
end
describe "#visual" do
it "passes through to first chargeable" do
expect(internal_chargeable_1).to receive(:visual).once.and_return("**** **** **** 4242")
expect(internal_chargeable_2).not_to receive(:visual)
expect(chargeable.visual).to eq("**** **** **** 4242")
end
end
describe "#expiry_month" do
it "calls on first chargeable" do
expect(internal_chargeable_1).to receive(:expiry_month).once.and_return(12)
expect(internal_chargeable_2).not_to receive(:expiry_month)
expect(chargeable.expiry_month).to eq(12)
end
end
describe "#expiry_year" do
it "calls on first chargeable" do
expect(internal_chargeable_1).to receive(:expiry_year).once.and_return(2014)
expect(internal_chargeable_2).not_to receive(:expiry_year)
expect(chargeable.expiry_year).to eq(2014)
end
end
describe "#zip_code" do
it "calls on first chargeable" do
expect(internal_chargeable_1).to receive(:zip_code).once.and_return("12345")
expect(internal_chargeable_2).not_to receive(:zip_code)
expect(chargeable.zip_code).to eq("12345")
end
end
describe "#card_type" do
it "calls on first chargeable" do
expect(internal_chargeable_1).to receive(:card_type).once.and_return("visa")
expect(internal_chargeable_2).not_to receive(:card_type)
expect(chargeable.card_type).to eq("visa")
end
end
describe "#country" do
it "calls on first chargeable" do
expect(internal_chargeable_1).to receive(:country).once.and_return("US")
expect(internal_chargeable_2).not_to receive(:country)
expect(chargeable.country).to eq("US")
end
end
describe "#payment_method_id" do
it "delegates to the first chargeable" do
expect(internal_chargeable_1).to receive(:payment_method_id).once.and_return("pm_123456")
expect(internal_chargeable_2).not_to receive(:payment_method_id)
expect(chargeable.payment_method_id).to eq("pm_123456")
end
end
describe "#requires_mandate?", :vcr do
it "returns false if charge processor is not Stripe" do
expect(create(:native_paypal_chargeable).requires_mandate?).to be false
expect(create(:paypal_chargeable).requires_mandate?).to be false
end
it "return false if charge processor is Stripe and card country is not India" do
expect(create(:chargeable, card: StripePaymentMethodHelper.success_with_sca).requires_mandate?).to be false
end
it "returns true if charge processor is Stripe and card country is India" do
expect(create(:chargeable, card: StripePaymentMethodHelper.success_indian_card_mandate).requires_mandate?).to be false
end
end
describe "#stripe_setup_intent_id" do
it "passes through to first chargeable only if it's a Stripe chargeable", :vcr do
stripe_chargeable = create(:chargeable)
expect_any_instance_of(StripeChargeablePaymentMethod).to receive(:stripe_setup_intent_id).and_return("seti_123456")
expect(stripe_chargeable.stripe_setup_intent_id).to be "seti_123456"
end
it "returns nil for non-Stripe chargeable" do
braintree_chargeable = create(:paypal_chargeable)
expect(braintree_chargeable.stripe_setup_intent_id).to be nil
paypal_chargeable = create(:native_paypal_chargeable)
expect(paypal_chargeable.stripe_setup_intent_id).to be nil
end
end
describe "#stripe_payment_intent_id" do
it "passes through to first chargeable only if it's a Stripe chargeable", :vcr do
stripe_chargeable = create(:chargeable)
expect_any_instance_of(StripeChargeablePaymentMethod).to receive(:stripe_payment_intent_id).and_return("pi_123456")
expect(stripe_chargeable.stripe_payment_intent_id).to be "pi_123456"
end
it "returns nil for non-Stripe chargeable" do
braintree_chargeable = create(:paypal_chargeable)
expect(braintree_chargeable.stripe_payment_intent_id).to be nil
paypal_chargeable = create(:native_paypal_chargeable)
expect(paypal_chargeable.stripe_payment_intent_id).to be nil
end
end
describe "#reusable_token_for!" do
let(:user) { create(:user) }
it "returns the respective chargeable's #reusable_token! #1" do
expect(internal_chargeable_1).to receive(:reusable_token!).with(user).once.and_return("a-reusable-token-1")
expect(internal_chargeable_2).not_to receive(:reusable_token!)
expect(chargeable.reusable_token_for!("stripe", user)).to eq("a-reusable-token-1")
end
it "returns the respective chargeable's #reusable_token! #2" do
expect(internal_chargeable_1).not_to receive(:reusable_token!)
expect(internal_chargeable_2).to receive(:reusable_token!).with(user).once.and_return("a-reusable-token-2")
expect(chargeable.reusable_token_for!("braintree", user)).to eq("a-reusable-token-2")
end
it "returns nil if chargeable not available" do
expect(internal_chargeable_1).not_to receive(:reusable_token!)
expect(internal_chargeable_2).not_to receive(:reusable_token!)
expect(chargeable.reusable_token_for!("something-else", user)).to be_nil
end
end
describe "#can_be_saved?", :vcr do
it "returns false if underlying chargeable is PaypalApprovedOrderChargeable" do
chargeable = create(:paypal_approved_order_chargeable)
expect(chargeable.charge_processor_id).to eq(PaypalChargeProcessor.charge_processor_id)
expect(chargeable.get_chargeable_for(chargeable.charge_processor_id)).to be_a(PaypalApprovedOrderChargeable)
expect(chargeable.can_be_saved?).to be(false)
end
it "returns true if underlying chargeable is PaypalChargeable" do
chargeable = create(:native_paypal_chargeable)
expect(chargeable.charge_processor_id).to eq(PaypalChargeProcessor.charge_processor_id)
expect(chargeable.get_chargeable_for(chargeable.charge_processor_id)).to be_a(PaypalChargeable)
expect(chargeable.can_be_saved?).to be(true)
end
it "returns true if underlying chargeable is StripeChargeablePaymentMethod" do
chargeable = create(:chargeable)
expect(chargeable.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id)
expect(chargeable.get_chargeable_for(chargeable.charge_processor_id)).to be_a(StripeChargeablePaymentMethod)
expect(chargeable.can_be_saved?).to be(true)
end
it "returns true if underlying chargeable is StripeChargeableToken" do
chargeable = create(:cc_token_chargeable)
expect(chargeable.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id)
expect(chargeable.get_chargeable_for(chargeable.charge_processor_id)).to be_a(StripeChargeableToken)
expect(chargeable.can_be_saved?).to be(true)
end
it "returns true if underlying chargeable is BraintreeChargeableNonce" do
chargeable = create(:paypal_chargeable)
expect(chargeable.charge_processor_id).to eq(BraintreeChargeProcessor.charge_processor_id)
expect(chargeable.get_chargeable_for(chargeable.charge_processor_id)).to be_a(BraintreeChargeableNonce)
expect(chargeable.can_be_saved?).to be(true)
end
end
describe "#get_chargeable_for" do
it "returns the respective underlying chargeable" do
expect(chargeable.get_chargeable_for("stripe")).to eq(internal_chargeable_1)
expect(chargeable.get_chargeable_for("braintree")).to eq(internal_chargeable_2)
end
it "returns nil when not available" do
expect(chargeable.get_chargeable_for("something-else")).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/business/payments/charging/flow_of_funds_spec.rb | spec/business/payments/charging/flow_of_funds_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe FlowOfFunds do
describe ".build_simple_flow_of_funds" do
let(:currency) { Currency::USD }
let(:amount_cents) { 100_00 }
let(:flow_of_funds) { described_class.build_simple_flow_of_funds(currency, amount_cents) }
it "returns a flow of funds object" do
expect(flow_of_funds).to be_a(FlowOfFunds)
end
it "returns a flow of funds object with an issued amount" do
expect(flow_of_funds.issued_amount.currency).to eq(currency)
expect(flow_of_funds.issued_amount.cents).to eq(amount_cents)
end
it "returns a flow of funds object with a settled amount" do
expect(flow_of_funds.settled_amount.currency).to eq(currency)
expect(flow_of_funds.settled_amount.cents).to eq(amount_cents)
end
it "returns a flow of funds object with a gumroad amount" do
expect(flow_of_funds.gumroad_amount.currency).to eq(currency)
expect(flow_of_funds.gumroad_amount.cents).to eq(amount_cents)
end
it "returns a flow of funds object without a merchant account gross amount" do
expect(flow_of_funds.merchant_account_gross_amount).to be_nil
expect(flow_of_funds.merchant_account_net_amount).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/business/payments/charging/implementations/braintree/braintree_charge_intent_spec.rb | spec/business/payments/charging/implementations/braintree/braintree_charge_intent_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BraintreeChargeIntent do
let(:braintree_charge) { double }
subject (:braintree_charge_intent) { described_class.new(charge: braintree_charge) }
describe "#succeeded?" do
it "returns true" do
expect(braintree_charge_intent.succeeded?).to eq(true)
end
end
describe "#requires_action?" do
it "returns false" do
expect(braintree_charge_intent.requires_action?).to eq(false)
end
end
describe "#charge" do
it "returns the charge object it was initialized with" do
expect(braintree_charge_intent.charge).to eq(braintree_charge)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/braintree/braintree_charge_refund_spec.rb | spec/business/payments/charging/implementations/braintree/braintree_charge_refund_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BraintreeChargeRefund, :vcr do
let(:braintree_chargeable) do
chargeable = BraintreeChargeableNonce.new(Braintree::Test::Nonce::PayPalFuturePayment, nil)
chargeable.prepare!
Chargeable.new([chargeable])
end
let(:braintree_charge) do
params = {
merchant_account_id: BRAINTREE_MERCHANT_ACCOUNT_ID_FOR_SUPPLIERS,
amount: 100_00 / 100.0,
customer_id: braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id).reusable_token!(nil),
options: {
submit_for_settlement: true
}
}
Braintree::Transaction.sale!(params)
end
let(:braintree_refund) do
Braintree::Transaction.refund!(braintree_charge.id)
end
let(:subject) { described_class.new(braintree_refund) }
describe "#initialize" do
describe "with a braintree refund" do
it "has a charge_processor_id set to 'braintree'" do
expect(subject.charge_processor_id).to eq "braintree"
end
it "has the #id from the braintree refund" do
expect(subject.id).to eq(braintree_refund.id)
end
it "has the #charge_id from the braintree refund" do
expect(subject.charge_id).to eq(braintree_refund.refunded_transaction_id)
end
it "has the #charge_id from the original braintree charge" do
expect(subject.charge_id).to eq(braintree_charge.id)
end
end
end
describe "#flow_of_funds" do
let(:flow_of_funds) { subject.flow_of_funds }
it "has a simple flow of funds" do
expect(flow_of_funds.issued_amount.currency).to eq(Currency::USD)
expect(flow_of_funds.issued_amount.cents).to eq(-100_00)
expect(flow_of_funds.settled_amount.currency).to eq(Currency::USD)
expect(flow_of_funds.settled_amount.cents).to eq(-100_00)
expect(flow_of_funds.gumroad_amount.currency).to eq(Currency::USD)
expect(flow_of_funds.gumroad_amount.cents).to eq(-100_00)
expect(flow_of_funds.merchant_account_gross_amount).to be_nil
expect(flow_of_funds.merchant_account_net_amount).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/business/payments/charging/implementations/braintree/braintree_charge_processor_spec.rb | spec/business/payments/charging/implementations/braintree/braintree_charge_processor_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BraintreeChargeProcessor, :vcr do
describe ".charge_processor_id" do
it "returns 'stripe'" do
expect(BraintreeChargeProcessor.charge_processor_id).to eq "braintree"
end
end
let(:braintree_chargeable) do
chargeable = BraintreeChargeableNonce.new(Braintree::Test::Nonce::PayPalFuturePayment, nil)
chargeable.prepare!
Chargeable.new([chargeable])
end
describe "#get_chargeable_for_params" do
describe "with invalid params" do
it "returns nil" do
expect(subject.get_chargeable_for_params({}, nil)).to be(nil)
end
end
describe "with only nonce" do
let(:paypal_nonce) { Braintree::Test::Nonce::PayPalFuturePayment }
it "returns a chargeable nonce" do
expect(BraintreeChargeableNonce).to receive(:new).with(paypal_nonce, nil).and_call_original
expect(subject.get_chargeable_for_params({ braintree_nonce: paypal_nonce }, nil)).to be_a(BraintreeChargeableNonce)
end
end
describe "with transient customer key", :vcr do
before do
@frozen_time = Time.current
travel_to(@frozen_time) do
@braintree_transient_customer_store_key = "braintree_transient_customer_store_key"
BraintreeChargeableTransientCustomer.tokenize_nonce_to_transient_customer(Braintree::Test::Nonce::PayPalFuturePayment, @braintree_transient_customer_store_key)
end
end
it "returns a transient customer" do
travel_to(@frozen_time) do
expect(subject.get_chargeable_for_params({ braintree_transient_customer_store_key: @braintree_transient_customer_store_key }, nil)).to be_a(BraintreeChargeableTransientCustomer)
end
end
end
describe "with braintree device data for fraud check on braintree's side" do
let(:dummy_device_data) { { dummy_session_id: "dummy" }.to_json }
describe "with a braintree nonce" do
let(:paypal_nonce) { Braintree::Test::Nonce::PayPalFuturePayment }
it "returns a chargeable nonce with the device data JSON string set" do
expect(BraintreeChargeableNonce).to receive(:new).with(paypal_nonce, nil).and_call_original
actual_chargeable = subject.get_chargeable_for_params({ braintree_nonce: paypal_nonce,
braintree_device_data: dummy_device_data }, nil)
expect(actual_chargeable).to be_a(BraintreeChargeableNonce)
expect(actual_chargeable.braintree_device_data).to eq(dummy_device_data)
end
end
describe "with a transient customer store key with the device data JSON string set" do
before do
@frozen_time = Time.current
travel_to(@frozen_time) do
@braintree_transient_customer_store_key = "braintree_transient_customer_store_key"
BraintreeChargeableTransientCustomer.tokenize_nonce_to_transient_customer(Braintree::Test::Nonce::PayPalFuturePayment, @braintree_transient_customer_store_key)
end
end
it "returns a transient customer" do
travel_to(@frozen_time) do
actual_chargeable = subject.get_chargeable_for_params({ braintree_transient_customer_store_key: @braintree_transient_customer_store_key,
braintree_device_data: dummy_device_data }, nil)
expect(actual_chargeable).to be_a(BraintreeChargeableTransientCustomer)
expect(actual_chargeable.braintree_device_data).to eq(dummy_device_data)
end
end
end
end
end
describe "#get_chargeable_for_data" do
describe "with customer id as retreivable token" do
it "returns a credit card with the reusable token set" do
expect(BraintreeChargeableCreditCard).to receive(:new)
.with(braintree_chargeable.reusable_token_for!(BraintreeChargeProcessor.charge_processor_id, nil), nil, nil, nil, nil, nil, nil, nil, nil, nil)
.and_call_original
expect(subject.get_chargeable_for_data(braintree_chargeable.reusable_token_for!(BraintreeChargeProcessor.charge_processor_id, nil), nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil))
.to be_a(BraintreeChargeableCreditCard)
end
end
end
describe "#get_charge" do
let(:braintree_charge_txn) do
params = {
merchant_account_id: BRAINTREE_MERCHANT_ACCOUNT_ID_FOR_SUPPLIERS,
amount: 100_00 / 100.0,
customer_id: braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id).reusable_token!(nil),
options: {
submit_for_settlement: true
}
}
Braintree::Transaction.sale!(params)
end
describe "with an invalid charge id" do
it "throws a charge processor invalid exception" do
expect do
subject.get_charge("invalid")
end.to raise_error(ChargeProcessorInvalidRequestError)
end
end
describe "with a valid charge id" do
it "retrieves and returns a braintree charge object" do
actual_charge = subject.get_charge(braintree_charge_txn.id)
expect(actual_charge).to_not be(nil)
expect(actual_charge).to be_a(BraintreeCharge)
expect(actual_charge.charge_processor_id).to eq(BraintreeChargeProcessor.charge_processor_id)
expect(actual_charge.zip_check_result).to be(nil)
expect(actual_charge.id).to eq(braintree_charge_txn.id)
expect(actual_charge.fee).to be(nil)
expect(actual_charge.card_fingerprint).to eq("paypal_jane.doe@example.com")
end
end
describe "when the charge processor is unavailable" do
before do
expect(Braintree::Transaction).to receive(:find).and_raise(Braintree::ServiceUnavailableError)
end
it "raises an error" do
expect { subject.get_charge("a-charge-id") }.to raise_error(ChargeProcessorUnavailableError)
end
end
end
describe "#search_charge" do
it "returns a Braintree::Transaction object with details of the transaction attached to the given purchase" do
allow_any_instance_of(Purchase).to receive(:external_id).and_return("50WuYB5aQYhDx2gzaxhP-Q==")
charge = subject.search_charge(purchase: create(:purchase, charge_processor_id: BraintreeChargeProcessor.charge_processor_id))
expect(charge).to be_a(Braintree::Transaction)
expect(charge.id).to eq("f4ajns4e")
expect(charge.status).to eq("settled")
end
it "returns nil if no transaction is found for the given purchase" do
allow_any_instance_of(Purchase).to receive(:external_id).and_return(ObfuscateIds.encrypt(1234567890))
expect(subject.search_charge(purchase: create(:purchase, charge_processor_id: BraintreeChargeProcessor.charge_processor_id))).to be(nil)
end
end
describe "#create_payment_intent_or_charge!" do
let(:braintree_merchant_account) { MerchantAccount.gumroad(BraintreeChargeProcessor.charge_processor_id) }
describe "successful charging" do
it "charges the card and returns a braintree charge" do
actual_charge = subject.create_payment_intent_or_charge!(braintree_merchant_account,
braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id),
225_00,
0,
"product-id",
nil,
statement_description: "dummy").charge
expect(actual_charge).to_not be(nil)
expect(actual_charge).to be_a(BraintreeCharge)
expect(actual_charge.charge_processor_id).to eq("braintree")
expect(actual_charge.id).to_not be(nil)
actual_txn = Braintree::Transaction.find(actual_charge.id)
expect(actual_txn).to_not be(nil)
expect(actual_txn.amount).to eq(225.0)
expect(actual_txn.customer_details.id).to eq(braintree_chargeable.reusable_token_for!(BraintreeChargeProcessor.charge_processor_id, nil))
end
end
describe "successful charging with device data passed to braintree" do
let(:dummy_device_data) do
{ device_session_id: "174dbf8146df0e205f9e04e54000bc11",
fraud_merchant_id: "600000",
correlation_id: "e69e3cd5129668146948413a77988f26" }.to_json
end
let(:braintree_chargeable) do
chargeable = BraintreeChargeableNonce.new(Braintree::Test::Nonce::PayPalFuturePayment, nil)
chargeable.braintree_device_data = dummy_device_data
chargeable.prepare!
Chargeable.new([chargeable])
end
it "charges the card and returns a braintree charge" do
expect(Braintree::Transaction)
.to receive(:sale)
.with(hash_including(device_data: dummy_device_data, options: { submit_for_settlement: true, paypal: { description: "sample description" } }))
.and_call_original
actual_charge = subject.create_payment_intent_or_charge!(braintree_merchant_account,
braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id),
225_00,
0,
"product-id",
"sample description",
statement_description: "dummy").charge
expect(actual_charge).to_not be(nil)
expect(actual_charge).to be_a(BraintreeCharge)
expect(actual_charge.charge_processor_id).to eq("braintree")
expect(actual_charge.id).to_not be(nil)
actual_txn = Braintree::Transaction.find(actual_charge.id)
expect(actual_txn).to_not be(nil)
expect(actual_txn.amount).to eq(225.0)
expect(actual_txn.customer_details.id).to eq(braintree_chargeable.reusable_token_for!(BraintreeChargeProcessor.charge_processor_id, nil))
end
end
describe "unsuccessful charging" do
describe "when the charge processor is unavailable" do
before do
expect(Braintree::Transaction).to receive(:sale).and_raise(Braintree::ServiceUnavailableError)
end
it "raises an error" do
expect do
subject.create_payment_intent_or_charge!(braintree_merchant_account,
braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id),
225_00,
0,
"product-id",
nil,
statement_description: "dummy")
end.to raise_error(ChargeProcessorUnavailableError)
end
end
# Braintree echo'es back the charge amount as the error code for testing.
# We use this feature to simulate various failure responses.
# See https://developers.braintreepayments.com/javascript+ruby/reference/general/processor-responses/authorization-responses
describe "failures emulated by payment amount" do
describe "when card is declined" do
it "returns an error" do
expect do
subject.create_payment_intent_or_charge!(braintree_merchant_account,
braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id),
204_600,
0,
"product-id",
nil,
statement_description: "dummy")
end.to raise_error do |error|
expect(error).to be_a(ChargeProcessorCardError)
expect(error.error_code).to eq("2046")
expect(error.message).to eq("Declined")
end
end
end
describe "when paypal account is unsupported" do
it "returns an error" do
expect do
subject.create_payment_intent_or_charge!(braintree_merchant_account,
braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id),
207_100,
0,
"product-id",
nil,
statement_description: "dummy")
end.to raise_error(ChargeProcessorUnsupportedPaymentAccountError)
end
end
describe "when paypal payment instrument is unsupported" do
it "returns an error" do
expect do
subject.create_payment_intent_or_charge!(braintree_merchant_account,
braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id),
207_400,
0,
"product-id",
nil,
statement_description: "dummy")
end.to raise_error(ChargeProcessorUnsupportedPaymentTypeError)
end
end
describe "when paypal payment instrument is unsupported" do
it "returns an error" do
expect do
subject.create_payment_intent_or_charge!(braintree_merchant_account,
braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id),
207_400,
0,
"product-id",
nil,
statement_description: "dummy")
end.to raise_error(ChargeProcessorUnsupportedPaymentTypeError)
end
end
describe "when paypal payment instrument is unsupported" do
it "returns an error" do
expect do
subject.create_payment_intent_or_charge!(braintree_merchant_account,
braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id),
207_400,
0,
"product-id",
nil,
statement_description: "dummy")
end.to raise_error(ChargeProcessorUnsupportedPaymentTypeError)
end
end
describe "when paypal payment is settlement declined" do
it "returns an error" do
expect do
subject.create_payment_intent_or_charge!(braintree_merchant_account,
braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id),
400_100,
0,
"product-id",
nil,
statement_description: "dummy")
end.to raise_error do |error|
expect(error).to be_a(ChargeProcessorCardError)
expect(error.error_code).to eq("4001")
expect(error.message).to eq("Settlement Declined")
end
end
end
end
end
end
describe "#refund!" do
let(:braintree_merchant_account) { MerchantAccount.gumroad(BraintreeChargeProcessor.charge_processor_id) }
describe "when the charge processor is unavailable" do
before do
expect(Braintree::Transaction).to receive(:refund!).and_raise(Braintree::ServiceUnavailableError)
end
it "raises an error" do
expect { subject.refund!("dummy") }.to raise_error(ChargeProcessorUnavailableError)
end
end
describe "refunding an non-existant transaction" do
it "raises an error" do
expect do
subject.refund!("invalid-charge-id")
end.to raise_error(ChargeProcessorInvalidRequestError)
end
end
describe "fully refunding a charge" do
before do
@charge = subject.create_payment_intent_or_charge!(braintree_merchant_account,
braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id),
225_00,
0,
"product-id",
nil,
statement_description: "dummy").charge
end
describe "fully refunding a charge is successful" do
it "returns a BraintreeChargeRefund object" do
expect(subject.refund!(@charge.id)).to be_a(BraintreeChargeRefund)
end
it "returns the refund id" do
expect(subject.refund!(@charge.id).id).to match(/^[a-z0-9]+$/)
end
it "returns the charge id" do
expect(subject.refund!(@charge.id).charge_id).to eq(@charge.id)
end
end
describe "refunding an already fully refunded charge" do
before do
subject.refund!(@charge.id)
end
it "raises an error" do
expect do
subject.refund!(@charge.id)
end.to raise_error(ChargeProcessorAlreadyRefundedError)
end
end
describe "refunding an already chargedback charge, which will return a ValidationFailed without errors specified" do
before do
validation_failed_error_result = double
expect(validation_failed_error_result).to receive(:errors).and_return([])
validation_failed_error = Braintree::ValidationsFailed.new(validation_failed_error_result)
expect(Braintree::Transaction).to receive(:refund!).with(@charge.id).and_raise(validation_failed_error)
end
it "raises an error" do
expect do
subject.refund!(@charge.id)
end.to raise_error(ChargeProcessorInvalidRequestError)
end
end
end
describe "partially refunding a charge" do
before do
@charge = subject.create_payment_intent_or_charge!(braintree_merchant_account,
braintree_chargeable.get_chargeable_for(BraintreeChargeProcessor.charge_processor_id),
225_00,
0,
"product-id",
nil,
statement_description: "dummy").charge
end
describe "partially refunding a valid charge" do
it "returns a BraintreeChargeRefund when amount is refundable" do
expect(subject.refund!(@charge.id, amount_cents: 125_00)).to be_a(BraintreeChargeRefund)
end
it "returns the refund id when amount is refundable" do
expect(subject.refund!(@charge.id, amount_cents: 125_00).id).to match(/^[a-z0-9]+$/)
end
it "returns the charge id when amount is refundable" do
expect(subject.refund!(@charge.id, amount_cents: 125_00).charge_id).to eq(@charge.id)
end
end
end
end
describe "#holder_of_funds" do
let(:merchant_account) { MerchantAccount.gumroad(BraintreeChargeProcessor.charge_processor_id) }
it "returns Gumroad" do
expect(subject.holder_of_funds(merchant_account)).to eq(HolderOfFunds::GUMROAD)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/braintree/braintree_chargeable_nonce_spec.rb | spec/business/payments/charging/implementations/braintree/braintree_chargeable_nonce_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BraintreeChargeableNonce, :vcr do
describe "#prepare!" do
it "throws a validation failure on using an invalid chargeable" do
expect do
chargeable = BraintreeChargeableNonce.new("invalid", nil)
chargeable.prepare!
end.to raise_exception(ChargeProcessorInvalidRequestError)
end
it "throws a validation failure on using an already consumed chargeable" do
expect do
chargeable = BraintreeChargeableNonce.new(Braintree::Test::Nonce::Consumed, nil)
chargeable.prepare!
end.to raise_exception(ChargeProcessorInvalidRequestError)
end
describe "credit card chargeable" do
it "accepts a valid chargeable and displays expected card information" do
chargeable = BraintreeChargeableNonce.new(Braintree::Test::Nonce::Transactable, nil)
chargeable.prepare!
expect(chargeable.braintree_customer_id).to_not be(nil)
expect(chargeable.fingerprint).to eq("9a09e816d246aac4198e616ca18abe6e")
expect(chargeable.card_type).to eq(CardType::VISA)
expect(chargeable.last4).to eq("1881")
expect(chargeable.expiry_month).to eq("12")
expect(chargeable.expiry_year).to eq("2020")
end
end
describe "PayPal account chargeable" do
it "accepts a valid chargeable and displays expected account information" do
chargeable = BraintreeChargeableNonce.new(Braintree::Test::Nonce::PayPalFuturePayment, nil)
chargeable.prepare!
expect(chargeable.braintree_customer_id).to_not be(nil)
expect(chargeable.fingerprint).to eq("paypal_jane.doe@example.com")
expect(chargeable.card_type).to eq(CardType::PAYPAL)
expect(chargeable.last4).to eq(nil)
expect(chargeable.visual).to eq("jane.doe@example.com")
expect(chargeable.expiry_month).to eq(nil)
expect(chargeable.expiry_year).to eq(nil)
end
end
end
describe "#charge_processor_id" do
let(:chargeable) { BraintreeChargeableNonce.new(Braintree::Test::Nonce::PayPalFuturePayment, nil) }
it "returns 'stripe'" do
expect(chargeable.charge_processor_id).to eq "braintree"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/braintree/braintree_charge_spec.rb | spec/business/payments/charging/implementations/braintree/braintree_charge_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BraintreeCharge, :vcr do
describe "charge without fingerprint or card details" do
before do
chargeable_element = BraintreeChargeableNonce.new(Braintree::Test::Nonce::PayPalFuturePayment, nil)
chargeable_element.prepare!
params = {
merchant_account_id: BRAINTREE_MERCHANT_ACCOUNT_ID_FOR_SUPPLIERS,
amount: 100_00 / 100.0,
customer_id: chargeable_element.reusable_token!(nil),
options: {
submit_for_settlement: true
}
}
@transaction = Braintree::Transaction.sale!(params)
@transaction_id = @transaction.id
end
it "retrieves the card information for a paypal account successfully" do
test_transaction = Braintree::Transaction.find(@transaction_id)
test_charge = BraintreeCharge.new(test_transaction, load_extra_details: true)
expect(test_charge.card_instance_id).to eq(test_transaction.credit_card_details.token)
expect(test_charge.card_last4).to eq(nil)
expect(test_charge.card_type).to eq(CardType::UNKNOWN)
expect(test_charge.card_number_length).to eq(nil)
expect(test_charge.card_expiry_month).to eq(nil)
expect(test_charge.card_expiry_year).to eq(nil)
expect(test_charge.card_country).to eq(nil)
expect(test_charge.card_zip_code).to eq(nil)
expect(test_charge.card_fingerprint).to eq("paypal_jane.doe@example.com")
end
it "has a simple flow of funds" do
charge = BraintreeCharge.new(@transaction, load_extra_details: false)
expect(charge.flow_of_funds.issued_amount.currency).to eq(Currency::USD)
expect(charge.flow_of_funds.issued_amount.cents).to eq(100_00)
expect(charge.flow_of_funds.settled_amount.currency).to eq(Currency::USD)
expect(charge.flow_of_funds.settled_amount.cents).to eq(100_00)
expect(charge.flow_of_funds.gumroad_amount.currency).to eq(Currency::USD)
expect(charge.flow_of_funds.gumroad_amount.cents).to eq(100_00)
expect(charge.flow_of_funds.merchant_account_gross_amount).to be_nil
expect(charge.flow_of_funds.merchant_account_net_amount).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/business/payments/charging/implementations/braintree/braintree_chargeable_transient_customer_spec.rb | spec/business/payments/charging/implementations/braintree/braintree_chargeable_transient_customer_spec.rb | # frozen_string_literal: true
describe BraintreeChargeableTransientCustomer, :vcr do
let(:transient_customer_store_key) { "transient-customer-token-key" }
describe "tokenize_nonce_to_transient_customer" do
it "stores the customer id with an expiry in redis" do
frozen_time = Time.current
travel_to(frozen_time) do
result = BraintreeChargeableTransientCustomer.tokenize_nonce_to_transient_customer(Braintree::Test::Nonce::PayPalFuturePayment,
transient_customer_store_key)
expect(result).to_not be(nil)
expect(result).to be_a(BraintreeChargeableTransientCustomer)
transient_braintree_customer_store = Redis::Namespace.new(:transient_braintree_customer_store, redis: $redis)
transient_customer_token = transient_braintree_customer_store.get(transient_customer_store_key)
expect(transient_customer_token).to_not be(nil)
end
end
it "stores the value in redis with expiry" do
braintree_double = double("braintree")
allow(braintree_double).to receive(:id).and_return(123)
allow(Braintree::Customer).to receive(:create!).and_return(braintree_double)
expect_any_instance_of(Redis::Namespace).to receive(:set).with(transient_customer_store_key, ObfuscateIds.encrypt(123), ex: 5.minutes)
BraintreeChargeableTransientCustomer.tokenize_nonce_to_transient_customer(Braintree::Test::Nonce::PayPalFuturePayment, transient_customer_store_key)
end
it "returns an error message when the nonce is invalid" do
expect do
BraintreeChargeableTransientCustomer.tokenize_nonce_to_transient_customer("invalid", transient_customer_store_key)
end.to raise_error(ChargeProcessorInvalidRequestError)
end
it "returns an error message when the charge processor is down" do
expect(Braintree::Customer).to receive(:create!).and_raise(Braintree::ServiceUnavailableError)
expect do
BraintreeChargeableTransientCustomer.tokenize_nonce_to_transient_customer(Braintree::Test::Nonce::PayPalFuturePayment, transient_customer_store_key)
end.to raise_error(ChargeProcessorUnavailableError)
end
end
describe "from_transient_customer_store_key" do
before do
@frozen_time = Time.current
travel_to(@frozen_time) do
BraintreeChargeableTransientCustomer.tokenize_nonce_to_transient_customer(Braintree::Test::Nonce::PayPalFuturePayment,
transient_customer_store_key)
end
end
it "raises an error if transient customer storage does not have any contents" do
expect do
BraintreeChargeableTransientCustomer.from_transient_customer_store_key("this-key-doesnt-exists")
end.to raise_error(ChargeProcessorInvalidRequestError)
end
describe "valid, non-expired storage entry exists" do
it "returns a constructed object if the storage contents have not expired" do
travel_to(@frozen_time) do
transient_customer = BraintreeChargeableTransientCustomer.from_transient_customer_store_key(transient_customer_store_key)
expect(transient_customer).to be_a(BraintreeChargeableTransientCustomer)
end
end
end
end
describe "#prepare!" do
before do
@frozen_time = Time.current
travel_to(@frozen_time) do
BraintreeChargeableTransientCustomer.tokenize_nonce_to_transient_customer(Braintree::Test::Nonce::PayPalFuturePayment,
transient_customer_store_key)
end
end
it "throws a validation failure on using an invalid customer ID" do
expect do
chargeable = BraintreeChargeableTransientCustomer.new("invalid", nil)
chargeable.prepare!
end.to raise_exception(ChargeProcessorInvalidRequestError)
end
it "succeeds as long as we can find a customer" do
travel_to(@frozen_time + 2.minutes) do
transient_customer = BraintreeChargeableTransientCustomer.from_transient_customer_store_key(transient_customer_store_key)
expect(transient_customer).to be_a(BraintreeChargeableTransientCustomer)
transient_customer.prepare!
expect(transient_customer.fingerprint).to eq("paypal_jane.doe@example.com")
end
end
end
describe "#charge_processor_id" do
let(:chargeable) { BraintreeChargeableTransientCustomer.new(nil, nil) }
it "returns 'stripe'" do
expect(chargeable.charge_processor_id).to eq "braintree"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/stripe/stripe_charge_intent_spec.rb | spec/business/payments/charging/implementations/stripe/stripe_charge_intent_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StripeChargeIntent, :vcr do
include StripeChargesHelper
let(:processor_payment_intent) do
create_stripe_payment_intent(StripePaymentMethodHelper.success.to_stripejs_payment_method_id,
amount: 1_00,
currency: "usd")
end
subject (:stripe_charge_intent) { described_class.new(payment_intent: processor_payment_intent) }
describe "#id" do
it "returns the ID of Stripe payment intent" do
expect(stripe_charge_intent.id).to eq(processor_payment_intent.id)
end
end
describe "#client_secret" do
it "returns the client secret of Stripe payment intent" do
expect(stripe_charge_intent.client_secret).to eq(processor_payment_intent.client_secret)
end
end
context "when Stripe payment intent requires confirmation" do
let(:stripe_payment_method_id) { StripePaymentMethodHelper.success.to_stripejs_payment_method_id }
let(:processor_payment_intent) do
params = {
payment_method: stripe_payment_method_id,
payment_method_types: ["card"],
amount: 1_00,
currency: "usd"
}
Stripe::PaymentIntent.create(params)
end
it "is not successful" do
expect(stripe_charge_intent.succeeded?).to eq(false)
end
it "requires confirmation" do
expect(stripe_charge_intent.payment_intent.status == StripeIntentStatus::REQUIRES_CONFIRMATION).to eq(true)
end
it "does not load the charge" do
expect(ChargeProcessor).not_to receive(:get_charge)
expect(stripe_charge_intent.charge).to be_blank
end
end
context "when Stripe payment intent is successful" do
let(:stripe_payment_method_id) { StripePaymentMethodHelper.success.to_stripejs_payment_method_id }
let(:processor_payment_intent) do
create_stripe_payment_intent(stripe_payment_method_id, amount: 1_00, currency: "usd")
end
before do
processor_payment_intent.confirm
end
it "is successful" do
expect(stripe_charge_intent.succeeded?).to eq(true)
end
it "does not require action" do
expect(stripe_charge_intent.requires_action?).to eq(false)
end
it "loads the charge" do
expect(stripe_charge_intent.charge.id).to eq(processor_payment_intent.latest_charge)
end
end
context "when Stripe payment intent is not successful" do
let(:processor_payment_intent) do
create_stripe_payment_intent(nil,
amount: 1_00,
currency: "usd")
end
it "is not successful" do
expect(stripe_charge_intent.succeeded?).to eq(false)
end
it "does not require action" do
expect(stripe_charge_intent.requires_action?).to eq(false)
end
it "does not load the charge" do
expect(ChargeProcessor).not_to receive(:get_charge)
expect(stripe_charge_intent.charge).to be_blank
end
end
context "when Stripe payment intent is canceled" do
let(:processor_payment_intent) do
payment_intent = create_stripe_payment_intent(StripePaymentMethodHelper.success.to_stripejs_payment_method_id,
amount: 1_00,
currency: "usd")
ChargeProcessor.cancel_payment_intent!(MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id), payment_intent.id)
end
it "is canceled" do
expect(stripe_charge_intent.canceled?).to eq(true)
end
it "is not successful" do
expect(stripe_charge_intent.succeeded?).to eq(false)
end
it "does not require action" do
expect(stripe_charge_intent.requires_action?).to eq(false)
end
it "does not load the charge" do
expect(ChargeProcessor).not_to receive(:get_charge)
expect(stripe_charge_intent.charge).to be_blank
end
end
context "when Stripe payment intent requires action" do
let(:stripe_payment_method_id) { StripePaymentMethodHelper.success_with_sca.to_stripejs_payment_method_id }
let(:processor_payment_intent) do
create_stripe_payment_intent(stripe_payment_method_id, amount: 1_00, currency: "usd")
end
before do
processor_payment_intent.confirm
end
it "is not successful" do
expect(stripe_charge_intent.succeeded?).to eq(false)
end
it "requires action" do
expect(stripe_charge_intent.requires_action?).to eq(true)
end
it "does not load the charge" do
expect(ChargeProcessor).not_to receive(:get_charge)
expect(stripe_charge_intent.charge).to be_blank
end
context "when next action type is unsupported" do
before do
allow(processor_payment_intent.next_action).to receive(:type).and_return "redirect_to_url"
end
it "notifies us via Bugsnag" do
expect(Bugsnag).to receive(:notify).with(/requires an unsupported action/)
described_class.new(payment_intent: processor_payment_intent)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/stripe/stripe_charge_processor_spec.rb | spec/business/payments/charging/implementations/stripe/stripe_charge_processor_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StripeChargeProcessor, :vcr do
include CurrencyHelper
include StripeMerchantAccountHelper
include StripeChargesHelper
describe ".charge_processor_id" do
it "is 'stripe'" do
expect(described_class.charge_processor_id).to eq "stripe"
end
end
describe "#get_chargeable_for_params" do
describe "with invalid params" do
it "returns nil" do
expect(subject.get_chargeable_for_params({}, nil)).to be(nil)
end
end
context "with Stripe token" do
describe "with only token" do
let(:token) { CardParamsSpecHelper.success.to_stripejs_token }
it "returns a chargeable token" do
expect(StripeChargeableToken).to receive(:new).with(token, nil, product_permalink: nil).and_call_original
expect(subject.get_chargeable_for_params({ stripe_token: token }, nil)).to be_a(StripeChargeableToken)
end
end
describe "with token and zip code" do
let(:token) { CardParamsSpecHelper.success.to_stripejs_token }
it "returns a chargeable token" do
expect(StripeChargeableToken).to receive(:new).with(token, nil, product_permalink: nil).and_call_original
chargeable_token = subject.get_chargeable_for_params({ stripe_token: token, cc_zipcode: "12345" }, nil)
expect(chargeable_token).to be_a(StripeChargeableToken)
expect(chargeable_token.zip_code).to be(nil)
end
end
describe "with token and zip code and zip code required" do
let(:token) { CardParamsSpecHelper.success.with_zip_code("12345").to_stripejs_token }
it "returns a chargeable token" do
expect(StripeChargeableToken).to receive(:new).with(token, "12345", product_permalink: nil).and_call_original
chargeable_token = subject.get_chargeable_for_params({ stripe_token: token, cc_zipcode: "12345", cc_zipcode_required: "true" }, nil)
expect(chargeable_token).to be_a(StripeChargeableToken)
expect(chargeable_token.zip_code).to eq("12345")
end
end
end
context "with Stripe payment method" do
describe "with only a payment method" do
let(:payment_method_id) { StripePaymentMethodHelper.success.to_stripejs_payment_method_id }
it "returns a chargeable payment method" do
chargeable_payment_method = subject.get_chargeable_for_params({ stripe_payment_method_id: payment_method_id }, nil)
expect(chargeable_payment_method).to be_a(StripeChargeablePaymentMethod)
expect(chargeable_payment_method.payment_method_id).to eq(payment_method_id)
end
end
describe "with a payment method" do
let(:payment_method_id) { StripePaymentMethodHelper.success.to_stripejs_payment_method_id }
it "returns a chargeable payment method" do
chargeable_payment_method = subject.get_chargeable_for_params({ stripe_payment_method_id: payment_method_id }, nil)
expect(chargeable_payment_method).to be_a(StripeChargeablePaymentMethod)
end
end
describe "with a payment method and a zip code and zip code not required" do
let(:payment_method_id) { StripePaymentMethodHelper.success.to_stripejs_payment_method_id }
it "returns a chargeable payment method" do
chargeable_payment_method = subject.get_chargeable_for_params({ stripe_payment_method_id: payment_method_id, cc_zipcode: "12345" }, nil)
expect(chargeable_payment_method).to be_a(StripeChargeablePaymentMethod)
expect(chargeable_payment_method.zip_code).to be(nil)
end
end
describe "with a payment method and a zip code and zip code required" do
let(:payment_method_id) { StripePaymentMethodHelper.success.with_zip_code("12345").to_stripejs_payment_method_id }
it "returns a chargeable payment method" do
chargeable_payment_method = subject.get_chargeable_for_params({ stripe_payment_method_id: payment_method_id, cc_zipcode: "12345", cc_zipcode_required: "true" }, nil)
expect(chargeable_payment_method).to be_a(StripeChargeablePaymentMethod)
expect(chargeable_payment_method.zip_code).to eq("12345")
end
end
end
end
describe "#get_chargeable_for_data" do
describe "with data" do
it "returns a chargeable" do
chargeable = subject.get_chargeable_for_data(
"customer-id",
"payment_method_id",
"fingerprint",
nil,
nil,
"4242",
16,
"**** **** **** 4242",
1,
2015,
CardType::VISA,
"US"
)
expect(chargeable.reusable_token!(nil)).to eq("customer-id")
expect(chargeable.payment_method_id).to eq("payment_method_id")
expect(chargeable.fingerprint).to eq("fingerprint")
expect(chargeable.last4).to eq("4242")
expect(chargeable.number_length).to eq(16)
expect(chargeable.visual).to eq("**** **** **** 4242")
expect(chargeable.expiry_month).to eq(1)
expect(chargeable.expiry_year).to eq(2015)
expect(chargeable.card_type).to eq(CardType::VISA)
expect(chargeable.country).to eq("US")
expect(chargeable.zip_code).to be(nil)
end
end
describe "with data including zip code" do
it "returns a chargeable with zip code" do
chargeable = subject.get_chargeable_for_data(
"customer-id",
"payment_method_id",
"fingerprint",
nil,
nil,
"4242",
16,
"**** **** **** 4242",
1,
2015,
CardType::VISA,
"US",
"94107"
)
expect(chargeable.reusable_token!(nil)).to eq("customer-id")
expect(chargeable.payment_method_id).to eq("payment_method_id")
expect(chargeable.fingerprint).to eq("fingerprint")
expect(chargeable.last4).to eq("4242")
expect(chargeable.number_length).to eq(16)
expect(chargeable.visual).to eq("**** **** **** 4242")
expect(chargeable.expiry_month).to eq(1)
expect(chargeable.expiry_year).to eq(2015)
expect(chargeable.card_type).to eq(CardType::VISA)
expect(chargeable.country).to eq("US")
expect(chargeable.zip_code).to eq("94107")
end
end
end
describe "#get_charge" do
describe "with an invalid charge id" do
let(:charge_id) { "an-invalid-charge-id" }
it "raises error" do
expect { subject.get_charge(charge_id) }.to raise_error(ChargeProcessorInvalidRequestError)
end
end
describe "when the charge processor is unavailable" do
before do
expect(Stripe::Charge).to receive(:retrieve).and_raise(Stripe::APIConnectionError)
end
it "raises error" do
expect { subject.get_charge("a-charge-id") }.to raise_error(ChargeProcessorUnavailableError)
end
end
describe "with a valid charge id" do
let(:stripe_charge) do
stripe_charge = create_stripe_charge(StripePaymentMethodHelper.success.to_stripejs_payment_method_id,
amount: 1_00,
currency: "usd",
)
Stripe::Charge.retrieve(id: stripe_charge.id, expand: %w[balance_transaction])
end
let(:charge_id) { stripe_charge.id }
let(:charge) { subject.get_charge(charge_id) }
it "returns a charge object" do
expect(charge).to be_a(BaseProcessorCharge)
end
it "has matching id" do
expect(charge.id).to eq(stripe_charge.id)
end
it "has matching fingerprint" do
expect(charge.card_fingerprint).to eq(stripe_charge.payment_method_details.card.fingerprint)
end
it "has matching fee" do
expect(charge.fee).to eq(stripe_charge.balance_transaction.fee_details.first.amount)
end
it "has matching fee cents" do
expect(charge.fee_currency).to eq(stripe_charge.balance_transaction.fee_details.first.currency)
end
end
end
describe "#search_charge" do
it "returns a Stripe::Charge object with details of the charge attached to the given purchase" do
allow_any_instance_of(Purchase).to receive(:id).and_return(115787) # Charge with no destination connect account
charge = subject.search_charge(purchase: create(:purchase))
expect(charge).to be_a(Stripe::Charge)
expect(charge.id).to eq("ch_0IvAB29e1RjUNIyY1hyx6deT")
expect(charge.status).to eq("succeeded")
allow_any_instance_of(Purchase).to receive(:id).and_return(115780) # Charge with a destination connect account
charge = subject.search_charge(purchase: create(:purchase))
expect(charge).to be_a(Stripe::Charge)
expect(charge.id).to eq("ch_0Iv6ZR9e1RjUNIyYVBMK1ueH")
expect(charge.status).to eq("succeeded")
# Charge where transfer_group does not match but metadata matches
allow_any_instance_of(Purchase).to receive(:id).and_return(1234567890)
allow_any_instance_of(Purchase).to receive(:external_id).and_return("6RNPNSondrJ8t9SqSjxTjw==")
charge = subject.search_charge(purchase: create(:purchase, created_at: Time.zone.at(1621973384)))
expect(charge).to be_a(Stripe::Charge)
expect(charge.id).to eq("ch_0Iv6ZR9e1RjUNIyYVBMK1ueH")
expect(charge.status).to eq("succeeded")
end
it "returns a Stripe::Charge object for the given Stripe Connect purchase" do
merchant_account = create(:merchant_account_stripe_connect, charge_processor_merchant_id: "acct_1SOb0DEwFhlcVS6d", currency: "usd")
allow_any_instance_of(Purchase).to receive(:id).and_return(88) # Charge on a Stripe Connect account
charge = subject.search_charge(purchase: create(:purchase, link: create(:product, user: merchant_account.user), merchant_account:))
expect(charge).to be_a(Stripe::Charge)
expect(charge.id).to eq("ch_3Mf0bBKQKir5qdfM1FZ0agOH")
expect(charge.status).to eq("succeeded")
end
it "returns nil if no stripe charge is found for the given purchase" do
allow_any_instance_of(Purchase).to receive(:id).and_return(1234567890)
expect(subject.search_charge(purchase: create(:purchase, created_at: Time.zone.at(1621973384)))).to be(nil)
end
end
describe "#fight_chargeback" do
let(:disputed_purchase) do
create(
:disputed_purchase,
full_name: "John Example",
street_address: "123 Sample St",
city: "San Francisco",
state: "CA",
country: "United States",
zip_code: "12343",
ip_state: "California",
ip_country: "United States",
credit_card_zipcode: "1234",
link: create(:physical_product),
url_redirect: create(:url_redirect)
)
end
let(:purchase_product_url) do
Rails.application.routes.url_helpers.purchase_product_url(
disputed_purchase.external_id,
host: DOMAIN,
protocol: PROTOCOL,
anchor: "refund-policy",
)
end
let!(:shipment) do
create(
:shipment,
carrier: "UPS",
tracking_number: "123456",
purchase: disputed_purchase,
ship_state: "shipped",
shipped_at: DateTime.parse("2023-02-10 14:55:32")
)
end
before do
dispute = create(:dispute_formalized, purchase: disputed_purchase)
disputed_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."
)
disputed_purchase.events.create!(
event_name: Event::NAME_PRODUCT_REFUND_POLICY_FINE_PRINT_VIEW,
link_id: disputed_purchase.link_id,
browser_guid: disputed_purchase.browser_guid,
created_at: disputed_purchase.created_at - 1.second
)
sample_image = File.read(Rails.root.join("spec", "support", "fixtures", "test-small.jpg"))
allow(DisputeEvidence::GenerateReceiptImageService).to(
receive(:perform).with(disputed_purchase).and_return(sample_image)
)
allow(DisputeEvidence::GenerateRefundPolicyImageService).to(
receive(:perform)
.with(url: purchase_product_url, mobile_purchase: false, open_fine_print_modal: true, max_size_allowed: anything)
.and_return(sample_image)
)
DisputeEvidence.create_from_dispute!(dispute)
end
let!(:stripe_charge) do
create_stripe_charge(StripePaymentMethodHelper.success_charge_disputed.to_stripejs_payment_method_id,
amount: 10_00,
currency: "usd")
end
let(:charge_id) do
stripe_charge.refresh
while stripe_charge.dispute.nil?
stripe_charge.refresh
end
stripe_charge.id
end
it "retrieves charge from stripe" do
expect(Stripe::Charge).to receive(:retrieve).with(charge_id).and_call_original
subject.fight_chargeback(charge_id, disputed_purchase.dispute.dispute_evidence)
end
it "calls update_dispute on the stripe charge with the evidence as a parameter" do
stripe_charge.refresh
dispute_evidence = disputed_purchase.dispute.dispute_evidence
dispute_evidence.update!(
reason_for_winning: "reason_for_winning text",
cancellation_rebuttal: "cancellation_rebuttal text",
refund_refusal_explanation: "refund_refusal_explanation text"
)
expect(Stripe::Charge).to receive(:retrieve).with(charge_id).and_call_original
expected_uncategorized_text = [
"The merchant should win the dispute because:\n#{dispute_evidence.reason_for_winning}",
dispute_evidence.uncategorized_text
].join("\n\n")
expect(Stripe::Dispute).to receive(:update).with(
stripe_charge.dispute,
evidence: hash_including({
billing_address: dispute_evidence.billing_address,
customer_email_address: dispute_evidence.customer_email,
customer_name: dispute_evidence.customer_name,
customer_purchase_ip: dispute_evidence.customer_purchase_ip,
product_description: dispute_evidence.product_description,
service_date: dispute_evidence.purchased_at.to_fs(:formatted_date_full_month),
shipping_address: dispute_evidence.shipping_address,
shipping_carrier: dispute_evidence.shipping_carrier,
shipping_date: dispute_evidence.shipped_at&.to_fs(:formatted_date_full_month),
shipping_tracking_number: dispute_evidence.shipping_tracking_number,
uncategorized_text: expected_uncategorized_text,
access_activity_log: dispute_evidence.access_activity_log,
refund_policy_disclosure: dispute_evidence.refund_policy_disclosure,
cancellation_rebuttal: dispute_evidence.cancellation_rebuttal,
refund_refusal_explanation: dispute_evidence.refund_refusal_explanation
})
).and_call_original
subject.fight_chargeback(charge_id, disputed_purchase.dispute.dispute_evidence)
end
it "includes the receipt image's Stripe file id in the dispute evidence" do
allow(Stripe::File).to receive(:create).and_return(double(id: "receipt_file"))
stripe_charge.refresh
expect(Stripe::Dispute).to receive(:update).with(
stripe_charge.dispute,
evidence: hash_including({ receipt: "receipt_file" })
)
subject.fight_chargeback(charge_id, disputed_purchase.dispute.dispute_evidence)
end
it "includes the customer communication file's Stripe file id in the dispute evidence" do
dispute_evidence = disputed_purchase.dispute.dispute_evidence
dispute_evidence.customer_communication_file.attach(fixture_file_upload("smilie.png"))
allow(Stripe::File).to receive(:create).and_return(double(id: "customer_communication_file"))
stripe_charge.refresh
expect(Stripe::Dispute).to receive(:update).with(
stripe_charge.dispute,
evidence: hash_including({ customer_communication: "customer_communication_file" })
)
subject.fight_chargeback(charge_id, disputed_purchase.dispute.dispute_evidence)
end
context "when the associated product is not a membership" do
it "includes the refund_policy's Stripe file id in the dispute evidence" do
allow(Stripe::File).to receive(:create).and_return(double(id: "refund_policy_file"))
stripe_charge.refresh
expect(Stripe::Dispute).to receive(:update).with(
stripe_charge.dispute,
evidence: hash_including({ refund_policy: "refund_policy_file" })
)
subject.fight_chargeback(charge_id, disputed_purchase.dispute.dispute_evidence)
end
end
context "when the associated product is a membership" do
let(:disputed_purchase) do
create(
:membership_purchase,
price_cents: 100,
url_redirect: create(:url_redirect),
chargeable: build(:chargeable_success_charge_disputed),
chargeback_date: Time.current
)
end
it "includes the cancellation_policy's Stripe file id in the dispute evidence" do
allow(Stripe::File).to receive(:create).and_return(double(id: "cancellation_policy_file"))
stripe_charge.refresh
expect(Stripe::Dispute).to receive(:update).with(
stripe_charge.dispute,
evidence: hash_including({ cancellation_policy: "cancellation_policy_file" })
)
subject.fight_chargeback(charge_id, disputed_purchase.dispute.dispute_evidence)
end
end
end
describe "#setup_future_charges!" do
let(:merchant_account) { create(:merchant_account, user: nil, charge_processor_id: described_class.charge_processor_id, charge_processor_merchant_id: nil) }
let(:stripe_card) { StripePaymentMethodHelper.success }
let(:payment_method_id) { stripe_card.to_stripejs_payment_method_id }
let(:customer_id) { stripe_card.to_stripejs_customer_id }
let(:chargeable) { StripeChargeablePaymentMethod.new(payment_method_id, customer_id:, zip_code: "12345", product_permalink: "xx") }
it "creates a setup intent" do
expect(Stripe::SetupIntent).to receive(:create).with(hash_including(payment_method: payment_method_id, customer: customer_id)).and_call_original
setup_intent = subject.setup_future_charges!(merchant_account, chargeable)
expect(setup_intent).to be_a(StripeSetupIntent)
expect(setup_intent.succeeded?).to eq(true)
expect(setup_intent.requires_action?).to eq(false)
end
context "for a managed Stripe account" do
let(:user) { create(:user) }
let(:stripe_account) { create_verified_stripe_account(country: "US") }
let(:merchant_account) do
create(:merchant_account, user:, charge_processor_id: described_class.charge_processor_id, charge_processor_merchant_id: stripe_account.id)
end
it "creates a setup intent on behalf of a managed account" do
expect(Stripe::SetupIntent).to receive(:create).with(hash_including(payment_method: payment_method_id, customer: customer_id)).and_call_original
subject.setup_future_charges!(merchant_account, chargeable)
end
end
context "for a card with SCA support" do
let(:stripe_card) { StripePaymentMethodHelper.success_with_sca }
it "creates a setup intent that requires action" do
expect(Stripe::SetupIntent).to receive(:create).with(hash_including(payment_method: payment_method_id, customer: customer_id)).and_call_original
setup_intent = subject.setup_future_charges!(merchant_account, chargeable)
expect(setup_intent).to be_a(StripeSetupIntent)
expect(setup_intent.succeeded?).to eq(false)
expect(setup_intent.requires_action?).to eq(true)
end
end
# https://support.stripe.com/questions/faqs-for-setup-intents-and-payment-intents-api-recurring-charges-from-indian-cardholders
describe "Support for RBI regulations for Indian cards" do
let(:manual_3ds_params) { { payment_method_options: { card: { request_three_d_secure: "any" } } } }
context "for an Indian card with SCA support" do
let(:stripe_card) { StripePaymentMethodHelper.build(token: "tok_in") } # https://stripe.com/docs/testing#international-cards
it "ignores the default Radar rules and always requests 3DS" do
expect(Stripe::SetupIntent).to receive(:create).with(hash_including(manual_3ds_params)).and_call_original
setup_intent = subject.setup_future_charges!(merchant_account, chargeable)
expect(setup_intent).to be_a(StripeSetupIntent)
expect(setup_intent.succeeded?).to eq(false)
expect(setup_intent.requires_action?).to eq(true)
end
it "creates a mandate if future off-session charges are required" do
mandate_options = {
payment_method_options: {
card: {
mandate_options: {
reference: StripeChargeProcessor::MANDATE_PREFIX + "UniqueMandateID",
amount_type: "maximum",
amount: 10_00,
currency: "usd",
start_date: Date.new(2023, 12, 25).to_time.to_i,
interval: "sporadic",
supported_types: ["india"]
},
request_three_d_secure: "any"
}
}
}
expect(Stripe::SetupIntent).to receive(:create).with(hash_including(mandate_options)).and_call_original
setup_intent = subject.setup_future_charges!(merchant_account, chargeable, mandate_options:)
expect(setup_intent).to be_a(StripeSetupIntent)
expect(setup_intent.succeeded?).to eq(false)
expect(setup_intent.requires_action?).to eq(true)
end
end
context "for a non-Indian card" do
context "with SCA support" do
let(:stripe_card) { StripePaymentMethodHelper.success_with_sca }
it "follows the default Radar rules and does not request 3DS manually" do
expect(Stripe::SetupIntent).to receive(:create).with(hash_excluding(manual_3ds_params)).and_call_original
setup_intent = subject.setup_future_charges!(merchant_account, chargeable)
expect(setup_intent).to be_a(StripeSetupIntent)
expect(setup_intent.succeeded?).to eq(false)
expect(setup_intent.requires_action?).to eq(true)
end
end
context "without SCA support" do
let(:stripe_card) { StripePaymentMethodHelper.success }
it "follows the default Radar rules and does not request 3DS manually" do
expect(Stripe::SetupIntent).to receive(:create).with(hash_excluding(manual_3ds_params)).and_call_original
setup_intent = subject.setup_future_charges!(merchant_account, chargeable)
expect(setup_intent).to be_a(StripeSetupIntent)
expect(setup_intent.succeeded?).to eq(true)
expect(setup_intent.requires_action?).to eq(false)
end
end
end
end
end
describe "#create_payment_intent_or_charge!" do
let(:merchant_account) { create(:merchant_account, user: nil, charge_processor_id: described_class.charge_processor_id, charge_processor_merchant_id: nil) }
let(:payment_method_id) { StripePaymentMethodHelper.success.to_stripejs_payment_method_id }
let(:chargeable) { StripeChargeablePaymentMethod.new(payment_method_id, zip_code: "12345", product_permalink: "xx") }
it "creates payment intent" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_including(payment_method: payment_method_id)).and_call_original
subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description")
end
it "passes on the reference" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_including(metadata: hash_including(purchase: "reference"))).and_call_original
subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description")
end
it "passes on the description" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_including(description: "test description")).and_call_original
subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description")
end
context "for a card without SCA support" do
let(:payment_method_id) { StripePaymentMethodHelper.success.to_stripejs_payment_method_id }
it "returns a successful StripeChargeIntent with a charge" do
charge_intent = subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description")
expect(charge_intent).to be_a(StripeChargeIntent)
expect(charge_intent.succeeded?).to eq(true)
expect(charge_intent.requires_action?).to eq(false)
expect(charge_intent.charge).to be_a(StripeCharge)
end
end
context "for a card with SCA support" do
let(:payment_method_id) { StripePaymentMethodHelper.success_with_sca.to_stripejs_payment_method_id }
context "when on-session" do
it "returns a StripeChargeIntent that requires action" do
charge_intent = subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description", off_session: false)
expect(charge_intent).to be_a(StripeChargeIntent)
expect(charge_intent.succeeded?).to eq(false)
expect(charge_intent.requires_action?).to eq(true)
expect(charge_intent.charge).to be_blank
end
end
context "when off-session" do
context "usage was prepared for card" do
let(:payment_method_id) { StripePaymentMethodHelper.success_future_usage_set_up.to_stripejs_payment_method_id }
it "returns a successful StripeChargeIntent" do
charge_intent = subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description", off_session: true)
expect(charge_intent).to be_a(StripeChargeIntent)
expect(charge_intent.succeeded?).to eq(true)
expect(charge_intent.requires_action?).to eq(false)
expect(charge_intent.charge).to be_a(StripeCharge)
end
end
context "usage was not prepared for card" do
it "fails with ChargeProcessorCardError" do
expect do
subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description", off_session: true)
end.to raise_error(ChargeProcessorCardError)
end
end
end
end
# https://support.stripe.com/questions/faqs-for-setup-intents-and-payment-intents-api-recurring-charges-from-indian-cardholders
describe "Support for RBI regulations for Indian cards" do
before do
chargeable.prepare!
end
let(:manual_3ds_params) { { payment_method_options: { card: { request_three_d_secure: "any" } } } }
context "when off-session" do
context "for an Indian card with SCA support" do
let(:payment_method_id) { StripePaymentMethodHelper.build(token: "tok_in").to_stripejs_payment_method_id } # https://stripe.com/docs/testing#international-cards
it "follows the default Radar rules and does not request 3DS manually" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_excluding(manual_3ds_params)).and_call_original
charge_intent = subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description", off_session: true)
expect(charge_intent).to be_a(StripeChargeIntent)
end
end
context "for a non-Indian card with SCA support" do
let(:payment_method_id) { StripePaymentMethodHelper.success_future_usage_set_up.to_stripejs_payment_method_id }
it "follows the default Radar rules and does not request 3DS manually" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_excluding(manual_3ds_params)).and_call_original
charge_intent = subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description", off_session: true)
expect(charge_intent).to be_a(StripeChargeIntent)
end
end
end
context "when on-session" do
context "when NOT setting up future usage" do
context "for an Indian card with SCA support" do
let(:payment_method_id) { StripePaymentMethodHelper.build(token: "tok_in").to_stripejs_payment_method_id } # https://stripe.com/docs/testing#international-cards
it "follows the default Radar rules and does not request 3DS manually" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_excluding(manual_3ds_params)).and_call_original
charge_intent = subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description", off_session: false)
expect(charge_intent).to be_a(StripeChargeIntent)
end
end
context "for a non-Indian card with SCA support" do
let(:payment_method_id) { StripePaymentMethodHelper.success_future_usage_set_up.to_stripejs_payment_method_id }
it "follows the default Radar rules and does not request 3DS manually" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_excluding(manual_3ds_params)).and_call_original
charge_intent = subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description", off_session: false)
expect(charge_intent).to be_a(StripeChargeIntent)
end
end
end
context "when setting up future usage" do
context "for an Indian card with SCA support" do
let(:payment_method_id) { StripePaymentMethodHelper.build(token: "tok_in").to_stripejs_payment_method_id } # https://stripe.com/docs/testing#international-cards
it "ignores the default Radar rules and always requests 3DS" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_including(manual_3ds_params)).and_call_original
charge_intent = subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description", off_session: false, setup_future_charges: true)
expect(charge_intent).to be_a(StripeChargeIntent)
end
end
context "for a non-Indian card with SCA support" do
let(:payment_method_id) { StripePaymentMethodHelper.success_future_usage_set_up.to_stripejs_payment_method_id }
it "follows the default Radar rules and does not request 3DS manually" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_excluding(manual_3ds_params)).and_call_original
charge_intent = subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description", off_session: false, setup_future_charges: true)
expect(charge_intent).to be_a(StripeChargeIntent)
end
end
end
end
end
describe "if a reusable token has been requested already" do
let(:reusable_token) { chargeable.reusable_token!(nil) }
it "charges the persistable token (stripe customer)" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_including(customer: reusable_token)).and_call_original
subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 30, "reference", "test description", off_session: false)
end
end
it "does not set a destination since it's on our stripe account" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_not_including(destination: anything)).and_call_original
subject.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 0_30, "reference", "test description")
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/stripe/stripe_chargeable_common_shared_examples.rb | spec/business/payments/charging/implementations/stripe/stripe_chargeable_common_shared_examples.rb | # frozen_string_literal: true
require "spec_helper"
shared_examples_for "stripe chargeable common" do
describe "#charge_processor_id" do
it "returns 'stripe'" do
expect(chargeable.charge_processor_id).to eq "stripe"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/stripe/stripe_setup_intent_spec.rb | spec/business/payments/charging/implementations/stripe/stripe_setup_intent_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StripeSetupIntent, :vcr do
include StripeChargesHelper
let(:processor_setup_intent) { create_stripe_setup_intent(StripePaymentMethodHelper.success.to_stripejs_payment_method_id) }
subject (:stripe_setup_intent) { described_class.new(processor_setup_intent) }
describe "#id" do
it "returns the ID of Stripe setup intent" do
expect(stripe_setup_intent.id).to eq(processor_setup_intent.id)
end
end
describe "#client_secret" do
it "returns the client secret of Stripe setup intent" do
expect(stripe_setup_intent.client_secret).to eq(processor_setup_intent.client_secret)
end
end
context "when Stripe setup intent is successful" do
let(:processor_setup_intent) do
create_stripe_setup_intent(StripePaymentMethodHelper.success.to_stripejs_payment_method_id)
end
it "is successful" do
expect(stripe_setup_intent.succeeded?).to eq(true)
end
it "does not require action" do
expect(stripe_setup_intent.requires_action?).to eq(false)
end
end
context "when Stripe payment intent is not successful" do
let(:processor_setup_intent) do
create_stripe_setup_intent(nil, confirm: false)
end
it "is not successful" do
expect(stripe_setup_intent.succeeded?).to eq(false)
end
it "does not require action" do
expect(stripe_setup_intent.requires_action?).to eq(false)
end
end
context "when Stripe payment intent is canceled" do
let(:processor_setup_intent) do
setup_intent = create_stripe_setup_intent(StripePaymentMethodHelper.success.to_stripejs_payment_method_id, confirm: false)
ChargeProcessor.cancel_setup_intent!(MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id), setup_intent.id)
end
it "is canceled" do
expect(stripe_setup_intent.canceled?).to eq(true)
end
it "is not successful" do
expect(stripe_setup_intent.succeeded?).to eq(false)
end
it "does not require action" do
expect(stripe_setup_intent.requires_action?).to eq(false)
end
end
context "when Stripe payment intent requires action" do
let(:processor_setup_intent) do
create_stripe_setup_intent(StripePaymentMethodHelper.success_with_sca.to_stripejs_payment_method_id)
end
it "is not successful" do
expect(stripe_setup_intent.succeeded?).to eq(false)
end
it "requires action" do
expect(stripe_setup_intent.requires_action?).to eq(true)
end
context "when next action type is unsupported" do
before do
allow(processor_setup_intent.next_action).to receive(:type).and_return "redirect_to_url"
end
it "notifies us via Bugsnag" do
expect(Bugsnag).to receive(:notify).with(/requires an unsupported action/)
described_class.new(processor_setup_intent)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/stripe/stripe_charge_radar_processor_spec.rb | spec/business/payments/charging/implementations/stripe/stripe_charge_radar_processor_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StripeChargeRadarProcessor, :vcr do
describe "#handle_event" do
let(:purchase) { create(:purchase) }
shared_examples_for "purchase doesn't exist without Stripe Connect" do
context "when not in production environment" do
it "does nothing" do
expect_any_instance_of(EarlyFraudWarning).not_to receive(:update_from_stripe!)
expect do
StripeChargeRadarProcessor.handle_event(stripe_params)
end.not_to change(EarlyFraudWarning, :count)
end
end
context "when in production environment" do
before do
allow(Rails.env).to receive(:production?).and_return(true)
end
it "raises error" do
expect_any_instance_of(EarlyFraudWarning).not_to receive(:update_from_stripe!)
expect do
StripeChargeRadarProcessor.handle_event(stripe_params)
end.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
shared_examples_for "purchase doesn't exist with Stripe Connect" do
context "when not in production environment" do
it "does nothing" do
expect_any_instance_of(EarlyFraudWarning).not_to receive(:update_from_stripe!)
StripeChargeRadarProcessor.handle_event(stripe_params)
end
end
context "when in production environment" do
before do
allow(Rails.env).to receive(:production?).and_return(true)
end
it "does nothing" do
expect_any_instance_of(EarlyFraudWarning).not_to receive(:update_from_stripe!)
StripeChargeRadarProcessor.handle_event(stripe_params)
end
end
end
describe "radar.early_fraud_warning.created" do
context "without Stripe Connect" do
let(:stripe_params) do
{
"id" => "evt_0O8n7L9e1RjUNIyY90W7gkV3",
"object" => "event",
"api_version" => "2020-08-27",
"created" => 1699116878,
"data" => {
"object" => {
"id" => "issfr_0O8n7K9e1RjUNIyYmTbvMMLa",
"object" => "radar.early_fraud_warning",
"actionable" => false,
"charge" => "ch_2O8n7J9e1RjUNIyY1rs9MIRL",
"created" => 1699116878,
"fraud_type" => "made_with_stolen_card",
"livemode" => false,
"payment_intent" => "pi_2O8n7J9e1RjUNIyY1X7FyY6q"
}
},
"livemode" => false,
"pending_webhooks" => 8,
"request" => {
"id" => "req_2WfpkRMdlbjEkY",
"idempotency_key" => "82f4bcef-7a1e-4a28-ac2d-2ae4ceb7fcbe"
},
"type" => "radar.early_fraud_warning.created"
}
end
describe "for a Purchase" do
context "when the purchase doesn't exist" do
it_behaves_like "purchase doesn't exist without Stripe Connect"
end
context "when the purchase is found" do
before do
purchase.update_attribute(:stripe_transaction_id, stripe_params["data"]["object"]["charge"])
end
it "handles the event by creating a new EFW record" do
expect_any_instance_of(EarlyFraudWarning).to receive(:update_from_stripe!).and_call_original
expect do
StripeChargeRadarProcessor.handle_event(stripe_params)
end.to change(EarlyFraudWarning, :count).by(1)
early_fraud_warning = EarlyFraudWarning.last
expect(early_fraud_warning.processor_id).to eq("issfr_0O8n7K9e1RjUNIyYmTbvMMLa")
expect(early_fraud_warning.purchase).to eq(purchase)
expect(early_fraud_warning.charge).to be_nil
expect(ProcessEarlyFraudWarningJob).to have_enqueued_sidekiq_job(early_fraud_warning.id)
end
end
end
describe "for a Charge" do
let(:charge) { create(:charge) }
before do
charge.purchases << purchase
charge.update!(processor_transaction_id: stripe_params["data"]["object"]["charge"])
end
it "handles the event by creating a new EFW record" do
expect_any_instance_of(EarlyFraudWarning).to receive(:update_from_stripe!).and_call_original
expect do
StripeChargeRadarProcessor.handle_event(stripe_params)
end.to change(EarlyFraudWarning, :count).by(1)
early_fraud_warning = EarlyFraudWarning.last
expect(early_fraud_warning.processor_id).to eq("issfr_0O8n7K9e1RjUNIyYmTbvMMLa")
expect(early_fraud_warning.purchase).to be_nil
expect(early_fraud_warning.charge).to eq(charge)
expect(ProcessEarlyFraudWarningJob).to have_enqueued_sidekiq_job(early_fraud_warning.id)
end
end
end
context "with Stripe Connect" do
let(:stripe_params) do
{
"id" => "evt_1ODwGzGFgEK9GGWTrZ2dh9EV",
"object" => "event",
"account" => "acct_1O9tZ6GFgEK9GGWT",
"api_version" => "2023-10-16",
"created" => 1700343713,
"data" => {
"object" => {
"id" => "issfr_1ODwGzGFgEK9GGWT8y4r0PWV",
"object" => "radar.early_fraud_warning",
"actionable" => true,
"charge" => "ch_3ODwGyGFgEK9GGWT1EQ1TzoG",
"created" => 1700343713,
"fraud_type" => "made_with_stolen_card",
"livemode" => false,
"payment_intent" => "pi_3ODwGyGFgEK9GGWT1oI9Ocjf"
}
},
"livemode" => false,
"pending_webhooks" => 4,
"request" => {
"id" => "req_1Sfh0xoBJ2JwtC",
"idempotency_key" => "2d4049d4-0485-4d45-8aa9-77cfc317c012"
},
"type" => "radar.early_fraud_warning.created"
}
end
context "when the purchase doesn't exist" do
it_behaves_like "purchase doesn't exist with Stripe Connect"
end
end
end
describe "radar.early_fraud_warning.updated" do
context "without Stripe Connect" do
let!(:stripe_params) do
{
"id" => "evt_0O8n869e1RjUNIyYetklSxRz",
"object" => "event",
"api_version" => "2020-08-27",
"created" => 1699116926,
"data" => {
"object" => {
"id" => "issfr_0O8n7K9e1RjUNIyYmTbvMMLa",
"object" => "radar.early_fraud_warning",
"actionable" => false,
"charge" => "ch_2O8n7J9e1RjUNIyY1rs9MIRL",
"created" => 1699116878,
"fraud_type" => "made_with_stolen_card",
"livemode" => false,
"payment_intent" => "pi_2O8n7J9e1RjUNIyY1X7FyY6q"
},
"previous_attributes" => {
"actionable" => true
}
},
"livemode" => false,
"pending_webhooks" => 4,
"request" => {
"id" => nil,
"idempotency_key" => nil
},
"type" => "radar.early_fraud_warning.updated"
}
end
describe "for a Purchase" do
let!(:early_fraud_warning) do
create(
:early_fraud_warning,
processor_id: "issfr_0O8n7K9e1RjUNIyYmTbvMMLa",
purchase:,
actionable: true
)
end
context "when the purchase doesn't exist" do
it_behaves_like "purchase doesn't exist without Stripe Connect"
end
context "when the purchase is found" do
before do
purchase.update_attribute(:stripe_transaction_id, stripe_params["data"]["object"]["charge"])
end
it "handles the event without creating a new EFW record" do
expect_any_instance_of(EarlyFraudWarning).to receive(:update_from_stripe!).and_call_original
expect do
StripeChargeRadarProcessor.handle_event(stripe_params)
end.not_to change(EarlyFraudWarning, :count)
expect(early_fraud_warning.reload.actionable).to eq(false)
expect(early_fraud_warning.purchase).to eq(purchase)
expect(early_fraud_warning.charge).to be_nil
expect(ProcessEarlyFraudWarningJob).to have_enqueued_sidekiq_job(early_fraud_warning.id)
end
end
end
describe "for a Charge" do
let(:charge) { create(:charge) }
let!(:early_fraud_warning) do
create(
:early_fraud_warning,
processor_id: "issfr_0O8n7K9e1RjUNIyYmTbvMMLa",
charge:,
purchase: nil,
actionable: true
)
end
before do
charge.purchases << purchase
charge.update!(processor_transaction_id: stripe_params["data"]["object"]["charge"])
end
it "handles the event without creating a new EFW record" do
expect_any_instance_of(EarlyFraudWarning).to receive(:update_from_stripe!).and_call_original
expect do
StripeChargeRadarProcessor.handle_event(stripe_params)
end.not_to change(EarlyFraudWarning, :count)
early_fraud_warning = EarlyFraudWarning.last
expect(early_fraud_warning.reload.actionable).to eq(false)
expect(early_fraud_warning.purchase).to be_nil
expect(early_fraud_warning.charge).to eq(charge)
expect(ProcessEarlyFraudWarningJob).to have_enqueued_sidekiq_job(early_fraud_warning.id)
end
end
end
context "with Stripe Connect" do
let(:stripe_params) do
{
"id" => "evt_1ODwGzGFgEK9GGWTrZ2dh9EV",
"object" => "event",
"account" => "acct_1O9tZ6GFgEK9GGWT",
"api_version" => "2023-10-16",
"created" => 1700343713,
"data" => {
"object" => {
"id" => "issfr_1ODwGzGFgEK9GGWT8y4r0PWV",
"object" => "radar.early_fraud_warning",
"actionable" => true,
"charge" => "ch_3ODwGyGFgEK9GGWT1EQ1TzoG",
"created" => 1700343713,
"fraud_type" => "made_with_stolen_card",
"livemode" => false,
"payment_intent" => "pi_3ODwGyGFgEK9GGWT1oI9Ocjf"
}
},
"livemode" => false,
"pending_webhooks" => 4,
"request" => {
"id" => "req_1Sfh0xoBJ2JwtC",
"idempotency_key" => "2d4049d4-0485-4d45-8aa9-77cfc317c012"
},
"type" => "radar.early_fraud_warning.created"
}
end
context "when the purchase doesn't exist" do
it_behaves_like "purchase doesn't exist with Stripe Connect"
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/business/payments/charging/implementations/stripe/stripe_charge_spec.rb | spec/business/payments/charging/implementations/stripe/stripe_charge_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "business/payments/charging/charge_shared_examples"
describe StripeCharge, :vcr do
include StripeMerchantAccountHelper
include StripeChargesHelper
let(:currency) { Currency::USD }
let(:amount_cents) { 1_00 }
let(:stripe_charge) do
stripe_charge = create_stripe_charge(StripePaymentMethodHelper.success.to_stripejs_payment_method_id,
amount: amount_cents,
currency:
)
Stripe::Charge.retrieve(id: stripe_charge.id, expand: %w[balance_transaction])
end
let(:subject) { described_class.new(stripe_charge, stripe_charge.balance_transaction, nil, nil, nil) }
it_behaves_like "a base processor charge"
describe "#initialize" do
describe "with a stripe charge" do
it "has a charge_processor_id set to 'stripe'" do
expect(subject.charge_processor_id).to eq "stripe"
end
it "has the correct #id" do
expect(subject.id).to eq stripe_charge.id
end
it "has the correct #refunded" do
expect(subject.refunded).to be(false)
end
it "has the correct #fee" do
expect(subject.fee).to eq stripe_charge.balance_transaction.fee
end
it "has the correct #fee_currency" do
expect(subject.fee_currency).to eq stripe_charge.balance_transaction.currency
end
it "has the correct #card_fingerprint" do
expect(subject.card_fingerprint).to eq stripe_charge.payment_method_details.card.fingerprint
end
it "has the correct #card_instance_id" do
expect(subject.card_instance_id).to eq stripe_charge.payment_method
end
it "has the correct #card_last4" do
expect(subject.card_last4).to eq stripe_charge.payment_method_details.card.last4
end
it "has the correct #card_number_length" do
expect(subject.card_number_length).to eq 16
end
it "has the correct #card_expiry_month" do
expect(subject.card_expiry_month).to eq stripe_charge.payment_method_details.card.exp_month
end
it "has the correct #card_expiry_year" do
expect(subject.card_expiry_year).to eq stripe_charge.payment_method_details.card.exp_year
end
it "has the correct #card_zip_code" do
expect(subject.card_zip_code).to eq stripe_charge.billing_details.address.postal_code
end
it "has the correct #card_type" do
expect(subject.card_type).to eq "visa"
end
it "has the correct #card_zip_code" do
expect(subject.card_country).to eq stripe_charge.payment_method_details.card.country
end
it "has the correct #zip_check_result" do
expect(subject.zip_check_result).to be(nil)
end
it "has a simple flow of funds" do
expect(subject.flow_of_funds.issued_amount.currency).to eq(Currency::USD)
expect(subject.flow_of_funds.issued_amount.cents).to eq(amount_cents)
expect(subject.flow_of_funds.settled_amount.currency).to eq(Currency::USD)
expect(subject.flow_of_funds.settled_amount.cents).to eq(amount_cents)
expect(subject.flow_of_funds.gumroad_amount.currency).to eq(Currency::USD)
expect(subject.flow_of_funds.gumroad_amount.cents).to eq(amount_cents)
expect(subject.flow_of_funds.merchant_account_gross_amount).to be_nil
expect(subject.flow_of_funds.merchant_account_net_amount).to be_nil
end
it "sets the correct risk_level" do
expect(subject.risk_level).to eq stripe_charge.outcome.risk_level
end
it "initializes correctly without the stripe fee info" do
stripe_charge.balance_transaction.fee_details = []
expect(subject.fee).to be(nil)
expect(subject.fee_currency).to be(nil)
end
end
describe "with a stripe charge with pass zip check" do
let(:stripe_charge) do
stripe_charge = create_stripe_charge(StripePaymentMethodHelper.success.with_zip_code.to_stripejs_payment_method_id,
amount: amount_cents,
currency:
)
Stripe::Charge.retrieve(id: stripe_charge.id, expand: %w[balance_transaction])
end
let(:subject) { described_class.new(stripe_charge, stripe_charge.balance_transaction, nil, nil, nil) }
it "has the correct #zip_check_result" do
expect(subject.zip_check_result).to be(true)
end
end
# NOTE: There is no test for failed zip check because Gumroad has Stripe configured to raise an error if we
# attempt to process with an incorrect zip. This means that under the current Stripe configuration the
# zip_check_result will never be false since we do not create Charge object when an error is raised.
# If the Stripe configuration changes in the future then a test should be added for this scenario.
describe "with a stripe charge destined for a managed account" do
let(:application_fee) { 50 }
let(:destination_currency) { Currency::CAD }
let(:stripe_managed_account) { create_verified_stripe_account(country: "CA", default_currency: destination_currency) }
let(:stripe_charge) do
stripe_charge = create_stripe_charge(StripePaymentMethodHelper.success.to_stripejs_payment_method_id,
amount: amount_cents,
currency:,
transfer_data: { destination: stripe_managed_account.id, amount: amount_cents - application_fee },
)
Stripe::Charge.retrieve(id: stripe_charge.id, expand: %w[balance_transaction application_fee.balance_transaction])
end
let(:stripe_destination_transfer) do
Stripe::Transfer.retrieve(id: stripe_charge.transfer)
end
let(:stripe_destination_payment) do
destination_transfer = Stripe::Transfer.retrieve(id: stripe_charge.transfer)
Stripe::Charge.retrieve({ id: destination_transfer.destination_payment,
expand: %w[balance_transaction refunds.data.balance_transaction application_fee.refunds] },
{ stripe_account: destination_transfer.destination })
end
let(:subject) do
described_class.new(stripe_charge, stripe_charge.balance_transaction,
stripe_charge.application_fee.try(:balance_transaction),
stripe_destination_payment.balance_transaction, stripe_destination_transfer)
end
describe "#flow_of_funds" do
let(:flow_of_funds) { subject.flow_of_funds }
describe "#issued_amount" do
let(:issued_amount) { flow_of_funds.issued_amount }
it "matches the currency the buyer was charged in" do
expect(issued_amount.currency).to eq(currency)
end
it "matches the amount the buyer was charged" do
expect(issued_amount.cents).to eq(amount_cents)
end
end
describe "#settled_amount" do
let(:settled_amount) { flow_of_funds.settled_amount }
it "matches the currency the destinations default currency" do
expect(settled_amount.currency).to eq(stripe_charge.balance_transaction.currency)
end
it "does not match the currency the destination received in" do
expect(settled_amount.currency).not_to eq(stripe_destination_payment.balance_transaction.currency)
end
it "matches the amount the destination received" do
expect(settled_amount.cents).to eq(stripe_charge.balance_transaction.amount)
end
end
describe "#gumroad_amount" do
let(:gumroad_amount) { flow_of_funds.gumroad_amount }
it "matches the currency of gumroads account (usd)" do
expect(gumroad_amount.currency).to eq(Currency::USD)
end
it "matches the currency that gumroad received the application fee in" do
expect(gumroad_amount.currency).to eq(stripe_charge.currency)
end
it "matches the amount of the application fee received in gumroads account" do
expect(gumroad_amount.cents).to eq(stripe_charge.amount - stripe_destination_transfer.amount)
end
end
describe "#merchant_account_gross_amount" do
let(:merchant_account_gross_amount) { flow_of_funds.merchant_account_gross_amount }
it "matches the currency the destinations default currency" do
expect(merchant_account_gross_amount.currency).to eq(destination_currency)
end
it "matches the currency the destination received in" do
expect(merchant_account_gross_amount.currency).to eq(stripe_destination_payment.balance_transaction.currency)
end
it "matches the amount the destination received" do
expect(merchant_account_gross_amount.cents).to eq(stripe_destination_payment.balance_transaction.amount)
end
end
describe "#merchant_account_net_amount" do
let(:merchant_account_net_amount) { flow_of_funds.merchant_account_net_amount }
it "matches the currency the destinations default currency" do
expect(merchant_account_net_amount.currency).to eq(destination_currency)
end
it "matches the currency the destination received in" do
expect(merchant_account_net_amount.currency).to eq(stripe_destination_payment.balance_transaction.currency)
end
it "matches the amount the destination received after taking out gumroads application fee" do
expect(merchant_account_net_amount.cents).to eq(stripe_destination_payment.balance_transaction.net)
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/business/payments/charging/implementations/stripe/stripe_chargeable_credit_card_spec.rb | spec/business/payments/charging/implementations/stripe/stripe_chargeable_credit_card_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "business/payments/charging/chargeable_protocol"
require "business/payments/charging/implementations/stripe/stripe_chargeable_common_shared_examples"
describe StripeChargeableCreditCard, :vcr do
let(:user) { create(:user) }
let(:original_chargeable) { build(:chargeable) }
let(:original_chargeable_reusable_token) do
original_chargeable.prepare!
original_chargeable.reusable_token_for!(StripeChargeProcessor.charge_processor_id, user)
end
let(:chargeable) do
StripeChargeableCreditCard.new(
nil,
original_chargeable_reusable_token,
original_chargeable.payment_method_id,
original_chargeable.fingerprint,
original_chargeable.stripe_setup_intent_id,
original_chargeable.stripe_payment_intent_id,
original_chargeable.last4,
original_chargeable.number_length,
original_chargeable.visual,
original_chargeable.expiry_month,
original_chargeable.expiry_year,
original_chargeable.card_type,
original_chargeable.country,
original_chargeable.zip_code
)
end
it_should_behave_like "a chargeable"
include_examples "stripe chargeable common"
describe "#reusable_token!" do
it "returns persistable token" do
chargeable.prepare!
expect(chargeable.reusable_token!(user)).to eq original_chargeable_reusable_token
end
end
describe "#stripe_charge_params" do
it "returns customer and payment method" do
chargeable.prepare!
expect(chargeable.stripe_charge_params).to eq({ customer: original_chargeable.reusable_token_for!(StripeChargeProcessor.charge_processor_id, nil),
payment_method: original_chargeable.payment_method_id })
end
end
describe "#charge!" do
describe "when merchant account is not a stripe connect account" do
let(:merchant_account) { MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id) }
let(:chargeable) do
StripeChargeableCreditCard.new(
merchant_account,
original_chargeable_reusable_token,
original_chargeable.payment_method_id,
original_chargeable.fingerprint,
original_chargeable.stripe_setup_intent_id,
original_chargeable.stripe_payment_intent_id,
original_chargeable.last4,
original_chargeable.number_length,
original_chargeable.visual,
original_chargeable.expiry_month,
original_chargeable.expiry_year,
original_chargeable.card_type,
original_chargeable.country,
original_chargeable.zip_code
)
end
it "charges using the credit card payment method id" do
expect_any_instance_of(StripeChargeableCreditCard).not_to receive(:prepare_for_direct_charge)
chargeable.prepare!
expect(chargeable.reusable_token!(user)).to eq original_chargeable_reusable_token
expect(chargeable.stripe_charge_params[:customer]).to eq original_chargeable_reusable_token
expect(chargeable.stripe_charge_params[:payment_method]).to eq original_chargeable.payment_method_id
end
it "retrieves payment method id if it is not present" do
expect_any_instance_of(StripeChargeableCreditCard).not_to receive(:prepare_for_direct_charge)
chargeable = StripeChargeableCreditCard.new(
merchant_account,
original_chargeable_reusable_token,
nil,
original_chargeable.fingerprint,
original_chargeable.stripe_setup_intent_id,
original_chargeable.stripe_payment_intent_id,
original_chargeable.last4,
original_chargeable.number_length,
original_chargeable.visual,
original_chargeable.expiry_month,
original_chargeable.expiry_year,
original_chargeable.card_type,
original_chargeable.country,
original_chargeable.zip_code
)
chargeable.prepare!
expect(chargeable.reusable_token!(user)).to eq original_chargeable_reusable_token
expect(chargeable.stripe_charge_params[:customer]).to eq original_chargeable_reusable_token
expect(chargeable.stripe_charge_params[:payment_method]).to eq original_chargeable.payment_method_id
end
it "charges the payment method on gumroad stripe account" do
expect(Stripe::PaymentIntent).to receive(:create).with(hash_including({ amount: 100,
currency: "usd",
description: "test description",
metadata: { purchase: "reference" },
transfer_group: nil,
confirm: true,
payment_method_types: ["card"],
off_session: true,
setup_future_usage: nil,
customer: original_chargeable_reusable_token,
payment_method: original_chargeable.payment_method_id })).and_call_original
chargeable.prepare!
StripeChargeProcessor.new.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 0_30, "reference", "test description")
end
end
describe "when merchant account is a stripe connect account" do
let(:merchant_account) { create(:merchant_account_stripe_connect) }
let(:chargeable) do
StripeChargeableCreditCard.new(
merchant_account,
original_chargeable_reusable_token,
original_chargeable.payment_method_id,
original_chargeable.fingerprint,
original_chargeable.stripe_setup_intent_id,
original_chargeable.stripe_payment_intent_id,
original_chargeable.last4,
original_chargeable.number_length,
original_chargeable.visual,
original_chargeable.expiry_month,
original_chargeable.expiry_year,
original_chargeable.card_type,
original_chargeable.country,
original_chargeable.zip_code
)
end
it "charges using the cloned payment method" do
expect_any_instance_of(StripeChargeableCreditCard).to receive(:prepare_for_direct_charge).and_call_original
chargeable.prepare!
expect(chargeable.reusable_token!(user)).to eq original_chargeable_reusable_token
expect(chargeable.stripe_charge_params[:customer]).not_to eq original_chargeable_reusable_token
expect(chargeable.stripe_charge_params[:payment_method]).not_to eq original_chargeable.payment_method_id
end
it "charges the payment method cloned on the connected stripe account" do
chargeable.prepare!
expect(Stripe::PaymentIntent).to receive(:create).with(hash_including({ amount: 100,
currency: "usd",
description: "test description",
metadata: { purchase: "reference" },
transfer_group: nil,
payment_method_types: ["card"],
confirm: true,
off_session: true,
setup_future_usage: nil,
payment_method: chargeable.stripe_charge_params[:payment_method],
application_fee_amount: 24 }), { stripe_account: merchant_account.charge_processor_merchant_id }).and_call_original
StripeChargeProcessor.new.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 0_30, "reference", "test description")
end
context "when saved credit card only has a customer ID and no payment method ID" do
let(:merchant_account) { create(:merchant_account_stripe_connect) }
let(:chargeable) do
StripeChargeableCreditCard.new(
merchant_account,
original_chargeable_reusable_token,
nil,
original_chargeable.fingerprint,
original_chargeable.stripe_setup_intent_id,
original_chargeable.stripe_payment_intent_id,
original_chargeable.last4,
original_chargeable.number_length,
original_chargeable.visual,
original_chargeable.expiry_month,
original_chargeable.expiry_year,
original_chargeable.card_type,
original_chargeable.country,
original_chargeable.zip_code
)
end
it "retrieves the payment method associated with the customer and clones it" do
expect_any_instance_of(StripeChargeableCreditCard).to receive(:prepare_for_direct_charge).and_call_original
chargeable.prepare!
expect(chargeable.reusable_token!(user)).to eq original_chargeable_reusable_token
expect(chargeable.payment_method_id).to eq original_chargeable.payment_method_id
expect(chargeable.stripe_charge_params[:customer]).not_to eq original_chargeable_reusable_token
expect(chargeable.stripe_charge_params[:payment_method]).not_to eq original_chargeable.payment_method_id
end
it "charges the payment method cloned on the connected stripe account" do
chargeable.prepare!
expect(Stripe::PaymentIntent).to receive(:create).with(hash_including({ amount: 100,
currency: "usd",
description: "test description",
metadata: { purchase: "reference" },
transfer_group: nil,
payment_method_types: ["card"],
confirm: true,
off_session: true,
setup_future_usage: nil,
payment_method: chargeable.stripe_charge_params[:payment_method],
application_fee_amount: 24 }), { stripe_account: merchant_account.charge_processor_merchant_id }).and_call_original
StripeChargeProcessor.new.create_payment_intent_or_charge!(merchant_account, chargeable, 1_00, 0_30, "reference", "test description")
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/business/payments/charging/implementations/stripe/stripe_charge_refund_spec.rb | spec/business/payments/charging/implementations/stripe/stripe_charge_refund_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StripeChargeRefund, :vcr do
include StripeMerchantAccountHelper
include StripeChargesHelper
let(:currency) { Currency::USD }
let(:amount_cents) { 1_00 }
let(:stripe_charge) do
create_stripe_charge(StripePaymentMethodHelper.success.to_stripejs_payment_method_id,
amount: amount_cents,
currency:,
)
end
let(:stripe_refund) do
Stripe::Refund.create(
charge: stripe_charge[:id],
expand: %w[balance_transaction]
)
end
let(:subject) do
described_class.new(stripe_charge, stripe_refund, nil, stripe_refund.balance_transaction, nil, nil, nil)
end
describe "#initialize" do
describe "with a stripe refund" do
it "has a charge_processor_id set to 'stripe'" do
expect(subject.charge_processor_id).to eq "stripe"
end
it "has the #id from the stripe refund" do
expect(subject.id).to eq(stripe_refund[:id])
end
it "has the #charge_id from the stripe refund" do
expect(subject.charge_id).to eq(stripe_refund[:charge])
end
it "has the #charge_id from the original stripe charge" do
expect(subject.charge_id).to eq(stripe_charge[:id])
end
end
describe "with a stripe refund for a charge that was destined for a managed account" do
let(:application_fee) { 50 }
let(:destination_currency) { Currency::CAD }
let(:stripe_managed_account) { create_verified_stripe_account(country: "CA", default_currency: destination_currency) }
let(:stripe_charge) do
create_stripe_charge(StripePaymentMethodHelper.success.to_stripejs_payment_method_id,
amount: amount_cents,
currency:,
transfer_data: { destination: stripe_managed_account.id, amount: amount_cents - application_fee },
)
end
let(:stripe_refund_additional_params) do
{}
end
let(:stripe_refund_params) do
{
charge: stripe_charge[:id],
expand: %w[balance_transaction]
}.merge(stripe_refund_additional_params)
end
let(:stripe_refund) { Stripe::Refund.create(stripe_refund_params) }
before do
stripe_refund
end
let(:stripe_charge_refreshed) do
# A bug in the Stripe ruby gem causes it to lose it's expanded objects if it is refreshed after it's been created.
# Re-retrieving it anew solves this problem as refreshes of a retrieve charged refresh and maintain the expanded objects.
Stripe::Charge.retrieve(id: stripe_charge.id, expand: %w[balance_transaction application_fee.refunds.data.balance_transaction])
end
let(:stripe_destination_payment) do
destination_transfer = Stripe::Transfer.retrieve(id: stripe_charge_refreshed.transfer)
Stripe::Charge.retrieve({ id: destination_transfer.destination_payment,
expand: %w[refunds.data.balance_transaction application_fee.refunds] },
{ stripe_account: destination_transfer.destination })
end
let(:stripe_destination_payment_refund) { stripe_destination_payment.refunds.first }
let(:stripe_refund_bt) { stripe_refund.balance_transaction }
let(:subject) do
described_class.new(
stripe_charge_refreshed,
stripe_refund,
stripe_destination_payment,
stripe_refund_bt,
nil,
stripe_destination_payment_refund.try(:balance_transaction),
nil
)
end
describe "that involves the destination" do
let(:stripe_refund_additional_params) do
{
reverse_transfer: true,
refund_application_fee: true
}
end
describe "#flow_of_funds" do
let(:flow_of_funds) { subject.flow_of_funds }
describe "#issued_amount" do
let(:issued_amount) { flow_of_funds.issued_amount }
it "matches the currency the buyer was charged in" do
expect(issued_amount.currency).to eq(currency)
end
it "matches the amount the buyer was charged" do
expect(issued_amount.cents).to eq(-amount_cents)
end
end
describe "#settled_amount" do
let(:settled_amount) { flow_of_funds.settled_amount }
it "matches the currency of the transaction was made in " do
expect(settled_amount.currency).to eq(Currency::USD)
end
it "matches the currency the refund was withdrawn from" do
expect(settled_amount.currency).to eq(stripe_refund_bt.currency)
end
it "matches the amount withdrawn" do
expect(settled_amount.cents).to eq(stripe_refund_bt.amount)
end
end
describe "#gumroad_amount" do
let(:gumroad_amount) { flow_of_funds.gumroad_amount }
it "matches the currency of gumroads account (usd)" do
expect(gumroad_amount.currency).to eq(Currency::USD)
end
it "matches the currency of the Stripe refund" do
expect(gumroad_amount.currency).to eq(stripe_refund_bt.currency)
end
it "matches the amount of the Stripe refund" do
expect(gumroad_amount.cents).to eq(stripe_charge.amount - stripe_destination_payment.amount)
end
end
describe "#merchant_account_gross_amount" do
let(:merchant_account_gross_amount) { flow_of_funds.merchant_account_gross_amount }
it "matches the currency the destinations default currency" do
expect(merchant_account_gross_amount.currency).to eq(destination_currency)
end
it "matches the currency the destination payment is refunded in" do
expect(merchant_account_gross_amount.currency).to eq(stripe_destination_payment_refund.balance_transaction.currency)
end
it "matches the amount of the destination payment refund" do
expect(merchant_account_gross_amount.cents).to eq(
stripe_destination_payment_refund.balance_transaction.amount
)
end
end
describe "#merchant_account_net_amount" do
let(:merchant_account_net_amount) { flow_of_funds.merchant_account_net_amount }
it "matches the currency the destinations default currency" do
expect(merchant_account_net_amount.currency).to eq(destination_currency)
end
it "matches the currency the destination payment is refunded in" do
expect(merchant_account_net_amount.currency).to eq(stripe_destination_payment_refund.balance_transaction.currency)
end
it "matches the amount of the destination payment refund minus Gumroad's application fee refund amount" do
expect(merchant_account_net_amount.cents).to eq(
stripe_destination_payment_refund.balance_transaction.amount
)
end
end
end
end
describe "that doesn't involve the destination" do
let(:refunded_amount_cents) { 0_30 }
let(:stripe_refund_additional_params) do
{
amount: refunded_amount_cents
}
end
describe "some sanity checks on what we expect from stripe" do
it "Stripe should not have refunded the destination payment" do
expect(stripe_destination_payment_refund).to eq(nil)
end
end
describe "#flow_of_funds" do
let(:flow_of_funds) { subject.flow_of_funds }
let(:issued_amount) { flow_of_funds.issued_amount }
describe "#issued_amount" do
it "matches the currency the buyer was charged in" do
expect(issued_amount.currency).to eq(currency)
end
it "matches the amount the buyer was charged" do
expect(issued_amount.cents).to eq(-refunded_amount_cents)
end
end
describe "#settled_amount" do
let(:settled_amount) { flow_of_funds.settled_amount }
it "matches the currency of that the transaction was made in as fallback (cad)" do
expect(settled_amount.currency).to eq(stripe_refund_bt.currency)
end
it "matches the amount withdrawn" do
expect(settled_amount.cents).to eq(stripe_refund_bt.amount)
end
end
describe "#gumroad_amount" do
let(:gumroad_amount) { flow_of_funds.gumroad_amount }
it "matches the currency of that the transaction was made in (usd)" do
expect(gumroad_amount.currency).to eq(stripe_refund.currency)
end
it "matches the amount taken from the funds that gumroad holds (settled amount as fallback)" do
expect(gumroad_amount.cents).to eq(-stripe_refund.amount)
end
end
describe "#merchant_account_gross_amount" do
let(:merchant_account_gross_amount) { flow_of_funds.merchant_account_gross_amount }
it "is nil" do
expect(merchant_account_gross_amount).to eq(nil)
end
end
describe "#merchant_account_net_amount" do
let(:merchant_account_net_amount) { flow_of_funds.merchant_account_net_amount }
it "is nil" do
expect(merchant_account_net_amount).to eq(nil)
end
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/business/payments/charging/implementations/stripe/stripe_chargeable_token_spec.rb | spec/business/payments/charging/implementations/stripe/stripe_chargeable_token_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "business/payments/charging/chargeable_protocol"
require "business/payments/charging/implementations/stripe/stripe_chargeable_common_shared_examples"
describe StripeChargeableToken, :vcr do
let(:number) { "4242 4242 4242 4242" }
let(:expiry_month) { 12 }
let(:expiry_year) { 2050 }
let(:cvc) { "123" }
let(:zip_code) { "12345" }
let(:token) { Stripe::Token.create(card: { number:, exp_month: expiry_month, exp_year: expiry_year, cvc:, address_zip: zip_code }) }
let(:token_id) { token.id }
let(:chargeable) { StripeChargeableToken.new(token_id, zip_code, product_permalink: "xx") }
let(:user) { create(:user) }
it_behaves_like "a chargeable"
include_examples "stripe chargeable common"
describe "#prepare!" do
it "retrieves token details from stripe" do
expect(Stripe::Token).to receive(:retrieve).with(token_id).and_call_original
chargeable.prepare!
end
end
describe "#reusable_token!" do
it "uses stripe to get a reusable token" do
expect(Stripe::Customer)
.to receive(:create)
.with(hash_including(card: token_id,
description: user.id.to_s,
email: user.email))
.and_return(id: "cus_testcustomer")
expect(chargeable.reusable_token!(user)).to eq "cus_testcustomer"
end
it "fetches the customer's payment sources" do
expect(Stripe::Customer).to receive(:create).with(hash_including(expand: %w[sources])).and_call_original
chargeable.reusable_token!(user)
expect(chargeable.card).to be_present
end
end
describe "#visual" do
it "calls ChargeableVisual to build a visual" do
expect(ChargeableVisual).to receive(:build_visual).with("4242", 16).and_call_original
chargeable.prepare!
expect(chargeable.visual).to eq("**** **** **** 4242")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/stripe/stripe_chargeable_payment_method_spec.rb | spec/business/payments/charging/implementations/stripe/stripe_chargeable_payment_method_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "business/payments/charging/chargeable_protocol"
require "business/payments/charging/implementations/stripe/stripe_chargeable_common_shared_examples"
describe StripeChargeablePaymentMethod, :vcr do
let(:number) { "4242 4242 4242 4242" }
let(:expiry_month) { 12 }
let(:expiry_year) { 2050 }
let(:cvc) { "123" }
let(:zip_code) { "12345" }
let(:stripe_payment_method) do
Stripe::PaymentMethod.create(type: "card",
card: { number:, exp_month: expiry_month, exp_year: expiry_year, cvc: },
billing_details: { address: { postal_code: zip_code } })
end
let(:stripe_payment_method_id) { stripe_payment_method.id }
let(:chargeable) { StripeChargeablePaymentMethod.new(stripe_payment_method_id, zip_code:, product_permalink: "xx") }
let(:user) { create(:user) }
it_behaves_like "a chargeable"
include_examples "stripe chargeable common"
describe "#prepare!" do
it "retrieves token details from stripe" do
expect(Stripe::PaymentMethod).to receive(:retrieve).with(stripe_payment_method_id).and_call_original
chargeable.prepare!
end
it "does not prepare for direct charge if merchant account is not a stripe connect account" do
allow_any_instance_of(StripeChargeablePaymentMethod).to receive(:get_merchant_account).and_return(create(:merchant_account))
expect(Stripe::PaymentMethod).to receive(:retrieve).with(stripe_payment_method_id).and_call_original
expect_any_instance_of(StripeChargeablePaymentMethod).not_to receive(:prepare_for_direct_charge)
chargeable.prepare!
end
it "prepares for direct charge if merchant account is a stripe connect account" do
allow_any_instance_of(StripeChargeablePaymentMethod).to receive(:get_merchant_account).and_return(create(:merchant_account_stripe_connect))
expect(Stripe::PaymentMethod).to receive(:retrieve).with(stripe_payment_method_id).and_call_original
expect_any_instance_of(StripeChargeablePaymentMethod).to receive(:prepare_for_direct_charge)
chargeable.prepare!
end
end
describe "#reusable_token!" do
it "uses stripe to get a reusable token" do
expect(Stripe::Customer)
.to receive(:create)
.with(hash_including(payment_method: stripe_payment_method_id,
description: user.id.to_s,
email: user.email))
.and_return(OpenStruct.new(id: "cus_testcustomer"))
expect(chargeable.reusable_token!(user)).to eq "cus_testcustomer"
end
end
describe "#visual" do
it "calls ChargeableVisual to build a visual" do
expect(ChargeableVisual).to receive(:build_visual).with("4242", 16).and_call_original
chargeable.prepare!
expect(chargeable.visual).to eq("**** **** **** 4242")
end
end
describe "#stripe_charge_params" do
it "returns the original customer and payment method details if merchant account is not a stripe connect account" do
allow_any_instance_of(StripeChargeablePaymentMethod).to receive(:get_merchant_account).and_return(create(:merchant_account))
expect(Stripe::PaymentMethod).to receive(:retrieve).with(stripe_payment_method_id).and_call_original
expect_any_instance_of(StripeChargeablePaymentMethod).not_to receive(:prepare_for_direct_charge)
chargeable.prepare!
expect(chargeable.stripe_charge_params[:payment_method]).to be_present
expect(chargeable.stripe_charge_params[:payment_method]).to eq(stripe_payment_method_id)
end
it "returns the cloned payment method details if merchant account is a stripe connect account" do
allow_any_instance_of(StripeChargeablePaymentMethod).to receive(:get_merchant_account).and_return(create(:merchant_account_stripe_connect))
expect(Stripe::PaymentMethod).to receive(:retrieve).with(stripe_payment_method_id).and_call_original
expect_any_instance_of(StripeChargeablePaymentMethod).to receive(:prepare_for_direct_charge).and_call_original
chargeable.prepare!
expect(chargeable.stripe_charge_params[:payment_method]).to be_present
expect(chargeable.stripe_charge_params[:payment_method]).not_to eq(stripe_payment_method_id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/paypal/paypal_charge_intent_spec.rb | spec/business/payments/charging/implementations/paypal/paypal_charge_intent_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PaypalChargeIntent do
let(:paypal_charge) { double }
subject (:paypal_charge_intent) { described_class.new(charge: paypal_charge) }
describe "#succeeded?" do
it "returns true" do
expect(paypal_charge_intent.succeeded?).to eq(true)
end
end
describe "#requires_action?" do
it "returns false" do
expect(paypal_charge_intent.requires_action?).to eq(false)
end
end
describe "#charge" do
it "returns the charge object it was initialized with" do
expect(paypal_charge_intent.charge).to eq(paypal_charge)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/paypal/paypal_charge_spec.rb | spec/business/payments/charging/implementations/paypal/paypal_charge_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PaypalCharge do
context "when order api is used" do
context "when paypal transaction is present" do
let(:order_details) do
{
"id" => "426572068V1934255",
"intent" => "CAPTURE",
"purchase_units" => [
{
"reference_id" => "P5ppE6H8XIjy2JSCgUhbAw==",
"amount" => {
"currency_code" => "USD",
"value" => "19.50",
"breakdown" => {
"item_total" => {
"currency_code" => "USD",
"value" => "15.00"
},
"shipping" => {
"currency_code" => "USD",
"value" => "3.00"
},
"handling" => {
"currency_code" => "USD",
"value" => "0.00"
},
"tax_total" => {
"currency_code" => "USD",
"value" => "1.50"
},
"insurance" => {
"currency_code" => "USD",
"value" => "0.00"
},
"shipping_discount" => {
"currency_code" => "USD",
"value" => "0.00"
},
"discount" => {
"currency_code" => "USD",
"value" => "0.00"
}
}
},
"payee" => {
"email_address" => "sb-c7jpx2385730@business.example.com",
"merchant_id" => "MN7CSWD6RCNJ8"
},
"payment_instruction" => {
"platform_fees" => [
{
"amount" => {
"currency_code" => "USD",
"value" => "0.75"
},
"payee" => {
"email_address" => "paypal-api-facilitator@gumroad.com",
"merchant_id" => "HU29XVVCZXNFN"
}
}
]
},
"description" => "The Works of Edgar Gumstein",
"soft_descriptor" => "PAYPAL *JOHNDOESTES YO",
"items" => [
{
"name" => "The Works of Edgar Gumstein",
"unit_amount" => {
"currency_code" => "USD",
"value" => "5.00"
},
"tax" => {
"currency_code" => "USD",
"value" => "0.00"
},
"quantity" => "3",
"sku" => "aa"
}
],
"shipping" => {
"name" => {
"full_name" => "Gumbot Gumstein"
},
"address" => {
"address_line_1" => "1 Main St",
"admin_area_2" => "San Jose",
"admin_area_1" => "CA",
"postal_code" => "95131",
"country_code" => "US"
}
},
"payments" => {
"captures" => [
{
"id" => "58003532R80972514",
"status" => "REFUNDED",
"amount" => {
"currency_code" => "USD",
"value" => "19.50"
},
"final_capture" => true,
"disbursement_mode" => "INSTANT",
"seller_protection" => {
"status" => "ELIGIBLE",
"dispute_categories" => [
{},
{}
]
},
"seller_receivable_breakdown" => {
"gross_amount" => {
"currency_code" => "USD",
"value" => "19.50"
},
"paypal_fee" => {
"currency_code" => "USD",
"value" => "0.87"
},
"platform_fees" => [
{
"amount" => {
"currency_code" => "USD",
"value" => "0.75"
},
"payee" => {
"merchant_id" => "HU29XVVCZXNFN"
}
}
],
"net_amount" => {
"currency_code" => "USD",
"value" => "17.88"
}
},
"links" => [
{
"href" => "https://api.sandbox.paypal.com/v2/payments/captures/58003532R80972514",
"rel" => "self",
"method" => "GET"
},
{
"href" => "https://api.sandbox.paypal.com/v2/payments/captures/58003532R80972514/refund",
"rel" => "refund",
"method" => "POST"
},
{
"href" => "https://api.sandbox.paypal.com/v2/checkout/orders/426572068V1934255",
"rel" => "up",
"method" => "GET"
}
],
"create_time" => "2020-06-26T17:42:28Z",
"update_time" => "2020-06-26T19:23:02Z"
}
],
"refunds" => [
{
"id" => "8A762400SC645253S",
"amount" => {
"currency_code" => "USD",
"value" => "19.50"
},
"seller_payable_breakdown" => {
"gross_amount" => {
"currency_code" => "USD",
"value" => "19.50"
},
"paypal_fee" => {
"currency_code" => "USD",
"value" => "0.57"
},
"platform_fees" => [
{
"amount" => {
"currency_code" => "USD",
"value" => "0.75"
}
}
],
"net_amount" => {
"currency_code" => "USD",
"value" => "18.18"
},
"total_refunded_amount" => {
"currency_code" => "USD",
"value" => "19.50"
}
},
"status" => "COMPLETED",
"links" => [
{
"href" => "https://api.sandbox.paypal.com/v2/payments/refunds/8A762400SC645253S",
"rel" => "self",
"method" => "GET"
},
{
"href" => "https://api.sandbox.paypal.com/v2/payments/captures/58003532R80972514",
"rel" => "up",
"method" => "GET"
}
],
"create_time" => "2020-06-26T12:23:02-07:00",
"update_time" => "2020-06-26T12:23:02-07:00"
}
]
}
},
{
"reference_id" => "bfi_30HLgGWL8H2wo_Gzlg==",
"amount" => {
"currency_code" => "USD",
"value" => "12.00",
"breakdown" => {
"item_total" => {
"currency_code" => "USD",
"value" => "12.00"
},
"shipping" => {
"currency_code" => "USD",
"value" => "0.00"
},
"handling" => {
"currency_code" => "USD",
"value" => "0.00"
},
"tax_total" => {
"currency_code" => "USD",
"value" => "0.00"
},
"insurance" => {
"currency_code" => "USD",
"value" => "0.00"
},
"shipping_discount" => {
"currency_code" => "USD",
"value" => "0.00"
}
}
},
"payee" => {
"email_address" => "sb-byx2u2205460@business.example.com",
"merchant_id" => "B66YJBBNCRW6L"
},
"payment_instruction" => {
"platform_fees" => [
{
"amount" => {
"currency_code" => "USD",
"value" => "0.60"
},
"payee" => {
"merchant_id" => "2124944962663691396"
}
}
]
},
"description" => "The Works of Edgar Gumstein",
"soft_descriptor" => "PAYPAL *JOHNDOESTES YO",
"items" => [
{
"name" => "The Works of Edgar Gumstein",
"unit_amount" => {
"currency_code" => "USD",
"value" => "6.00"
},
"tax" => {
"currency_code" => "USD",
"value" => "0.00"
},
"quantity" => "2",
"sku" => "bb"
}
],
"shipping" => {
"name" => {
"full_name" => "Gumbot Gumstein"
},
"address" => {
"address_line_1" => "1 Main St",
"admin_area_2" => "San Jose",
"admin_area_1" => "CA",
"postal_code" => "95131",
"country_code" => "US"
}
},
"payments" => {
"captures" => [
{
"id" => "4FF7716038572874Y",
"status" => "PARTIALLY_REFUNDED",
"amount" => {
"currency_code" => "USD",
"value" => "12.00"
},
"final_capture" => true,
"disbursement_mode" => "INSTANT",
"seller_protection" => {
"status" => "ELIGIBLE",
"dispute_categories" => [
{},
{}
]
},
"seller_receivable_breakdown" => {
"gross_amount" => {
"currency_code" => "USD",
"value" => "12.00"
},
"paypal_fee" => {
"currency_code" => "USD",
"value" => "0.65"
},
"platform_fees" => [
{
"amount" => {
"currency_code" => "USD",
"value" => "0.60"
},
"payee" => {
"merchant_id" => "HU29XVVCZXNFN"
}
}
],
"net_amount" => {
"currency_code" => "USD",
"value" => "10.75"
}
},
"links" => [
{
"href" => "https://api.sandbox.paypal.com/v2/payments/captures/4FF7716038572874Y",
"rel" => "self",
"method" => "GET"
},
{
"href" => "https://api.sandbox.paypal.com/v2/payments/captures/4FF7716038572874Y/refund",
"rel" => "refund",
"method" => "POST"
},
{
"href" => "https://api.sandbox.paypal.com/v2/checkout/orders/426572068V1934255",
"rel" => "up",
"method" => "GET"
}
],
"create_time" => "2020-06-26T17:42:32Z",
"update_time" => "2020-06-26T19:23:11Z"
}
],
"refunds" => [
{
"id" => "92M0058559975814A",
"amount" => {
"currency_code" => "USD",
"value" => "2.00"
},
"seller_payable_breakdown" => {
"gross_amount" => {
"currency_code" => "USD",
"value" => "2.00"
},
"paypal_fee" => {
"currency_code" => "USD",
"value" => "0.06"
},
"platform_fees" => [
{
"amount" => {
"currency_code" => "USD",
"value" => "0.10"
}
}
],
"net_amount" => {
"currency_code" => "USD",
"value" => "1.84"
},
"total_refunded_amount" => {
"currency_code" => "USD",
"value" => "2.00"
}
},
"status" => "COMPLETED",
"links" => [
{
"href" => "https://api.sandbox.paypal.com/v2/payments/refunds/92M0058559975814A",
"rel" => "self",
"method" => "GET"
},
{
"href" => "https://api.sandbox.paypal.com/v2/payments/captures/4FF7716038572874Y",
"rel" => "up",
"method" => "GET"
}
],
"create_time" => "2020-06-26T12:23:11-07:00",
"update_time" => "2020-06-26T12:23:11-07:00"
}
]
}
}
],
"payer" => {
"name" => {
"given_name" => "Gumbot",
"surname" => "Gumstein"
},
"email_address" => "paypal-gr-integspecs@gumroad.com",
"payer_id" => "92SVVJSWYT72E",
"phone" => {
"phone_number" => {
"national_number" => "4085146918"
}
},
"address" => {
"country_code" => "US"
}
},
"update_time" => "2020-06-26T19:23:02Z",
"links" => [
{
"href" => "https://api.sandbox.paypal.com/v2/checkout/orders/426572068V1934255",
"rel" => "self",
"method" => "GET"
}
],
"status" => "COMPLETED"
}
end
subject do
PaypalCharge.new(paypal_transaction_id: "58003532R80972514",
order_api_used: true,
payment_details: order_details)
end
it "sets all the properties of the order" do
is_expected.to have_attributes(charge_processor_id: PaypalChargeProcessor.charge_processor_id,
id: "58003532R80972514",
fee: 87.0,
paypal_payment_status: "REFUNDED",
refunded: true,
flow_of_funds: nil,
card_fingerprint: "paypal_paypal-gr-integspecs@gumroad.com",
card_country: "US",
card_type: "paypal",
card_visual: "paypal-gr-integspecs@gumroad.com")
end
it "does not throw error if paypal_fee value is absent" do
payment_details = order_details.tap { |order| order["purchase_units"][0]["payments"]["captures"][0]["seller_receivable_breakdown"].delete("paypal_fee") }
charge = PaypalCharge.new(paypal_transaction_id: "58003532R80972514",
order_api_used: true,
payment_details:)
expect(charge).to have_attributes(charge_processor_id: PaypalChargeProcessor.charge_processor_id,
id: "58003532R80972514",
fee: nil,
paypal_payment_status: "REFUNDED",
refunded: true,
flow_of_funds: nil,
card_fingerprint: "paypal_paypal-gr-integspecs@gumroad.com",
card_country: "US",
card_type: "paypal",
card_visual: "paypal-gr-integspecs@gumroad.com")
end
end
context "when paypal transaction is not present" do
subject do
PaypalCharge.new(paypal_transaction_id: nil, order_api_used: true)
end
it "doesn't set order API property" do
is_expected.to have_attributes(charge_processor_id: PaypalChargeProcessor.charge_processor_id,
id: nil,
fee: nil,
paypal_payment_status: nil,
refunded: nil,
flow_of_funds: nil,
card_fingerprint: nil,
card_country: nil,
card_type: nil,
card_visual: nil)
end
end
end
context "when express checkout api is used" do
describe "with payment and payer info passed in" do
let :paypal_payment_info do
paypal_payment_info = PayPal::SDK::Merchant::DataTypes::PaymentInfoType.new
paypal_payment_info.PaymentStatus = PaypalApiPaymentStatus::REFUNDED
paypal_payment_info.GrossAmount.value = "10.00"
paypal_payment_info.GrossAmount.currencyID = "USD"
paypal_payment_info.FeeAmount.value = "1.00"
paypal_payment_info.FeeAmount.currencyID = "USD"
paypal_payment_info
end
let :paypal_payer_info do
paypal_payer_info = PayPal::SDK::Merchant::DataTypes::PayerInfoType.new
paypal_payer_info.Payer = "paypal-buyer@gumroad.com"
paypal_payer_info.PayerID = "sample-fingerprint-source"
paypal_payer_info.PayerCountry = Compliance::Countries::USA.alpha2
paypal_payer_info
end
it "populates the required payment info and optional payer info" do
paypal_charge = PaypalCharge.new(paypal_transaction_id: "5SP884803B810025T",
order_api_used: false,
payment_details: {
paypal_payment_info:,
paypal_payer_info:
})
expect(paypal_charge).to_not be(nil)
expect(paypal_charge.id).to eq("5SP884803B810025T")
expect(paypal_charge.refunded).to be(true)
expect(paypal_charge.paypal_payment_status).to eq("Refunded")
expect(paypal_charge.fee).to eq(100)
expect(paypal_charge.card_fingerprint).to eq("paypal_sample-fingerprint-source")
expect(paypal_charge.card_type).to eq(CardType::PAYPAL)
expect(paypal_charge.card_country).to eq(Compliance::Countries::USA.alpha2)
end
it "populates the required payment and does not set payer fields if payload is not passed in" do
paypal_charge = PaypalCharge.new(paypal_transaction_id: "5SP884803B810025T",
order_api_used: false,
payment_details: {
paypal_payment_info:
})
expect(paypal_charge).to_not be(nil)
expect(paypal_charge.id).to eq("5SP884803B810025T")
expect(paypal_charge.refunded).to be(true)
expect(paypal_charge.paypal_payment_status).to eq("Refunded")
expect(paypal_charge.fee).to eq(100)
expect(paypal_charge.card_fingerprint).to be(nil)
expect(paypal_charge.card_type).to be(nil)
expect(paypal_charge.card_country).to be(nil)
end
it "sets the refund states based on the PayPal PaymentInfo PaymentStatus" do
paypal_payment_info.PaymentStatus = PaypalApiPaymentStatus::COMPLETED
paypal_charge = PaypalCharge.new(paypal_transaction_id: "5SP884803B810025T",
order_api_used: false,
payment_details: {
paypal_payment_info:
})
expect(paypal_charge.refunded).to be(false)
expect(paypal_charge.paypal_payment_status).to eq("Completed")
paypal_payment_info.PaymentStatus = "Refunded"
paypal_charge = PaypalCharge.new(paypal_transaction_id: "5SP884803B810025T",
order_api_used: false,
payment_details: {
paypal_payment_info:
})
expect(paypal_charge.refunded).to be(true)
paypal_payment_info.PaymentStatus = PaypalApiPaymentStatus::REVERSED
paypal_charge = PaypalCharge.new(paypal_transaction_id: "5SP884803B810025T",
order_api_used: false,
payment_details: {
paypal_payment_info:
})
expect(paypal_charge.refunded).to be(false)
end
it "does not have a flow of funds" do
paypal_charge = PaypalCharge.new(paypal_transaction_id: "5SP884803B810025T",
order_api_used: false,
payment_details: {
paypal_payment_info:
})
expect(paypal_charge.flow_of_funds).to be_nil
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/paypal/paypal_charge_refund_spec.rb | spec/business/payments/charging/implementations/paypal/paypal_charge_refund_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PaypalChargeRefund, :vcr do
let(:paypal_api) { PayPal::SDK::Merchant::API.new }
let(:pre_prepared_paypal_charge_id) do
# A USD$5 charge, pre-made on Paypal.
"58409660Y47347418"
end
let(:paypal_refund_response) do
refund_request = paypal_api.build_refund_transaction(TransactionID: pre_prepared_paypal_charge_id, RefundType: PaypalApiRefundType::FULL)
paypal_api.refund_transaction(refund_request)
end
let(:subject) { described_class.new(paypal_refund_response, pre_prepared_paypal_charge_id) }
describe "#initialize" do
describe "with a paypal refund response" do
it "has a charge_processor_id set to 'paypal' and id and charge_id but no flow_of_funds" do
expect(subject.charge_processor_id).to eq "paypal"
expect(subject.id).to eq(paypal_refund_response.RefundTransactionID)
expect(subject.charge_id).to eq(pre_prepared_paypal_charge_id)
expect(subject.flow_of_funds).to be_nil
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/paypal/paypal_order_refund_spec.rb | spec/business/payments/charging/implementations/paypal/paypal_order_refund_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PaypalOrderRefund do
describe ".new" do
it "sets attributes correctly" do
refund_response_double = double
allow(refund_response_double).to receive(:id).and_return("ExampleID")
order_refund = described_class.new(refund_response_double, "SampleCaptureId")
expect(order_refund).to have_attributes(charge_processor_id: PaypalChargeProcessor.charge_processor_id,
charge_id: "SampleCaptureId", id: "ExampleID")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/paypal/paypal_charge_processor_spec.rb | spec/business/payments/charging/implementations/paypal/paypal_charge_processor_spec.rb | # frozen_string_literal: true
require "spec_helper"
# The VCRs for this charge processor are recorded from manually setup scenarios
# DO NOT delete VCRs in case you are re-recording en masse
#
# Steps to setup an express checkout to record a VCR our of:
# - Create a product (non recurring charge, non pre order) locally with the desired amount required to auth (thorugh the rails server)
# - Purchase the product w/o logging in as any user in the desired price-affecting configuration and authenticate through the PayPal lightbox
# - After this point, you can use the PayPal express checkout token for all further operations available in the charge processor
# Manually setup the desired scenario.
describe PaypalChargeProcessor, :vcr do
let(:paypal_auth_token) do
"Bearer A21AAI9v6NTs3Y42Ufo-5Q-cskFZtTLkOodRO1uJQvdaWnsbiCt078vvzYnSy5X1gLFwGZIyhtT6D_EUZyyyp_YjB9CudeK7w"
end
before do
allow_any_instance_of(PaypalPartnerRestCredentials).to receive(:auth_token).and_return(paypal_auth_token)
end
describe ".charge_processor_id" do
it "returns 'paypal'" do
expect(described_class.charge_processor_id).to eq "paypal"
end
end
describe "PayPal payment events handler" do
describe "non payment event determined by the invoice field existing" do
before do
raw_payload =
"payment_type=echeck&payment_date=Sun%20May%2024%202015%2014%3A32%3A31%20GMT-0700%20%28PDT%29&payment_status=Reversed&" \
"payer_status=verified&first_name=John&last_name=Smith&payer_email=buyer%40paypalsandbox.com&payer_id=TESTBUYERID01&address_name=John%20Smith&address_country=United%20States&" \
"address_country_code=US&address_zip=95131&address_state=CA&address_city=San%20Jose&address_street=123%20any%20street&business=seller%40paypalsandbox.com&" \
"receiver_email=seller%40paypalsandbox.com&receiver_id=seller%40paypalsandbox.com&residence_country=US&item_name=something&item_number=AK-1234&quantity=1&" \
"shipping=3.04&tax=2.02&mc_currency=USD&mc_fee=0.44&mc_gross=12.34&mc_gross1=12.34&txn_type=web_accept&txn_id=995288809¬ify_version=2.1&parent_txn_id=SOMEPRIORTXNID002&" \
"reason_code=chargeback&receipt_ID=3012-5109-3782-6103&custom=xyz123&test_ipn=1&verify_sign=AFcWxV21C7fd0v3bYYYRCpSSRl31A4SYxlXZ9IdB.iATdIIByT4aW.Qa"
@payload = Rack::Utils.parse_nested_query(raw_payload)
end
it "does not process it and raises an error" do
expect do
described_class.handle_paypal_event(@payload)
end.to raise_error(RuntimeError)
end
end
describe "payment event" do
before do
@purchase = create(:purchase_with_balance, id: 1001)
allow_any_instance_of(Purchase).to receive(:fight_chargeback).and_return(true)
allow_any_instance_of(Purchase).to receive(:secure_external_id).and_return("sample-secure-id")
allow(Purchase).to receive(:find_by_external_id).and_return(@purchase)
allow(DisputeEvidence).to receive(:create_from_dispute!).and_return nil
end
describe "reversal and reversal cancelled events" do
describe "reversal event" do
before do
raw_payload =
"payment_type=echeck&payment_date=Sun%20May%2024%202015%2014%3A32%3A31%20GMT-0700%20%28PDT%29&payment_status=Reversed&" \
"payer_status=verified&first_name=John&last_name=Smith&payer_email=buyer%40paypalsandbox.com&payer_id=TESTBUYERID01&address_name=John%20Smith&address_country=United%20States&" \
"address_country_code=US&address_zip=95131&address_state=CA&address_city=San%20Jose&address_street=123%20any%20street&business=seller%40paypalsandbox.com&" \
"receiver_email=seller%40paypalsandbox.com&receiver_id=seller%40paypalsandbox.com&residence_country=US&item_name=something&item_number=AK-1234&quantity=1&" \
"shipping=-3.04&tax=-2.02&mc_currency=USD&mc_fee=-0.44&mc_gross=-12.34&mc_gross1=-12.34&txn_type=web_accept&txn_id=995288809¬ify_version=2.1&parent_txn_id=SOMEPRIORTXNID002&" \
"reason_code=chargeback&receipt_ID=3012-5109-3782-6103&custom=xyz123&invoice=D7lNKK8L-urz8D3awchsUA%3D%3D&test_ipn=1&verify_sign=AFcWxV21C7fd0v3bYYYRCpSSRl31A4SYxlXZ9IdB.iATdIIByT4aW.Qa"
@payload = Rack::Utils.parse_nested_query(raw_payload)
end
it "handles a chargeback message form PayPal" do
expect(@purchase.chargeback_date).to be(nil)
described_class.handle_paypal_event(@payload)
@purchase.reload
expect(@purchase.chargeback_date).to_not be(nil)
expect(@purchase.chargeback_reversed).to be(false)
expect(@purchase.chargeback_date).to eq(@payload["payment_date"])
end
it "tells the charge processor that a dispute was created" do
original_handle_event = ChargeProcessor.method(:handle_event)
expect(ChargeProcessor).to(receive(:handle_event) do |charge_event|
expect(charge_event).to be_a(ChargeEvent)
expect(charge_event.type).to eq(ChargeEvent::TYPE_DISPUTE_FORMALIZED)
expect(charge_event.flow_of_funds).to be(nil)
original_handle_event.call(charge_event)
end)
described_class.handle_paypal_event(@payload)
end
end
describe "reversal cancelled event" do
let(:paypal_payment_info) do
paypal_payment_info = PayPal::SDK::Merchant::DataTypes::PaymentInfoType.new
paypal_payment_info.PaymentStatus = PaypalApiPaymentStatus::REFUNDED
paypal_payment_info.GrossAmount.value = "10.00"
paypal_payment_info.GrossAmount.currencyID = "USD"
paypal_payment_info.FeeAmount.value = "1.00"
paypal_payment_info.FeeAmount.currencyID = "USD"
paypal_payment_info
end
let(:paypal_payer_info) do
paypal_payer_info = PayPal::SDK::Merchant::DataTypes::PayerInfoType.new
paypal_payer_info.Payer = "paypal-buyer@gumroad.com"
paypal_payer_info.PayerID = "sample-fingerprint-source"
paypal_payer_info.PayerCountry = Compliance::Countries::USA.alpha2
paypal_payer_info
end
before do
raw_payload =
"payment_type=instant&payment_date=Sun%20May%2024%202015%2015%3A04%3A11%20GMT-0700%20%28PDT%29&payment_status=Canceled_Reversal&" \
"address_status=confirmed&payer_status=verified&first_name=John&last_name=Smith&payer_email=buyer%40paypalsandbox.com&payer_id=TESTBUYERID01&" \
"address_name=John%20Smith&address_country=United%20States&address_country_code=US&address_zip=95131&address_state=CA&address_city=San%20Jose&" \
"address_street=123%20any%20street&business=seller%40paypalsandbox.com&receiver_email=seller%40paypalsandbox.com&receiver_id=seller%40paypalsandbox.com&residence_country=US&" \
"item_name=something&item_number=AK-1234&quantity=1&shipping=3.04&tax=2.02&mc_currency=USD&mc_fee=0.44&mc_gross=12.34&mc_gross1=12.34&txn_type=web_accept&txn_id=694541630&" \
"notify_version=2.1&parent_txn_id=PARENT_TXN_ID&reason_code=other&custom=xyz123&invoice=D7lNKK8L-urz8D3awchsUA%3D%3D&test_ipn=1&" \
"verify_sign=AFcWxV21C7fd0v3bYYYRCpSSRl31A48M..jE7GasP8rDsyMNp6bZuihz"
@payload = Rack::Utils.parse_nested_query(raw_payload)
@purchase.chargeback_date = Time.current
@purchase.save!
end
before(:each) do
@mock_paypal_charge = PaypalCharge.new(paypal_transaction_id: "5SP884803B810025T",
order_api_used: false,
payment_details: {
paypal_payment_info:,
paypal_payer_info:
})
end
describe "reversal cancelled event" do
describe "no transaction found for parent transaction ID" do
it "raises a NoMethodError exception" do
expect_any_instance_of(described_class).to receive(:get_charge).and_return(nil)
expect do
described_class.handle_paypal_event(@payload)
end.to raise_error(NoMethodError)
end
end
describe "the dispute was resolved in our favor" do
before(:each) do
@mock_paypal_charge.paypal_payment_status = PaypalApiPaymentStatus::COMPLETED
expect_any_instance_of(described_class).to receive(:get_charge).and_return(@mock_paypal_charge)
end
it "handles a chargeback reversed message form PayPal" do
expect(@purchase.chargeback_date).to_not be(nil)
described_class.handle_paypal_event(@payload)
@purchase.reload
expect(@purchase.chargeback_date).to_not be(nil)
expect(@purchase.chargeback_reversed).to be(true)
end
it "tells the charge processor that a dispute was won" do
original_handle_event = ChargeProcessor.method(:handle_event)
expect(ChargeProcessor).to(receive(:handle_event) do |charge_event|
expect(charge_event).to be_a(ChargeEvent)
expect(charge_event.type).to eq(ChargeEvent::TYPE_DISPUTE_WON)
expect(charge_event.flow_of_funds).to be(nil)
original_handle_event.call(charge_event)
end)
described_class.handle_paypal_event(@payload)
end
end
describe "the dispute was resolved in the buyers favor" do
before(:each) do
@mock_paypal_charge.paypal_payment_status = PaypalApiPaymentStatus::REVERSED
expect_any_instance_of(described_class).to receive(:get_charge).and_return(@mock_paypal_charge)
end
it "does not send any events and do nothing" do
expect(ChargeProcessor).to_not receive(:handle_event)
described_class.handle_paypal_event(@payload)
end
end
end
end
end
describe "payment completion event" do
before do
raw_payload =
"mc_gross=13.45&invoice=D7lNKK8L-urz8D3awchsUA==&auth_exp=17:15:30 Jul 23, 2015 PDT&protection_eligibility=Ineligible&payer_id=VPMPQMFE9ZCUC&" \
"tax=0.00&payment_date=17:15:32 Jun 23, 2015 PDT&payment_status=Completed&charset=UTF-8&first_name=Jane&transaction_entity=payment&mc_fee=0.56¬ify_version=3.8&" \
"custom=&payer_status=verified&quantity=1&verify_sign=ANjcFFL6thfg3pfU8XyZ4HGhsY0wAmacmdU9K4DVg7jf-Oll2FinOurH&payer_email=travelerpalm@sbcglobal.net&" \
"parent_txn_id=8KL149495L527372S&txn_id=2EX735004Y601032C&payment_type=instant&remaining_settle=0&auth_id=8KL149495L527372S&last_name=Wong&receiver_email=support@gumroad.com&" \
"auth_amount=13.45&payment_fee=0.56&receiver_id=VYZJQAA368WRW&txn_type=cart&item_name=&mc_currency=USD&item_number=&residence_country=US&handling_amount=0.00&transaction_subject=&" \
"payment_gross=13.45&auth_status=Completed&shipping=0.00&ipn_track_id=72e28fc50c6fa"
@payload = Rack::Utils.parse_nested_query(raw_payload)
end
it "creates a informational charge event with the fee information" do
@purchase.fee_cents = 0
@purchase.save!
described_class.handle_paypal_event(@payload)
@purchase.reload
expect(@purchase.chargeback_date).to be(nil)
expect(@purchase.processor_fee_cents).to eq(56)
end
end
describe "other non-completion payment event" do
before do
raw_payload =
"payment_type=instant&payment_date=Tue%20May%2026%202015%2019%3A31%3A02%20GMT-0700%20%28PDT%29&payment_status=Inflight&payer_status=verified&first_name=John&" \
"last_name=Smith&payer_email=buyer%40paypalsandbox.com&payer_id=TESTBUYERID01&address_name=John%20Smith&address_country=United%20States&address_country_code=US&" \
"address_zip=95131&address_state=CA&address_city=San%20Jose&address_street=123%20any%20street&business=seller%40paypalsandbox.com&receiver_email=seller%40paypalsandbox.com&" \
"receiver_id=seller%40paypalsandbox.com&residence_country=US&item_name1=something&item_number1=AK-1234&quantity=1&shipping=3.04&tax=2.02&mc_currency=USD&mc_fee=0.44&mc_gross=12.34&" \
"mc_gross1=12.34&mc_handling=2.06&mc_handling1=1.67&mc_shipping=3.02&mc_shipping1=1.02&txn_type=cart&txn_id=899327589¬ify_version=2.4&custom=xyz123&invoice=random_external_id%3D%3D&" \
"test_ipn=1&verify_sign=AFcWxV21C7fd0v3bYYYRCpSSRl31AbXPdTVhBcCUUizimR553bDXp-Fg"
@payload = Rack::Utils.parse_nested_query(raw_payload)
end
it "does not do anything" do
expect(ActiveSupport::Notifications).to_not receive(:instrument)
described_class.handle_paypal_event(@payload)
end
end
describe "on combined charges" do
it "creates a informational charge event with the fee information" do
charge = create(:charge, processor_fee_cents: nil)
charge.purchases << create(:purchase)
expect(charge.processor_fee_cents).to be nil
expect(charge.purchases.last.stripe_status).to be nil
raw_payload =
"mc_gross=13.45&invoice=#{charge.reference_id_for_charge_processors}&auth_exp=17:15:30 Jul 23, 2015 PDT&protection_eligibility=Ineligible&payer_id=VPMPQMFE9ZCUC&" \
"tax=0.00&payment_date=17:15:32 Jun 23, 2015 PDT&payment_status=Completed&charset=UTF-8&first_name=Jane&transaction_entity=payment&mc_fee=0.56¬ify_version=3.8&" \
"custom=&payer_status=verified&quantity=1&verify_sign=ANjcFFL6thfg3pfU8XyZ4HGhsY0wAmacmdU9K4DVg7jf-Oll2FinOurH&payer_email=travelerpalm@sbcglobal.net&" \
"parent_txn_id=8KL149495L527372S&txn_id=2EX735004Y601032C&payment_type=instant&remaining_settle=0&auth_id=8KL149495L527372S&last_name=Wong&receiver_email=support@gumroad.com&" \
"auth_amount=13.45&payment_fee=0.56&receiver_id=VYZJQAA368WRW&txn_type=cart&item_name=&mc_currency=USD&item_number=&residence_country=US&handling_amount=0.00&transaction_subject=&" \
"payment_gross=13.45&auth_status=Completed&shipping=0.00&ipn_track_id=72e28fc50c6fa"
payload = Rack::Utils.parse_nested_query(raw_payload)
described_class.handle_paypal_event(payload)
expect(charge.reload.processor_fee_cents).to eq(56)
expect(charge.purchases.last.stripe_status).to eq("Completed")
end
end
end
end
describe ".handle_order_events" do
context "when event type is CUSTOMER.DISPUTE.CREATED" do
it "sets chargeback details on purchase" do
event_info = { "id" => "WH-3TW20315YE525782H-3BD552601T418134F", "event_version" => "1.0", "create_time" => "2017-10-10T14:09:01.129Z", "resource_type" => "dispute", "event_type" => "CUSTOMER.DISPUTE.CREATED", "summary" => "A new dispute opened with Case # PP-D-4805PP-D-4805", "resource" => { "dispute_id" => "PP-D-4805", "create_time" => "2017-10-10T14:07:23.000Z", "update_time" => "2017-10-10T14:08:06.000Z", "disputed_transactions" => [{ "seller_transaction_id" => "6Y199803HH2987814", "seller" => { "name" => "facilitator account's Test Store" }, "items" => [{ "item_id" => "uF" }], "seller_protection_eligible" => true }], "reason" => "CREDIT_NOT_PROCESSED", "status" => "UNDER_REVIEW", "dispute_amount" => { "currency_code" => "[FILTERED]", "value" => "6.43" }, "offer" => { "buyer_requested_amount" => { "currency_code" => "[FILTERED]", "value" => "6.43" } }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/customer/disputes/PP-D-4805", "rel" => "self", "method" => "GET" }] }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-3TW20315YE525782H-3BD552601T418134F", "rel" => "self", "method" => "GET" }, { "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-3TW20315YE525782H-3BD552601T418134F/resend", "rel" => "resend", "method" => "POST" }], "foreign_webhook" => { "id" => "WH-3TW20315YE525782H-3BD552601T418134F", "event_version" => "1.0", "create_time" => "2017-10-10T14:09:01.129Z", "resource_type" => "dispute", "event_type" => "CUSTOMER.DISPUTE.CREATED", "summary" => "A new dispute opened with Case # PP-D-4805PP-D-4805", "resource" => { "dispute_id" => "PP-D-4805", "create_time" => "2017-10-10T14:07:23.000Z", "update_time" => "2017-10-10T14:08:06.000Z", "disputed_transactions" => [{ "seller_transaction_id" => "6Y199803HH2987814", "seller" => { "name" => "facilitator account's Test Store" }, "items" => [{ "item_id" => "uF" }], "seller_protection_eligible" => true }], "reason" => "CREDIT_NOT_PROCESSED", "status" => "UNDER_REVIEW", "dispute_amount" => { "currency_code" => "[FILTERED]", "value" => "6.43" }, "offer" => { "buyer_requested_amount" => { "currency_code" => "[FILTERED]", "value" => "6.43" } }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/customer/disputes/PP-D-4805", "rel" => "self", "method" => "GET" }] }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-3TW20315YE525782H-3BD552601T418134F", "rel" => "self", "method" => "GET" }, { "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-3TW20315YE525782H-3BD552601T418134F/resend", "rel" => "resend", "method" => "POST" }] } }
purchase = create(:purchase_with_balance, id: 1001, stripe_transaction_id: "6Y199803HH2987814")
allow_any_instance_of(Purchase).to receive(:fight_chargeback).and_return(true)
expect(purchase.chargeback_date).to be(nil)
described_class.handle_order_events(event_info)
purchase.reload
expect(purchase.chargeback_date).to_not be(nil)
expect(purchase.chargeback_reversed).to be(false)
expect(purchase.chargeback_date).to eq(DateTime.parse(event_info["resource"]["create_time"]))
end
it "raises `ChargeProcessorError` on error" do
event_info = { "event_type" => "CUSTOMER.DISPUTE.CREATED" }
create(:purchase_with_balance, id: 1001, stripe_transaction_id: "6Y199803HH2987814")
expect do
described_class.handle_order_events(event_info)
end.to raise_error(ChargeProcessorError)
end
end
context "when event type is CUSTOMER.DISPUTE.RESOLVED" do
it "marks dispute as WON when seller wins the dispute" do
%w[RESOLVED_SELLER_FAVOUR CANCELED_BY_BUYER DENIED].each do |dispute_outcome|
event_info = { "id" => "WH-6TU580349K989084X-4AH939136E356570T", "event_version" => "1.0", "create_time" => "2017-10-17T01:26:40.120Z", "resource_type" => "dispute", "event_type" => "CUSTOMER.DISPUTE.RESOLVED", "summary" => "A dispute was resolved with case # PP-D-4805PP-D-4805", "resource" => { "dispute_id" => "PP-D-4805", "create_time" => "2017-10-10T14:07:23.000Z", "update_time" => "2017-10-17T01:25:10.000Z", "disputed_transactions" => [{ "seller_transaction_id" => "6Y199803HH2987814", "seller" => { "name" => "facilitator account's Test Store" }, "items" => [{ "item_id" => "uF" }], "seller_protection_eligible" => true }], "reason" => "CREDIT_NOT_PROCESSED", "status" => "RESOLVED", "dispute_amount" => { "currency_code" => "USD", "value" => "6.43" }, "dispute_outcome" => { "outcome_code" => dispute_outcome }, "offer" => { "buyer_requested_amount" => { "currency_code" => "USD", "value" => "6.43" } }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/customer/disputes/PP-D-4805", "rel" => "self", "method" => "GET" }] }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-6TU580349K989084X-4AH939136E356570T", "rel" => "self", "method" => "GET" }, { "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-6TU580349K989084X-4AH939136E356570T/resend", "rel" => "resend", "method" => "POST" }], "controller" => "foreign_webhooks", "action" => "paypal", "foreign_webhook" => { "id" => "WH-6TU580349K989084X-4AH939136E356570T", "event_version" => "1.0", "create_time" => "2017-10-17T01:26:40.120Z", "resource_type" => "dispute", "event_type" => "CUSTOMER.DISPUTE.RESOLVED", "summary" => "A dispute was resolved with case # PP-D-4805PP-D-4805", "resource" => { "dispute_id" => "PP-D-4805", "create_time" => "2017-10-10T14:07:23.000Z", "update_time" => "2017-10-17T01:25:10.000Z", "disputed_transactions" => [{ "seller_transaction_id" => "6Y199803HH2987814", "seller" => { "name" => "facilitator account's Test Store" }, "items" => [{ "item_id" => "uF" }], "seller_protection_eligible" => true }], "reason" => "CREDIT_NOT_PROCESSED", "status" => "RESOLVED", "dispute_amount" => { "currency_code" => "USD", "value" => "6.43" }, "dispute_outcome" => { "outcome_code" => "CANCELED_BY_BUYER" }, "offer" => { "buyer_requested_amount" => { "currency_code" => "USD", "value" => "6.43" } }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/customer/disputes/PP-D-4805", "rel" => "self", "method" => "GET" }] }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-6TU580349K989084X-4AH939136E356570T", "rel" => "self", "method" => "GET" }, { "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-6TU580349K989084X-4AH939136E356570T/resend", "rel" => "resend", "method" => "POST" }] } }
purchase = create(:purchase_with_balance, stripe_transaction_id: "6Y199803HH2987814")
purchase.update_attribute(:chargeback_date, Time.current)
described_class.handle_order_events(event_info)
purchase.reload
expect(purchase.chargeback_reversed).to be(true)
expect(purchase.dispute.won?).to be(true)
end
end
it "marks dispute as LOST when seller loses the dispute" do
event_info = { "id" => "WH-6TU580349K989084X-4AH939136E356570T", "event_version" => "1.0", "create_time" => "2017-10-17T01:26:40.120Z", "resource_type" => "dispute", "event_type" => "CUSTOMER.DISPUTE.RESOLVED", "summary" => "A dispute was resolved with case # PP-D-4805PP-D-4805", "resource" => { "dispute_id" => "PP-D-4805", "create_time" => "2017-10-10T14:07:23.000Z", "update_time" => "2017-10-17T01:25:10.000Z", "disputed_transactions" => [{ "seller_transaction_id" => "6Y199803HH2987814", "seller" => { "name" => "facilitator account's Test Store" }, "items" => [{ "item_id" => "uF" }], "seller_protection_eligible" => true }], "reason" => "CREDIT_NOT_PROCESSED", "status" => "RESOLVED", "dispute_amount" => { "currency_code" => "USD", "value" => "6.43" }, "dispute_outcome" => { "outcome_code" => "RESOLVED_BUYER_FAVOUR" }, "offer" => { "buyer_requested_amount" => { "currency_code" => "USD", "value" => "6.43" } }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/customer/disputes/PP-D-4805", "rel" => "self", "method" => "GET" }] }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-6TU580349K989084X-4AH939136E356570T", "rel" => "self", "method" => "GET" }, { "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-6TU580349K989084X-4AH939136E356570T/resend", "rel" => "resend", "method" => "POST" }], "controller" => "foreign_webhooks", "action" => "paypal", "foreign_webhook" => { "id" => "WH-6TU580349K989084X-4AH939136E356570T", "event_version" => "1.0", "create_time" => "2017-10-17T01:26:40.120Z", "resource_type" => "dispute", "event_type" => "CUSTOMER.DISPUTE.RESOLVED", "summary" => "A dispute was resolved with case # PP-D-4805PP-D-4805", "resource" => { "dispute_id" => "PP-D-4805", "create_time" => "2017-10-10T14:07:23.000Z", "update_time" => "2017-10-17T01:25:10.000Z", "disputed_transactions" => [{ "seller_transaction_id" => "6Y199803HH2987814", "seller" => { "name" => "facilitator account's Test Store" }, "items" => [{ "item_id" => "uF" }], "seller_protection_eligible" => true }], "reason" => "CREDIT_NOT_PROCESSED", "status" => "RESOLVED", "dispute_amount" => { "currency_code" => "USD", "value" => "6.43" }, "dispute_outcome" => { "outcome_code" => "CANCELED_BY_BUYER" }, "offer" => { "buyer_requested_amount" => { "currency_code" => "USD", "value" => "6.43" } }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/customer/disputes/PP-D-4805", "rel" => "self", "method" => "GET" }] }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-6TU580349K989084X-4AH939136E356570T", "rel" => "self", "method" => "GET" }, { "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-6TU580349K989084X-4AH939136E356570T/resend", "rel" => "resend", "method" => "POST" }] } }
purchase = create(:purchase_with_balance, stripe_transaction_id: "6Y199803HH2987814")
described_class.handle_order_events(event_info)
purchase.reload
expect(purchase.dispute.lost?).to be(true)
end
it "raises `ChargeProcessorError` on error" do
event_info = { "event_type" => "CUSTOMER.DISPUTE.RESOLVED" }
create(:purchase_with_balance, stripe_transaction_id: "6Y199803HH2987814")
expect do
described_class.handle_order_events(event_info)
end.to raise_error(ChargeProcessorError)
end
end
context "when event type is PAYMENT.CAPTURE.COMPLETED" do
it "updates the processor fee for the purchase" do
purchase = create(:purchase, stripe_transaction_id: "5B223658W54364539",
processor_fee_cents: nil, processor_fee_cents_currency: nil)
event_info = { "id" => "WH-2C707249AJ963352S-8WR62076K2971640M", "event_version" => "1.0", "create_time" => "2021-01-08T14:10:09.452Z", "resource_type" => "capture", "resource_version" => "2.0", "event_type" => "PAYMENT.CAPTURE.COMPLETED", "summary" => "Payment completed for GBP 1.31 GBP", "resource" => { "disbursement_mode" => "INSTANT", "amount" => { "value" => "1.31", "currency_code" => "GBP" }, "seller_protection" => { "dispute_categories" => ["ITEM_NOT_RECEIVED", "UNAUTHORIZED_TRANSACTION"], "status" => "ELIGIBLE" }, "update_time" => "2021-01-08T14:09:45Z", "create_time" => "2021-01-08T14:09:45Z", "final_capture" => true, "seller_receivable_breakdown" => { "platform_fees" => [{ "payee" => { "merchant_id" => "HU29XVVCZXNFN" }, "amount" => { "value" => "0.08", "currency_code" => "GBP" } }], "paypal_fee" => { "value" => "0.25", "currency_code" => "GBP" }, "gross_amount" => { "value" => "1.31", "currency_code" => "GBP" }, "net_amount" => { "value" => "0.98", "currency_code" => "GBP" } }, "links" => [{ "method" => "GET", "rel" => "self", "href" => "https://api.sandbox.paypal.com/v2/payments/captures/5B223658W54364539" }, { "method" => "POST", "rel" => "refund", "href" => "https://api.sandbox.paypal.com/v2/payments/captures/5B223658W54364539/refund" }, { "method" => "GET", "rel" => "up", "href" => "https://api.sandbox.paypal.com/v2/checkout/orders/0PF373004F060160X" }], "id" => "5B223658W54364539", "status" => "COMPLETED" }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-2C707249AJ963352S-8WR62076K2971640M", "rel" => "self", "method" => "GET" }, { "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-2C707249AJ963352S-8WR62076K2971640M/resend", "rel" => "resend", "method" => "POST" }], "foreign_webhook" => { "id" => "WH-2C707249AJ963352S-8WR62076K2971640M", "event_version" => "1.0", "create_time" => "2021-01-08T14:10:09.452Z", "resource_type" => "capture", "resource_version" => "2.0", "event_type" => "PAYMENT.CAPTURE.COMPLETED", "summary" => "Payment completed for GBP 1.31 GBP", "resource" => { "disbursement_mode" => "INSTANT", "amount" => { "value" => "1.31", "currency_code" => "GBP" }, "seller_protection" => { "dispute_categories" => ["ITEM_NOT_RECEIVED", "UNAUTHORIZED_TRANSACTION"], "status" => "ELIGIBLE" }, "update_time" => "2021-01-08T14:09:45Z", "create_time" => "2021-01-08T14:09:45Z", "final_capture" => true, "seller_receivable_breakdown" => { "platform_fees" => [{ "payee" => { "merchant_id" => "HU29XVVCZXNFN" }, "amount" => { "value" => "0.08", "currency_code" => "GBP" } }], "paypal_fee" => { "value" => "0.25", "currency_code" => "GBP" }, "gross_amount" => { "value" => "1.31", "currency_code" => "GBP" }, "net_amount" => { "value" => "0.98", "currency_code" => "GBP" } }, "links" => [{ "method" => "GET", "rel" => "self", "href" => "https://api.sandbox.paypal.com/v2/payments/captures/5B223658W54364539" }, { "method" => "POST", "rel" => "refund", "href" => "https://api.sandbox.paypal.com/v2/payments/captures/5B223658W54364539/refund" }, { "method" => "GET", "rel" => "up", "href" => "https://api.sandbox.paypal.com/v2/checkout/orders/0PF373004F060160X" }], "id" => "5B223658W54364539", "status" => "COMPLETED" }, "links" => [{ "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-2C707249AJ963352S-8WR62076K2971640M", "rel" => "self", "method" => "GET" }, { "href" => "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-2C707249AJ963352S-8WR62076K2971640M/resend", "rel" => "resend", "method" => "POST" }] } }
described_class.handle_order_events(event_info)
purchase.reload
expect(purchase.processor_fee_cents).to eq(25)
expect(purchase.processor_fee_cents_currency).to eq("GBP")
end
it "does nothing if seller_receivable_breakdown is absent" do
purchase = create(:purchase, stripe_transaction_id: "5B223658W54364539",
processor_fee_cents: nil, processor_fee_cents_currency: nil)
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/paypal/paypal_approved_order_chargeable_spec.rb | spec/business/payments/charging/implementations/paypal/paypal_approved_order_chargeable_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PaypalApprovedOrderChargeable do
let(:paypal_approved_order_chargeable) { PaypalApprovedOrderChargeable.new("9J862133JL8076730", "paypal-gr-integspecs@gumroad.com", "US") }
it "returns customer paypal email for #email, paypal order id for #fingerprint, and nil #last4" do
expect(paypal_approved_order_chargeable.fingerprint).to eq("9J862133JL8076730")
expect(paypal_approved_order_chargeable.email).to eq("paypal-gr-integspecs@gumroad.com")
expect(paypal_approved_order_chargeable.last4).to be_nil
end
it "returns customer paypal email for #visual, and nil for #number_length, #expiry_month and #expiry_year" do
expect(paypal_approved_order_chargeable.visual).to eq("paypal-gr-integspecs@gumroad.com")
expect(paypal_approved_order_chargeable.number_length).to be_nil
expect(paypal_approved_order_chargeable.expiry_month).to be_nil
expect(paypal_approved_order_chargeable.expiry_year).to be_nil
end
it "returns correct country and nil #zip_code" do
expect(paypal_approved_order_chargeable.zip_code).to be_nil
expect(paypal_approved_order_chargeable.country).to eq("US")
end
it "returns nil for #reusable_token!" do
reusable_token = paypal_approved_order_chargeable.reusable_token!(123)
expect(reusable_token).to be(nil)
end
it "returns paypal for #charge_processor_id" do
expect(paypal_approved_order_chargeable.charge_processor_id).to eq("paypal")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/paypal/paypal_rest_api_spec.rb | spec/business/payments/charging/implementations/paypal/paypal_rest_api_spec.rb | # frozen_string_literal: true
describe PaypalRestApi, :vcr do
let(:api_object) { PaypalRestApi.new }
let(:paypal_auth_token) { "Bearer A21AAI6Qq9kon0Z2N7R6ed3OXwkNxFraroKppGHWHJUU5w-MlQBKKcZd_WlHbQJgh79HLaWQmEnRyj3GZdRW9FMqRbbSkcmBA" }
# Business accounts from our sandbox setup and their merchant IDs generated after manually completing onboarding
let(:creator_email) { "sb-c7jpx2385730@business.example.com" }
let(:creator_paypal_merchant_id) { "MN7CSWD6RCNJ8" }
let(:creator_2_email) { "sb-byx2u2205460@business.example.com" }
let(:creator_2_paypal_merchant_id) { "B66YJBBNCRW6L" }
let(:creator) { create(:user, email: creator_email) }
let(:creator_merchant_account) { create(:merchant_account_paypal, user: creator, charge_processor_merchant_id: creator_paypal_merchant_id) }
let(:link) { create(:product, user: creator, unique_permalink: "aa") }
let(:creator_2) { create(:user, email: creator_2_email) }
let(:creator_2_merchant_account) { create(:merchant_account_paypal, user: creator_2, charge_processor_merchant_id: creator_2_paypal_merchant_id) }
let(:link2) { create(:product, user: creator_2, unique_permalink: "bb") }
let(:purchase) do
create(:purchase, link:, shipping_cents: 150, price_cents: 1500, tax_cents: 75, quantity: 3)
end
before do
creator_merchant_account
creator_2_merchant_account
allow_any_instance_of(PaypalPartnerRestCredentials).to receive(:auth_token).and_return(paypal_auth_token)
end
describe "#create_order" do
let(:create_order_response) do
api_object.create_order(purchase_unit_info: PaypalChargeProcessor.paypal_order_info(purchase))
end
it "creates new order as requested and returns the order details in response" do
allow_any_instance_of(Purchase).to receive(:external_id).and_return("G_-mnBf9b1j9A7a4ub4nFQ==")
expect(create_order_response.status_code).to eq(201)
order = create_order_response.result
expect(order.id).to_not be(nil)
expect(order.status).to eq("CREATED")
purchase_unit = order.purchase_units[0]
expect(purchase_unit.invoice_id).to eq(purchase.external_id)
expect(purchase_unit.amount.value).to eq("15.00")
expect(purchase_unit.amount.breakdown.item_total.value).to eq("13.50")
expect(purchase_unit.amount.breakdown.shipping.value).to eq("1.50")
expect(purchase_unit.amount.breakdown.tax_total.value).to eq("0.00")
expect(purchase_unit.payee.merchant_id).to eq(creator_paypal_merchant_id)
expect(purchase_unit.items[0].quantity).to eq("3")
expect(purchase_unit.items[0].unit_amount.value).to eq("4.50")
expect(purchase_unit.items[0].sku).to eq(link.unique_permalink)
expect(purchase_unit.payment_instruction.platform_fees.size).to eq(1)
expect(purchase_unit.payment_instruction.platform_fees.first.amount.value).to eq("1.00")
urls = order.links
expect(urls.size).to eq(4)
expect(urls.map(&:rel)).to match_array(%w(self approve update capture))
end
it "limits the product (item) names to 127 characters" do
product_with_very_long_name = create(:product, user: creator, unique_permalink: "cc",
name: "Conversation Casanova Mastery: 48 Conversation Tactics, Techniques and Mindsets to "\
"Start Conversations, Flirt like a Master and Never Run Out of Things to Say, The Book")
purchase = create(:purchase, link: product_with_very_long_name)
response = api_object.create_order(purchase_unit_info: PaypalChargeProcessor.paypal_order_info(purchase))
order = response.result
expect(order.id).to_not be(nil)
expect(order.status).to eq("CREATED")
expect(order.purchase_units[0].items[0].name).to eq(purchase.link.name.strip[0...PaypalChargeProcessor::MAXIMUM_ITEM_NAME_LENGTH])
end
it "Formats the amounts to not have a thousands separator and have 2 decimal places" do
purchase = create(:purchase, link:, price_cents: 153399, quantity: 3)
response = api_object.create_order(purchase_unit_info: PaypalChargeProcessor.paypal_order_info(purchase))
order = response.result
expect(order.id).to_not be(nil)
expect(order.status).to eq("CREATED")
purchase_unit = order.purchase_units[0]
expect(purchase_unit.amount.value).to eq("1533.99")
expect(purchase_unit.amount.breakdown.item_total.value).to eq("1533.99")
expect(purchase_unit.payee.merchant_id).to eq(creator_paypal_merchant_id)
expect(purchase_unit.items[0].quantity).to eq("3")
expect(purchase_unit.items[0].unit_amount.value).to eq("511.33")
expect(purchase_unit.items[0].sku).to eq(link.unique_permalink)
expect(purchase_unit.payment_instruction.platform_fees.size).to eq(1)
expect(purchase_unit.payment_instruction.platform_fees.first.amount.value).to eq("76.94")
urls = order.links
expect(urls.size).to eq(4)
expect(urls.map(&:rel)).to match_array(%w(self approve update capture))
end
it "does not have decimal values for amounts in TWD" do
allow_any_instance_of(MerchantAccount).to receive(:currency).and_return("TWD")
purchase = create(:purchase, link:, price_cents: 1500, quantity: 3)
response = api_object.create_order(purchase_unit_info: PaypalChargeProcessor.paypal_order_info(purchase))
order = response.result
expect(order.id).to be_present
expect(order.status).to eq("CREATED")
purchase_unit = order.purchase_units[0]
expect(purchase_unit.amount.value).to eq("450.00")
expect(purchase_unit.amount.breakdown.item_total.value).to eq("450.00")
expect(purchase_unit.payee.merchant_id).to eq(creator_paypal_merchant_id)
expect(purchase_unit.items[0].quantity).to eq("3")
expect(purchase_unit.items[0].unit_amount.value).to eq("150.00")
expect(purchase_unit.items[0].sku).to eq(link.unique_permalink)
end
it "calculates the amounts in HUF correctly" do
allow_any_instance_of(MerchantAccount).to receive(:currency).and_return("HUF")
purchase = create(:purchase, link:, price_cents: 1500, quantity: 3)
response = api_object.create_order(purchase_unit_info: PaypalChargeProcessor.paypal_order_info(purchase))
order = response.result
expect(order.id).to be_present
expect(order.status).to eq("CREATED")
purchase_unit = order.purchase_units[0]
expect(purchase_unit.amount.value).to eq("3705.00")
expect(purchase_unit.amount.breakdown.item_total.value).to eq("3705.00")
expect(purchase_unit.payee.merchant_id).to eq(creator_paypal_merchant_id)
expect(purchase_unit.items[0].quantity).to eq("3")
expect(purchase_unit.items[0].unit_amount.value).to eq("1235.00")
expect(purchase_unit.items[0].sku).to eq(link.unique_permalink)
end
it "uses items details if passed to create new order" do
seller = create(:user)
merchant_account = create(:merchant_account_paypal, user: seller, charge_processor_merchant_id: "B66YJBBNCRW6L")
charge = create(:charge, seller:, merchant_account:, amount_cents: 10_00, gumroad_amount_cents: 2_50)
charge.purchases << create(:purchase, price_cents: 200, fee_cents: 48, link: create(:product, unique_permalink: "h"))
charge.purchases << create(:purchase, price_cents: 800, fee_cents: 102, link: create(:product, unique_permalink: "c"))
paypal_auth_token = "Bearer A21AAIwPw4niCFO4ziUTNt46mLva8lrt4cmMackDZFvFNVqEIpkEMzh6z-tt5cb2Sw6YcPsT1kVfuBdsVkAnZcAx9XFiMiGIw"
allow_any_instance_of(PaypalPartnerRestCredentials).to receive(:auth_token).and_return(paypal_auth_token)
allow_any_instance_of(Charge).to receive(:external_id).and_return("G_-mnBf9b1j9A7a4ub4nFQ==")
order_response = api_object.create_order(purchase_unit_info: PaypalChargeProcessor.paypal_order_info_from_charge(charge))
expect(order_response.status_code).to eq(201)
order = order_response.result
expect(order.id).to_not be(nil)
expect(order.status).to eq("CREATED")
purchase_unit = order.purchase_units[0]
expect(purchase_unit.invoice_id).to eq(charge.external_id)
expect(purchase_unit.amount.value).to eq("10.00")
expect(purchase_unit.amount.breakdown.item_total.value).to eq("10.00")
expect(purchase_unit.amount.breakdown.shipping.value).to eq("0.00")
expect(purchase_unit.amount.breakdown.tax_total.value).to eq("0.00")
expect(purchase_unit.payee.merchant_id).to eq(merchant_account.charge_processor_merchant_id)
expect(purchase_unit.items[0].quantity).to eq("1")
expect(purchase_unit.items[0].unit_amount.value).to eq("2.00")
expect(purchase_unit.items[0].sku).to eq(charge.purchases.first.link.unique_permalink)
expect(purchase_unit.items[1].quantity).to eq("1")
expect(purchase_unit.items[1].unit_amount.value).to eq("8.00")
expect(purchase_unit.items[1].sku).to eq(charge.purchases.last.link.unique_permalink)
expect(purchase_unit.payment_instruction.platform_fees.size).to eq(1)
expect(purchase_unit.payment_instruction.platform_fees.first.amount.value).to eq("1.50")
urls = order.links
expect(urls.size).to eq(4)
expect(urls.map(&:rel)).to match_array(%w(self approve update capture))
end
end
describe "update_order" do
it "updates the paypal order with the product info" do
allow_any_instance_of(Purchase).to receive(:external_id).and_return("G_-mnBf9b1j9A7a4ub4nFQ==")
purchase = create(:purchase, link:, shipping_cents: 150, price_cents: 1500, tax_cents: 75, quantity: 3,
merchant_account: creator_merchant_account)
create_order_response = api_object.create_order(purchase_unit_info: PaypalChargeProcessor.paypal_order_info(purchase))
order = create_order_response.result
purchase_unit = order.purchase_units[0]
expect(purchase_unit.amount.value).to eq("15.00")
expect(purchase_unit.amount.breakdown.item_total.value).to eq("13.50")
expect(purchase_unit.amount.breakdown.shipping.value).to eq("1.50")
expect(purchase_unit.amount.breakdown.tax_total.value).to eq("0.00")
expect(purchase_unit.items[0].quantity).to eq("3")
expect(purchase_unit.items[0].unit_amount.value).to eq("4.50")
expect(purchase_unit.items[0].sku).to eq(link.unique_permalink)
expect(purchase_unit.payment_instruction.platform_fees.size).to eq(1)
expect(purchase_unit.payment_instruction.platform_fees.first.amount.value).to eq("1.65")
purchase.update!(price_cents: 750, total_transaction_cents: 750, shipping_cents: 75, fee_cents: 83)
api_object.update_order(order_id: order.id,
purchase_unit_info: PaypalChargeProcessor.paypal_order_info(purchase))
fetch_order_response = api_object.fetch_order(order_id: order.id)
order = fetch_order_response.result
purchase_unit = order.purchase_units[0]
expect(purchase_unit.amount.value).to eq("7.50")
expect(purchase_unit.amount.breakdown.item_total.value).to eq("6.75")
expect(purchase_unit.amount.breakdown.shipping.value).to eq("0.75")
expect(purchase_unit.amount.breakdown.tax_total.value).to eq("0.00")
expect(purchase_unit.items[0].quantity).to eq("3")
expect(purchase_unit.items[0].unit_amount.value).to eq("2.25")
expect(purchase_unit.items[0].sku).to eq(link.unique_permalink)
expect(purchase_unit.payment_instruction.platform_fees.size).to eq(1)
expect(purchase_unit.payment_instruction.platform_fees.first.amount.value).to eq("0.83")
end
end
describe "#fetch_order" do
context "when invalid order id is passed" do
let(:fetch_order_response) { api_object.fetch_order(order_id: "invalid_order") }
it "returns error" do
expect(fetch_order_response.status_code).to eq(404)
expect(fetch_order_response.result.name).to eq("RESOURCE_NOT_FOUND")
end
end
context "when valid order id is passed" do
let(:create_order_response) do
api_object.create_order(purchase_unit_info: PaypalChargeProcessor.paypal_order_info(purchase))
end
let(:fetch_order_response) { api_object.fetch_order(order_id: create_order_response.result.id) }
it "returns order details" do
expect(fetch_order_response.status_code).to eq(200)
order = fetch_order_response.result
expect(order.id).to eq(create_order_response.result.id)
expect(order.status).to eq("CREATED")
purchase_unit = order.purchase_units[0]
expect(purchase_unit.amount.value).to eq("15.00")
expect(purchase_unit.amount.breakdown.item_total.value).to eq("13.50")
expect(purchase_unit.amount.breakdown.shipping.value).to eq("1.50")
expect(purchase_unit.amount.breakdown.tax_total.value).to eq("0.00")
expect(purchase_unit.payee.merchant_id).to eq(creator_paypal_merchant_id)
expect(purchase_unit.items[0].quantity).to eq("3")
expect(purchase_unit.items[0].unit_amount.value).to eq("4.50")
expect(purchase_unit.items[0].sku).to eq(link.unique_permalink)
expect(purchase_unit.payment_instruction.platform_fees.size).to eq(1)
expect(purchase_unit.payment_instruction.platform_fees.first.amount.value).to eq("1.00")
urls = order.links
expect(urls.size).to eq(4)
expect(urls.map(&:rel)).to match_array(%w(self approve update capture))
end
end
end
describe "#capture" do
context "when invalid order id is passed" do
let(:capture_order_response) { api_object.capture(order_id: "invalid_order", billing_agreement_id: nil) }
it "returns error" do
expect(capture_order_response.status_code).to eq(404)
expect(capture_order_response.result.name).to eq("RESOURCE_NOT_FOUND")
end
end
context "when valid order id is passed" do
let(:capture_order_response) { api_object.capture(order_id: "9XX680320L106570A", billing_agreement_id: "B-38D505255T217912K") }
it "returns success with valid order having completed status" do
expect(capture_order_response.status_code).to eq(201)
order = capture_order_response.result
expect(order.id).to_not be(nil)
expect(order.status).to eq("COMPLETED")
expect(order.payer.email_address).to eq("paypal-gr-integspecs@gumroad.com")
purchase_unit = order.purchase_units[0]
expect(purchase_unit.amount.value).to eq("15.00")
expect(purchase_unit.amount.breakdown.item_total.value).to eq("13.50")
expect(purchase_unit.amount.breakdown.shipping.value).to eq("1.50")
expect(purchase_unit.amount.breakdown.tax_total.value).to eq("0.00")
expect(purchase_unit.payee.merchant_id).to eq(creator_paypal_merchant_id)
expect(purchase_unit.items[0].quantity).to eq("3")
expect(purchase_unit.items[0].unit_amount.value).to eq("4.50")
expect(purchase_unit.items[0].sku).to eq(link.unique_permalink)
expect(purchase_unit.payments.captures.size).to eq(1)
expect(purchase_unit.payment_instruction.platform_fees.size).to eq(1)
expect(purchase_unit.payment_instruction.platform_fees.first.amount.value).to eq("1.00")
capture = purchase_unit.payments.captures[0]
expect(capture.status).to eq("COMPLETED")
expect(capture.disbursement_mode).to eq("INSTANT")
expect(capture.amount.value).to eq("15.00")
expect(capture.seller_receivable_breakdown.gross_amount.value).to eq("15.00")
expect(capture.seller_receivable_breakdown.paypal_fee.value).to eq("0.74")
expect(capture.seller_receivable_breakdown.platform_fees.size).to eq(1)
expect(capture.seller_receivable_breakdown.platform_fees.first.amount.value).to eq("1.00")
expect(capture.seller_receivable_breakdown.platform_fees.first.payee.merchant_id).to eq(PAYPAL_PARTNER_ID)
expect(capture.seller_receivable_breakdown.net_amount.value).to eq("13.26")
urls = capture.links
expect(urls.size).to eq(3)
expect(urls.map(&:rel)).to match_array(%w(self refund up))
end
end
end
describe "#refund" do
context "when it a full refund" do
context "when invalid capture id is passed" do
let(:refund_response) { api_object.refund(capture_id: "invalid_capture_id", merchant_account: creator_merchant_account) }
it "returns error" do
expect(refund_response.status_code).to eq(404)
expect(refund_response.result.name).to eq("RESOURCE_NOT_FOUND")
end
end
context "when valid capture id is passed" do
let(:refund_response) { api_object.refund(capture_id: "09G1866342856691M", merchant_account: creator_merchant_account) }
it "refunds full amount" do
expect(refund_response.status_code).to eq(201)
refund = refund_response.result
expect(refund.id).to_not be(nil)
expect(refund.status).to eq("COMPLETED")
expect(refund.seller_payable_breakdown.gross_amount.value).to eq("15.00")
expect(refund.seller_payable_breakdown.paypal_fee.value).to eq("0.44")
expect(refund.seller_payable_breakdown.platform_fees.first.amount.value).to eq("1.00")
expect(refund.seller_payable_breakdown.net_amount.value).to eq("13.56")
expect(refund.seller_payable_breakdown.total_refunded_amount.value).to eq("15.00")
urls_2 = refund.links
expect(urls_2.size).to eq(2)
expect(urls_2.map(&:rel)).to match_array(%w(self up))
end
end
end
context "when it is partial refund" do
context "when invalid capture id is passed" do
let(:refund_response) { api_object.refund(capture_id: "invalid_capture_id", merchant_account: creator_2_merchant_account, amount: 2.0) }
it "returns error" do
expect(refund_response.status_code).to eq(404)
expect(refund_response.result.name).to eq("RESOURCE_NOT_FOUND")
end
end
context "when valid capture id is passed" do
let(:refund_response) { api_object.refund(capture_id: "3K928030M4826742P", merchant_account: creator_merchant_account, amount: 2.0) }
it "refunds the passed amount" do
expect(refund_response.status_code).to eq(201)
refund = refund_response.result
expect(refund.id).to_not be(nil)
expect(refund.status).to eq("COMPLETED")
expect(refund.seller_payable_breakdown.gross_amount.value).to eq("2.00")
expect(refund.seller_payable_breakdown.paypal_fee.value).to eq("0.06")
expect(refund.seller_payable_breakdown.platform_fees.first.amount.value).to eq("0.10")
expect(refund.seller_payable_breakdown.net_amount.value).to eq("1.84")
expect(refund.seller_payable_breakdown.total_refunded_amount.value).to eq("2.00")
urls_2 = refund.links
expect(urls_2.size).to eq(2)
expect(urls_2.map(&:rel)).to match_array(%w(self up))
end
end
end
context "when merchant account details are not available" do
it "gets the paypal account details from original order and refunds successfully" do
purchase = create(:purchase, stripe_transaction_id: "8FM61749P03946202", paypal_order_id: "9UG44304FR485654R")
expect_any_instance_of(PaypalRestApi).to receive(:fetch_order).with(order_id: purchase.paypal_order_id).and_call_original
refund_response = api_object.refund(capture_id: purchase.stripe_transaction_id)
expect(refund_response.status_code).to eq(201)
refund = refund_response.result
expect(refund.id).to be_present
expect(refund.status).to eq("COMPLETED")
expect(refund.seller_payable_breakdown.gross_amount.value).to eq("5.00")
expect(refund.seller_payable_breakdown.paypal_fee.value).to eq("0.15")
expect(refund.seller_payable_breakdown.platform_fees.first.amount.value).to eq("0.30")
expect(refund.seller_payable_breakdown.net_amount.value).to eq("4.55")
expect(refund.seller_payable_breakdown.total_refunded_amount.value).to eq("5.00")
urls = refund.links
expect(urls.size).to eq(2)
expect(urls.map(&:rel)).to match_array(%w(self up))
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/paypal/paypal_chargeable_spec.rb | spec/business/payments/charging/implementations/paypal/paypal_chargeable_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PaypalChargeable do
let(:paypal_chargeable) { PaypalChargeable.new("B-38D505255T217912K", "paypal-gr-integspecs@gumroad.com", "US") }
it "returns customer paypal email for #email, billing agreement id for #fingerprint, and nil #last4" do
expect(paypal_chargeable.fingerprint).to eq("B-38D505255T217912K")
expect(paypal_chargeable.email).to eq("paypal-gr-integspecs@gumroad.com")
expect(paypal_chargeable.last4).to be_nil
end
it "returns customer paypal email for #visual, and nil for #number_length, #expiry_month and #expiry_year" do
expect(paypal_chargeable.visual).to eq("paypal-gr-integspecs@gumroad.com")
expect(paypal_chargeable.number_length).to be_nil
expect(paypal_chargeable.expiry_month).to be_nil
expect(paypal_chargeable.expiry_year).to be_nil
end
it "returns correct country and nil #zip_code" do
expect(paypal_chargeable.zip_code).to be_nil
expect(paypal_chargeable.country).to eq("US")
end
it "returns billing agreement id for #reusable_token!" do
reusable_token = paypal_chargeable.reusable_token!(nil)
expect(reusable_token).to eq("B-38D505255T217912K")
end
it "returns paypal for #charge_processor_id" do
expect(paypal_chargeable.charge_processor_id).to eq("paypal")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/charging/implementations/paypal/paypal_card_fingerprint_spec.rb | spec/business/payments/charging/implementations/paypal/paypal_card_fingerprint_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PaypalCardFingerprint do
describe "build_paypal_fingerprint" do
describe "paypal account has an email address" do
let(:email) { "jane.doe@gmail.com" }
it "forms a fingerprint using the email" do
expect(subject.build_paypal_fingerprint(email)).to eq("paypal_jane.doe@gmail.com")
end
end
describe "paypal account has an invalidly formed address" do
let(:email) { "jane.doe" }
it "forms a fingerprint using the email" do
expect(subject.build_paypal_fingerprint(email)).to eq("paypal_jane.doe")
end
end
describe "paypal account has a whitespace email address" do
let(:email) { " " }
it "returns nil" do
expect(subject.build_paypal_fingerprint(email)).to be_nil
end
end
describe "paypal account has no email address" do
let(:email) { nil }
it "returns nil" do
expect(subject.build_paypal_fingerprint(email)).to be_nil
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/events/stripe/stripe_event_handler_spec.rb | spec/business/payments/events/stripe/stripe_event_handler_spec.rb | # frozen_string_literal: true
describe StripeEventHandler do
let(:event_id) { "evt_eventid" }
describe "error handling", :vcr do
context "when staging environment" do
before do
allow(Rails.env).to receive(:staging?).and_return(true)
end
it "silences errors" do
expect { StripeEventHandler.new(id: "invalid-event-id").handle_stripe_event }.not_to raise_error
end
end
context "when not staging environment" do
before do
allow(Rails.env).to receive(:staging?).and_return(false)
end
it "does not silence errors" do
expect { StripeEventHandler.new(id: "invalid-event-id", type: "charge.succeeded").handle_stripe_event }.to raise_error(NoMethodError)
end
end
end
describe "an event on gumroad's account" do
describe "a charge event" do
let(:stripe_event) do
{
"id" => event_id,
"created" => "1406748559", # "2014-07-30T19:29:19+00:00"
"type" => "charge.succeeded",
"data" => {
"object" => {
"object" => "charge"
}
}
}
end
it "sends the event to StripeChargeProcessor" do
expect(StripeChargeProcessor).to receive(:handle_stripe_event).with(parsed(stripe_event))
described_class.new(stripe_event).handle_stripe_event
end
end
describe "a payment intent failed event" do
let(:stripe_event) do
{
"id" => event_id,
"created" => "1406748559", # "2014-07-30T19:29:19+00:00"
"type" => "payment_intent.payment_failed",
"data" => {
"object" => {
"object" => "payment_intent"
}
}
}
end
it "sends the event to StripeChargeProcessor" do
expect(StripeChargeProcessor).to receive(:handle_stripe_event).with(parsed(stripe_event))
described_class.new(stripe_event).handle_stripe_event
end
end
describe "a capital loan event" do
let(:stripe_event) do
{
"id" => event_id,
"created" => "1668996442",
"type" => "capital.financing_transaction.created",
"data" => {
"object" => {
"object" => "capital.financing_transaction"
}
}
}
end
it "sends the event to StripeChargeProcessor" do
expect(StripeChargeProcessor).to receive(:handle_stripe_event).with(parsed(stripe_event))
described_class.new(stripe_event).handle_stripe_event
end
end
describe "an account event" do
let(:stripe_event) do
{
"id" => event_id,
"created" => "1406748559", # "2014-07-30T19:29:19+00:00"
"type" => "account.updated",
"data" => {
"object" => {
"object" => "account"
}
}
}
end
it "does not send the event to StripeMerchantAccountManager" do
expect(StripeMerchantAccountManager).not_to receive(:handle_stripe_event)
described_class.new(stripe_event).handle_stripe_event
end
end
describe "an ignored event" do
let(:stripe_event) do
{
"id" => event_id,
"created" => "1406748559", # "2014-07-30T19:29:19+00:00"
"type" => "invoice.created",
"data" => {
"object" => {
"object" => "invoice"
}
}
}
end
it "does not send the event to StripeChargeProcessor" do
expect(StripeChargeProcessor).not_to receive(:handle_stripe_event)
expect(StripeMerchantAccountManager).not_to receive(:handle_stripe_event)
described_class.new(stripe_event).handle_stripe_event
end
it "does not retrieve event from stripe" do
expect(Stripe::Event).to_not receive(:retrieve)
described_class.new(stripe_event).handle_stripe_event
end
end
end
describe "an event on a connected account" do
describe "an account event", :vcr do
before do
@user = create(:user)
@merchant_account = create(:merchant_account_stripe, user: @user)
@stripe_event = {
"id" => event_id,
"created" => "1406748559", # "2014-07-30T19:29:19+00:00"
"type" => "account.updated",
"account" => @merchant_account.charge_processor_merchant_id,
"user_id" => @merchant_account.charge_processor_merchant_id,
"default_currency" => "usd",
"country" => "USA",
"data" => {
"object" => {
"object" => "account",
"default_currency" => "usd",
"country" => "USA",
"id" => @merchant_account.charge_processor_merchant_id
}
}
}
@merchant_account.charge_processor_merchant_id
end
it "sends the event to StripeMerchantAccountManager" do
expect(StripeChargeProcessor).not_to receive(:handle_stripe_event)
expect(StripeMerchantAccountManager).to receive(:handle_stripe_event).and_call_original
described_class.new(@stripe_event).handle_stripe_event
end
it "sends the event to StripeMerchantAccountManager when event has an account field" do
expect(StripeChargeProcessor).not_to receive(:handle_stripe_event)
expect(StripeMerchantAccountManager).to receive(:handle_stripe_event).and_call_original
described_class.new(@stripe_event).handle_stripe_event
end
it "updates currency and country for user merchant account" do
@merchant_account.country = "UK"
@merchant_account.currency = "gbp"
@merchant_account.save!
expect(StripeChargeProcessor).not_to receive(:handle_stripe_event)
expect(StripeMerchantAccountManager).to receive(:handle_stripe_event).and_call_original
described_class.new(@stripe_event).handle_stripe_event
@merchant_account.reload
expect(@merchant_account.currency).to eq("usd")
expect(@merchant_account.country).to eq("USA")
end
end
describe "a payout event", :vcr do
let(:stripe_event) do
{
"id" => event_id,
"created" => "1406748559", # "2014-07-30T19:29:19+00:00"
"type" => "payout.paid",
"account" => "acct_1234",
"user_id" => "acct_1234",
"data" => {
"object" => {
"object" => "transfer",
"type" => "bank_account",
"id" => "tr_1234"
}
}
}
end
it "sends the event to StripePayoutProcessor" do
expect(StripeChargeProcessor).not_to receive(:handle_stripe_event)
expect(StripeMerchantAccountManager).not_to receive(:handle_stripe_event)
expect(StripePayoutProcessor).to receive(:handle_stripe_event).with(parsed(stripe_event), stripe_connect_account_id: "acct_1234")
described_class.new(stripe_event).handle_stripe_event
end
end
describe "account deauthorized", :vcr do
before do
@user = create(:user)
@product = create(:product, user: @user)
@merchant_account = create(:merchant_account_stripe, user: @user)
@stripe_event = {
"id" => event_id,
"created" => "1406748559", # "2014-07-30T19:29:19+00:00"
"type" => "account.updated",
"account" => @merchant_account.charge_processor_merchant_id,
"user_id" => @merchant_account.charge_processor_merchant_id,
"data" => {
"object" => {
"object" => "account",
"id" => @merchant_account.charge_processor_merchant_id
}
}
}
allow(Stripe::Account).to receive(:list_persons).and_raise(Stripe::APIError, "Application access may have been revoked.")
end
it "rescues Stripe::APIError exception" do
expect { described_class.new(@stripe_event).handle_stripe_event }.not_to raise_error
end
it "deauthorizes the merchant account" do
expect(StripeMerchantAccountManager).to receive(:handle_stripe_event_account_deauthorized).and_call_original
described_class.new(@stripe_event).handle_stripe_event
@merchant_account.reload
expect(@merchant_account.meta).to eq(nil)
expect(@merchant_account.charge_processor_merchant_id).to eq(@stripe_event[:account])
expect(@merchant_account.deleted_at).not_to eq(nil)
expect(@merchant_account.charge_processor_deleted_at).not_to eq(nil)
expect(@product.alive?).to eq(true)
end
context "merchant_migration enabled" do
before do
Feature.activate_user(:merchant_migration, @user)
end
after do
Feature.deactivate_user(:merchant_migration, @user)
end
it "does not unpublish the products for user" do
expect(StripeMerchantAccountManager).to receive(:handle_stripe_event_account_deauthorized).and_call_original
described_class.new(@stripe_event).handle_stripe_event
@product.reload
expect(@product.alive?).to eq(true)
end
end
end
describe "a capability event", :vcr do
before do
@user = create(:user)
@merchant_account = create(:merchant_account_stripe, user: @user)
@stripe_event = {
"id" => event_id,
"created" => "1406748559",
"type" => "capability.updated",
"account" => @merchant_account.charge_processor_merchant_id,
"user_id" => @merchant_account.charge_processor_merchant_id,
"data" => {
"object" => {
"object" => "capability",
"id" => "transfers",
"account" => @merchant_account.charge_processor_merchant_id,
"requirements" => {
"currently_due" => ["individual.verification.document"],
"eventually_due" => ["individual.verification.document"],
"past_due" => ["individual.verification.document"]
}
},
"account" => {
"id" => @merchant_account.charge_processor_merchant_id,
"object" => "account",
"charges_enabled" => true,
"payouts_enabled" => true,
"requirements" => {
"currently_due" => [],
"eventually_due" => [],
"past_due" => []
},
"future_requirements" => {
"currently_due" => [],
"eventually_due" => [],
"past_due" => []
}
},
"previous_attributes" => {}
}
}
end
it "sends the event to StripeMerchantAccountManager" do
expect(StripeChargeProcessor).not_to receive(:handle_stripe_event)
expect(StripeMerchantAccountManager).to receive(:handle_stripe_event).and_call_original
described_class.new(@stripe_event).handle_stripe_event
end
end
end
private
def parsed(event)
Stripe::Util.convert_to_stripe_object(event, {})
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/events/paypal/paypal_event_handler_spec.rb | spec/business/payments/events/paypal/paypal_event_handler_spec.rb | # frozen_string_literal: true
describe PaypalEventHandler do
describe "#schedule_paypal_event_processing" do
context "when event is from paypal orders API" do
PaypalEventType::ORDER_API_EVENTS.each do |event_type|
before do
@event_info = { "event_type" => event_type }
end
it do
described_class.new(@event_info).schedule_paypal_event_processing
expect(HandlePaypalEventWorker).to have_enqueued_sidekiq_job(@event_info)
end
end
end
context "when event is from Integrated signup API" do
PaypalEventType::MERCHANT_ACCOUNT_EVENTS.each do |event_type|
before do
@event_info = { "event_type" => event_type }
it do
described_class.new(@event_info).schedule_paypal_event_processing
expect(HandlePaypalEventWorker).to have_enqueued_sidekiq_job(@event_info)
end
end
end
end
context "when event is from paypal legacy API" do
let(:event_info) { { "txn_type" => "masspay" } }
it do
described_class.new(event_info).schedule_paypal_event_processing
expect(HandlePaypalEventWorker).to have_enqueued_sidekiq_job(event_info).in(10.minutes)
end
end
end
describe "#handle_paypal_event" do
context "when event is from Integrated signup API" do
it do
event_info = { "event_type" => PaypalEventType::MERCHANT_PARTNER_CONSENT_REVOKED }
expect_any_instance_of(PaypalMerchantAccountManager).to receive(:handle_paypal_event).with(event_info)
described_class.new(event_info).handle_paypal_event
end
end
context "when event is from paypal legacy API" do
context "and IPN verification succeeds" do
before do
WebMock.stub_request(:post, "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr").to_return(body: "VERIFIED")
end
describe "paypal events mocked from production" do
describe "pay via paypal and handle IPNs" do
describe "reversal and cancelled reversal IPN messages" do
describe "reversal event" do
before do
raw_payload =
"payment_type=echeck&payment_date=Sun%20May%2024%202015%2014%3A32%3A31%20GMT-0700%20%28PDT%29&payment_status=Reversed&" \
"payer_status=verified&first_name=John&last_name=Smith&payer_email=buyer%40paypalsandbox.com&payer_id=TESTBUYERID01&address_name=John%20Smith&address_country=United%20States&" \
"address_country_code=US&address_zip=95131&address_state=CA&address_city=San%20Jose&address_street=123%20any%20street&business=seller%40paypalsandbox.com&" \
"receiver_email=seller%40paypalsandbox.com&receiver_id=seller%40paypalsandbox.com&residence_country=US&item_name=something&item_number=AK-1234&quantity=1&" \
"shipping=3.04&tax=2.02&mc_currency=USD&mc_fee=0.44&mc_gross=12.34&mc_gross1=12.34&txn_type=web_accept&txn_id=995288809¬ify_version=2.1&parent_txn_id=SOMEPRIORTXNID002&" \
"reason_code=chargeback&receipt_ID=3012-5109-3782-6103&custom=xyz123&invoice=dPFcxp0U0xmL5o0TD1NP9g%3D%3D&test_ipn=1&" \
"verify_sign=AFcWxV21C7fd0v3bYYYRCpSSRl31A4SYxlXZ9IdB.iATdIIByT4aW.Qa"
@payload = Rack::Utils.parse_nested_query(raw_payload)
end
it "handles a chargeback message from PayPal" do
expect(PaypalPayoutProcessor).to_not receive(:handle_paypal_event)
expect(PaypalChargeProcessor).to receive(:handle_paypal_event).and_call_original
described_class.new(@payload).handle_paypal_event
end
end
describe "reversal cancelled event" do
before do
raw_payload =
"payment_type=instant&payment_date=Sun%20May%2024%202015%2015%3A04%3A11%20GMT-0700%20%28PDT%29&payment_status=Canceled_Reversal&" \
"address_status=confirmed&payer_status=verified&first_name=John&last_name=Smith&payer_email=buyer%40paypalsandbox.com&payer_id=TESTBUYERID01&" \
"address_name=John%20Smith&address_country=United%20States&address_country_code=US&address_zip=95131&address_state=CA&address_city=San%20Jose&" \
"address_street=123%20any%20street&business=seller%40paypalsandbox.com&receiver_email=seller%40paypalsandbox.com&receiver_id=seller%40paypalsandbox.com&residence_country=US&" \
"item_name=something&item_number=AK-1234&quantity=1&shipping=3.04&tax=2.02&mc_currency=USD&mc_fee=0.44&mc_gross=12.34&mc_gross1=12.34&txn_type=web_accept&txn_id=694541630&" \
"notify_version=2.1&parent_txn_id=SOMEPRIORTXNID003&reason_code=other&custom=xyz123&invoice=D7lNKK8L-urz8D3awchsUA%3D%3D&test_ipn=1&" \
"verify_sign=AFcWxV21C7fd0v3bYYYRCpSSRl31A48M..jE7GasP8rDsyMNp6bZuihz"
@payload = Rack::Utils.parse_nested_query(raw_payload)
end
it "handles a chargeback reversed message from PayPal" do
expect(PaypalPayoutProcessor).to_not receive(:handle_paypal_event)
expect(PaypalChargeProcessor).to receive(:handle_paypal_event)
described_class.new(@payload).handle_paypal_event
end
end
end
end
describe "purchase event with an invoice field", :vcr do
before do
raw_payload =
"payment_type=instant&payment_date=Tue%20May%2026%202015%2017%3A15%3A44%20GMT-0700%20%28PDT%29&payment_status=Completed&address_status=confirmed&payer_status=verified&" \
"first_name=John&last_name=Smith&payer_email=buyer%40paypalsandbox.com&payer_id=TESTBUYERID01&address_name=John%20Smith&address_country=United%20States&address_country_code=US&" \
"address_zip=95131&address_state=CA&address_city=San%20Jose&address_street=123%20any%20street&business=seller%40paypalsandbox.com&receiver_email=seller%40paypalsandbox.com&" \
"receiver_id=seller%40paypalsandbox.com&residence_country=US&item_name1=something&item_number1=AK-1234&tax=2.02&mc_currency=USD&mc_fee=0.44&mc_gross=12.34&mc_gross1=12.34&" \
"mc_handling=2.06&mc_handling1=1.67&mc_shipping=3.02&mc_shipping1=1.02&txn_type=cart&txn_id=108864103¬ify_version=2.1&custom=xyz123&invoice=random_external_id%3D%3D&" \
"test_ipn=1&verify_sign=ACAZ6FVFxLgizH8UbrtwxaIa4AOcAwq2HjoeG6XjAhqWvKP.pgZUJAqk"
@payload = Rack::Utils.parse_nested_query(raw_payload)
end
it "is handled by the PayPal charge processor" do
expect(PaypalChargeProcessor).to receive(:handle_paypal_event).and_call_original
expect(PaypalPayoutProcessor).to_not receive(:handle_paypal_event)
described_class.new(@payload).handle_paypal_event
end
end
describe "payouts IPN messages" do
before do
raw_payload =
"txn_type=masspay&payment_gross_1=10.00&payment_date=17:19:05 Jun 24, 2015 PDT&last_name=Lavingia&mc_fee_1=0.20&masspay_txn_id_1=8G377690596809442&" \
"receiver_email_1=paypal-buyer@gumroad.com&residence_country=US&verify_sign=Ae-XDUZhrxwaCSsmGO9JpO33K7P1AozUnt1w.tzHJKWOWYlez5cVvscv&payer_status=verified&" \
"test_ipn=1&payer_email=paypal-gr-sandbox@gumroad.com&first_name=Sahil&payment_fee_1=0.20&payer_id=3FBN6YS9YFTV6&payer_business_name=Sahil Lavingia's Test Store&" \
"payment_status=Processed&status_1=Completed&mc_gross_1=10.00&charset=windows-1252¬ify_version=3.8&mc_currency_1=USD&unique_id_1=38&ipn_track_id=29339dfb40e24"
@payload = Rack::Utils.parse_nested_query(raw_payload)
@payment = create(:payment, id: 38)
end
it "assigns messages with the masspay transaction type to the payout processor" do
expect(@payment.state).to eq("processing")
expect(PaypalPayoutProcessor).to receive(:handle_paypal_event).with(@payload).and_call_original
described_class.new(@payload).handle_paypal_event
expect(@payment.reload.state).to eq("completed")
end
end
end
describe "ignored IPN messages" do
describe "cart checkout IPN messages" do
before do
raw_payload =
"payment_date=17:36:04 Jul 22, 2015 PDT&txn_type=cart&last_name=buyer&residence_country=US&pending_reason=order&item_name=Gumroad Purchase& " \
"payment_gross=127.56&mc_currency=USD&verify_sign=AUkau1FwogE3kL3qo1vGTARqlijQAi30ARWjcqXEBUjAiWyIw2fh8BbU&payer_status=verified&test_ipn=1&tax=0.00&" \
"payer_email=paypal-buyer@gumroad.com&txn_id=O-1WA78012KV456861R&quantity=1&receiver_email=paypal-gr-sandbox@gumroad.com&first_name=test&payer_id=YZGRBNEN5T2QJ&"\
"receiver_id=3FBN6YS9YFTV6&item_number=&payer_business_name=Gumroad Inc.&handling_amount=0.00&payment_status=Pending&shipping=0.00&mc_gross=127.56&custom=&" \
"transaction_entity=order&charset=windows-1252¬ify_version=3.8&ipn_track_id=afd7f243d4729"
@payload = Rack::Utils.parse_nested_query(raw_payload)
end
it "does nothing with express checkout messages for Order creation and does not error out" do
expect(Payment).to_not receive(:find)
expect(Purchase).to_not receive(:find_by_external_id)
expect(Bugsnag).to_not receive(:notify)
described_class.new(@payload).handle_paypal_event
end
end
describe "express checkout IPN messages", :vcr do
before do
raw_payload =
"payment_date=17:36:04 Jul 22, 2015 PDT&txn_type=express_checkout&last_name=buyer&residence_country=US&pending_reason=order&item_name=Gumroad Purchase& " \
"payment_gross=127.56&mc_currency=USD&verify_sign=AUkau1FwogE3kL3qo1vGTARqlijQAi30ARWjcqXEBUjAiWyIw2fh8BbU&payer_status=verified&test_ipn=1&tax=0.00&" \
"payer_email=paypal-buyer@gumroad.com&txn_id=O-1WA78012KV456861R&quantity=1&receiver_email=paypal-gr-sandbox@gumroad.com&first_name=test&payer_id=YZGRBNEN5T2QJ&"\
"receiver_id=3FBN6YS9YFTV6&item_number=&payer_business_name=Gumroad Inc.&handling_amount=0.00&payment_status=Pending&shipping=0.00&mc_gross=127.56&custom=&" \
"transaction_entity=order&charset=windows-1252¬ify_version=3.8&ipn_track_id=afd7f243d4729"
@payload = Rack::Utils.parse_nested_query(raw_payload)
end
it "does nothing with express checkout messages for Order creation and does not error out" do
expect(Payment).to_not receive(:find)
expect(Purchase).to_not receive(:find_by_external_id)
expect(Bugsnag).to_not receive(:notify)
described_class.new(@payload).handle_paypal_event
end
end
describe "express checkout IPN message with invalid IPN", :vcr do
before do
raw_payload =
"payment_date=17:36:04 Jul 22, 2015 PDT&txn_type=express_checkout&last_name=buyer&residence_country=US&pending_reason=order&item_name=Gumroad Purchase& " \
"payment_gross=127.56&mc_currency=USD&verify_sign=AUkau1FwogE3kL3qo1vGTARqlijQAi30ARWjcqXEBUjAiWyIw2fh8BbU&payer_status=verified&test_ipn=1&tax=0.00&" \
"payer_email=paypal-buyer@gumroad.com&txn_id=xxxxxx-1WA78012KV456861R&quantity=1&receiver_email=paypal-gr-sandbox@gumroad.com&first_name=test&payer_id=YZGRBNEN5T2QJ&"\
"receiver_id=3FBN6YS9YFTV6&item_number=&payer_business_name=Gumroad Inc.&handling_amount=0.00&payment_status=Pending&shipping=0.00&mc_gross=127.56&custom=&" \
"transaction_entity=order&charset=windows-1252¬ify_version=3.8&ipn_track_id=afd7f243d4729"
@payload = Rack::Utils.parse_nested_query(raw_payload)
end
it "does nothing with invalid transaction ipn" do
expect(Payment).to_not receive(:find)
expect(Purchase).to_not receive(:find_by_external_id)
expect(Bugsnag).to_not receive(:notify)
described_class.new(@payload).handle_paypal_event
end
end
describe "Billing agreement creation checkout messages" do
before do
raw_payload =
"payment_date=17:36:04 Jul 22, 2015 PDT&txn_type=mp_signup&last_name=buyer&residence_country=US&pending_reason=order&item_name=Gumroad Purchase& " \
"payment_gross=127.56&mc_currency=USD&verify_sign=AUkau1FwogE3kL3qo1vGTARqlijQAi30ARWjcqXEBUjAiWyIw2fh8BbU&payer_status=verified&test_ipn=1&tax=0.00&" \
"payer_email=paypal-buyer@gumroad.com&txn_id=O-1WA78012KV456861R&quantity=1&receiver_email=paypal-gr-sandbox@gumroad.com&first_name=test&payer_id=YZGRBNEN5T2QJ&"\
"receiver_id=3FBN6YS9YFTV6&item_number=&payer_business_name=Gumroad Inc.&handling_amount=0.00&payment_status=Pending&shipping=0.00&mc_gross=127.56&custom=&" \
"transaction_entity=order&charset=windows-1252¬ify_version=3.8&ipn_track_id=afd7f243d4729"
@payload = Rack::Utils.parse_nested_query(raw_payload)
end
it "does nothing with express checkout messages for new billing agreeement and does not error out" do
expect(Payment).to_not receive(:find)
expect(Purchase).to_not receive(:find_by_external_id)
expect(Bugsnag).to_not receive(:notify)
described_class.new(@payload).handle_paypal_event
end
end
end
end
context "and IPN verification fails" do
before do
WebMock.stub_request(:post, "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr").to_return(body: "INVALID")
end
it "does not process the IPN payload" do
payment = create(:payment)
raw_payload =
"txn_type=masspay&payment_gross_1=10.00&payment_date=17:19:05 Jun 24, 2015 PDT&last_name=Lavingia&mc_fee_1=0.20&masspay_txn_id_1=8G377690596809442&" \
"receiver_email_1=paypal-buyer@gumroad.com&residence_country=US&verify_sign=Ae-XDUZhrxwaCSsmGO9JpO33K7P1AozUnt1w.tzHJKWOWYlez5cVvscv&payer_status=verified&" \
"test_ipn=1&payer_email=paypal-gr-sandbox@gumroad.com&first_name=Sahil&payment_fee_1=0.20&payer_id=3FBN6YS9YFTV6&payer_business_name=Sahil Lavingia's Test Store&" \
"payment_status=Processed&status_1=Completed&mc_gross_1=10.00&charset=windows-1252¬ify_version=3.8&mc_currency_1=USD&unique_id_1=#{payment.id}&ipn_track_id=29339dfb40e24"
payload = Rack::Utils.parse_nested_query(raw_payload)
expect(PaypalPayoutProcessor).not_to receive(:handle_paypal_event)
described_class.new(payload).handle_paypal_event
expect(payment.state).to eq("processing")
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/business/payments/transfers/stripe/stripe_transfer_externally_to_gumroad_spec.rb | spec/business/payments/transfers/stripe/stripe_transfer_externally_to_gumroad_spec.rb | # frozen_string_literal: true
describe StripeTransferExternallyToGumroad, :vcr do
include StripeChargesHelper
describe "available balances" do
let(:available_balances) { described_class.available_balances }
before do
# ensure the available balance has positive value
create_stripe_charge(StripePaymentMethodHelper.success_available_balance.to_stripejs_payment_method_id,
amount: 100,
currency: "usd"
)
expect(!available_balances.empty?).to eq(true)
end
describe "available_balances" do
it "returns a hash of currencies to balances in cents" do
expect(available_balances).to be_a(Hash)
expect(available_balances.keys).to include("usd")
available_balances.each do |_currency, balance_cents|
expect(balance_cents).to be_a(Integer)
end
end
end
describe "transfer" do
it "transfers the currency and balance using stripe to the Gumroad recipient" do
expect(Stripe::Payout).to receive(:create).with(hash_including(
amount: 1234,
currency: "usd",
))
travel_to(Time.zone.local(2015, 4, 7)) do
described_class.transfer("usd", 1234)
end
end
it "sets the description (which shows up in the stripe dashboard)" do
expect(Stripe::Payout).to receive(:create).with(hash_including(
description: "USD 150407 0000"
))
travel_to(Time.zone.local(2015, 4, 7)) do
described_class.transfer("usd", 1234)
end
end
end
describe "transfer_all_available_balances" do
describe "with balance" do
before do
expect(described_class).to receive(:available_balances).and_return("usd" => 100_00)
end
it "creates a stripe transfer for each available balance" do
expect(described_class).to receive(:transfer).with("usd", 100_00)
described_class.transfer_all_available_balances
end
end
describe "with balance greater than 99_999_999_99 cents" do
before do
expect(described_class).to receive(:available_balances).and_return("usd" => 100_000_000_00)
end
it "creates a stripe transfer for 99_999_999_99 cents" do
expect(described_class).to receive(:transfer).with("usd", 99_999_999_99)
described_class.transfer_all_available_balances
end
end
describe "zero balance" do
before do
expect(described_class).to receive(:available_balances).and_return("usd" => 0, "cad" => 100)
end
it "does not attempt to transfer" do
expect(described_class).not_to receive(:transfer).with("usd", anything)
expect(described_class).to receive(:transfer).with("cad", 100)
described_class.transfer_all_available_balances
end
end
describe "negative balance" do
before do
expect(described_class).to receive(:available_balances).and_return("usd" => -100, "cad" => 100)
end
it "does not attempt to transfer" do
expect(described_class).not_to receive(:transfer).with("usd", anything)
expect(described_class).to receive(:transfer).with("cad", 100)
described_class.transfer_all_available_balances
end
end
describe "with buffer" do
let(:buffer_cents) { 50 }
describe "with balance" do
it "creates a stripe transfer for each available balance" do
available_balances.each do |currency, balance_cents|
expect(described_class).to receive(:transfer).with(currency, balance_cents - 50) if balance_cents > 0
end
described_class.transfer_all_available_balances(buffer_cents:)
end
end
describe "zero balance" do
before do
expect(described_class).to receive(:available_balances).and_return("usd" => 0, "cad" => 100)
end
it "does not attempt to transfer" do
expect(described_class).not_to receive(:transfer).with("usd", anything)
expect(described_class).to receive(:transfer).with("cad", 50)
described_class.transfer_all_available_balances(buffer_cents:)
end
end
describe "negative balance" do
before do
expect(described_class).to receive(:available_balances).and_return("usd" => -100, "cad" => 100)
end
it "does not attempt to transfer" do
expect(described_class).not_to receive(:transfer).with("usd", anything)
expect(described_class).to receive(:transfer).with("cad", 50)
described_class.transfer_all_available_balances(buffer_cents:)
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/business/payments/transfers/stripe/stripe_transfer_internally_to_creator_spec.rb | spec/business/payments/transfers/stripe/stripe_transfer_internally_to_creator_spec.rb | # frozen_string_literal: true
describe StripeTransferInternallyToCreator, :vcr do
include StripeMerchantAccountHelper
include StripeChargesHelper
describe "transfer_funds_to_account" do
before do
# ensure the available balance has positive value
create_stripe_charge(StripePaymentMethodHelper.success_available_balance.to_stripejs_payment_method_id,
amount: 100_000_00,
currency: "usd"
)
end
let(:managed_account) { create_verified_stripe_account(country: "US") }
let(:managed_account_id) { managed_account.id }
describe "transfer_funds_to_account" do
describe "when no related charge given" do
it "creates a transfer at stripe destined for the connected account" do
expect(Stripe::Transfer).to receive(:create).with(hash_including(
destination: managed_account_id,
currency: "usd",
amount: 1_000_00,
description: "message_why",
metadata: nil
)).and_call_original
subject.transfer_funds_to_account(message_why: "message_why",
stripe_account_id: managed_account_id,
currency: Currency::USD,
amount_cents: 1_000_00)
end
it "returns a transfer that has balance transactions for itself and for the application fee" do
transfer = subject.transfer_funds_to_account(message_why: "message_why",
stripe_account_id: managed_account_id,
currency: Currency::USD,
amount_cents: 1_000_00)
expect(transfer.balance_transaction).to be_a(Stripe::BalanceTransaction)
end
end
describe "when a related charge is given" do
it "creates a transfer at stripe destined for the connected account" do
expect(Stripe::Transfer).to receive(:create).with(hash_including(
destination: managed_account_id,
currency: "usd",
amount: 1_000_00,
description: "message_why Related Charge ID: charge-id.",
metadata: nil
)).and_call_original
subject.transfer_funds_to_account(message_why: "message_why",
stripe_account_id: managed_account_id,
currency: Currency::USD,
amount_cents: 1_000_00,
related_charge_id: "charge-id")
end
it "returns a transfer that has balance transactions for itself and for the application fee" do
transfer = subject.transfer_funds_to_account(message_why: "message_why",
stripe_account_id: managed_account_id,
currency: Currency::USD,
amount_cents: 1_000_00)
expect(transfer.balance_transaction).to be_a(Stripe::BalanceTransaction)
end
end
describe "when metadata is given" do
it "creates a transfer with the given metadata" do
expect(Stripe::Transfer).to receive(:create).with(hash_including(
destination: managed_account_id,
currency: "usd",
amount: 1_000_00,
description: "message_why",
metadata: {
metadata_1: "metadata_1",
metadata_2: 1234,
metadata_3: "metadata_2_a,metadata_2_a"
}
)).and_call_original
subject.transfer_funds_to_account(message_why: "message_why",
stripe_account_id: managed_account_id,
currency: Currency::USD,
amount_cents: 1_000_00,
metadata: {
metadata_1: "metadata_1",
metadata_2: 1234,
metadata_3: %w[metadata_2_a metadata_2_a].join(",")
})
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/business/payments/utilities/stripe_url_spec.rb | spec/business/payments/utilities/stripe_url_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StripeUrl do
describe "dashboard_url" do
describe "production" do
before do
allow(Rails.env).to receive(:production?).and_return(true)
end
after do
allow(Rails.env).to receive(:production?).and_call_original
end
it "returns a stripe dashboard url" do
expect(described_class.dashboard_url(account_id: "1234")).to eq("https://dashboard.stripe.com/1234/dashboard")
end
end
describe "not production" do
it "returns a stripe test dashboard url" do
expect(described_class.dashboard_url(account_id: "1234")).to eq("https://dashboard.stripe.com/1234/test/dashboard")
end
end
end
describe "event_url" do
describe "production" do
before do
allow(Rails.env).to receive(:production?).and_return(true)
end
after do
allow(Rails.env).to receive(:production?).and_call_original
end
it "returns a stripe dashboard url" do
expect(described_class.event_url("1234")).to eq("https://dashboard.stripe.com/events/1234")
end
end
describe "not production" do
it "returns a stripe test dashboard url" do
expect(described_class.event_url("1234")).to eq("https://dashboard.stripe.com/test/events/1234")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/payments/utilities/stripe_metadata_spec.rb | spec/business/payments/utilities/stripe_metadata_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe StripeMetadata do
describe "build_metadata_large_list" do
let(:key) { "myKey" }
let(:items) { %w[asdfasdf asdfasdfasdfasdf] }
it "returns a key-value pair hash of items" do
expect(subject.build_metadata_large_list(items, key:)).to eq(
"myKey{0}" => "asdfasdf,asdfasdfasdfasdf"
)
end
describe "key is symbol" do
let(:key) { :my_key }
it "results in a string key too" do
expect(subject.build_metadata_large_list(items, key:)).to eq("my_key{0}" => "asdfasdf,asdfasdfasdfasdf")
end
end
describe "big list" do
let(:items) { (1..99).map { |n| format("asdfasdf%.2i", n) } }
it "returns a multiple key-value pairs" do
expect(subject.build_metadata_large_list(items, key:)).to eq(
"myKey{0}" => "asdfasdf01,asdfasdf02,asdfasdf03,asdfasdf04,asdfasdf05,asdfasdf06,asdfasdf07,asdfasdf08,asdfasdf09," \
"asdfasdf10,asdfasdf11,asdfasdf12,asdfasdf13,asdfasdf14,asdfasdf15,asdfasdf16,asdfasdf17,asdfasdf18," \
"asdfasdf19,asdfasdf20,asdfasdf21,asdfasdf22,asdfasdf23,asdfasdf24,asdfasdf25,asdfasdf26,asdfasdf27," \
"asdfasdf28,asdfasdf29,asdfasdf30,asdfasdf31,asdfasdf32,asdfasdf33,asdfasdf34,asdfasdf35,asdfasdf36," \
"asdfasdf37,asdfasdf38,asdfasdf39,asdfasdf40,asdfasdf41,asdfasdf42,asdfasdf43,asdfasdf44,asdfasdf45",
"myKey{1}" => "asdfasdf46,asdfasdf47,asdfasdf48,asdfasdf49,asdfasdf50,asdfasdf51,asdfasdf52,asdfasdf53,asdfasdf54," \
"asdfasdf55,asdfasdf56,asdfasdf57,asdfasdf58,asdfasdf59,asdfasdf60,asdfasdf61,asdfasdf62,asdfasdf63," \
"asdfasdf64,asdfasdf65,asdfasdf66,asdfasdf67,asdfasdf68,asdfasdf69,asdfasdf70,asdfasdf71,asdfasdf72," \
"asdfasdf73,asdfasdf74,asdfasdf75,asdfasdf76,asdfasdf77,asdfasdf78,asdfasdf79,asdfasdf80,asdfasdf81," \
"asdfasdf82,asdfasdf83,asdfasdf84,asdfasdf85,asdfasdf86,asdfasdf87,asdfasdf88,asdfasdf89,asdfasdf90",
"myKey{2}" => "asdfasdf91,asdfasdf92,asdfasdf93,asdfasdf94,asdfasdf95,asdfasdf96,asdfasdf97,asdfasdf98,asdfasdf99"
)
end
end
describe "big items" do
let(:items) do
[
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01" \
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01" \
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01" \
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01" \
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01" \
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01",
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02" \
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02" \
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02" \
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02" \
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02" \
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02"
]
end
it "returns a multiple key-value pairs with the big items in each one" do
expect(subject.build_metadata_large_list(items, key:)).to eq(
"myKey{0}" =>
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01" \
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01" \
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01" \
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01" \
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01" \
"asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01asdfasdf01",
"myKey{1}" =>
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02" \
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02" \
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02" \
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02" \
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02" \
"asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02asdfasdf02"
)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/sales_tax/sales_tax_calculation_spec.rb | spec/business/sales_tax/sales_tax_calculation_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SalesTaxCalculation do
it "returns a valid object for the zero tax helper" do
taxation_info = SalesTaxCalculation.zero_tax(100)
expect(taxation_info.price_cents).to eq(100)
expect(taxation_info.tax_cents).to eq(0)
expect(taxation_info.zip_tax_rate).to be(nil)
end
describe "to_hash" do
it "returns a valid hash even on zero/no/invalid tax calculation" do
actual_hash = SalesTaxCalculation.zero_tax(100).to_hash
expect(actual_hash[:price_cents]).to eq(100)
expect(actual_hash[:tax_cents]).to eq(0)
expect(actual_hash[:has_vat_id_input]).to eq(false)
end
it "serializes a valid tax calculation" do
zip_tax_rate = create(:zip_tax_rate, is_seller_responsible: 0)
actual_hash = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 10,
zip_tax_rate:).to_hash
expect(actual_hash[:price_cents]).to eq(100)
expect(actual_hash[:tax_cents]).to eq(10)
expect(actual_hash[:has_vat_id_input]).to be(false)
end
it "serializes a valid tax calculation for an EU country" do
zip_tax_rate = create(:zip_tax_rate, country: "IT", is_seller_responsible: 0)
actual_hash = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 10,
zip_tax_rate:).to_hash
expect(actual_hash[:price_cents]).to eq(100)
expect(actual_hash[:tax_cents]).to eq(10)
expect(actual_hash[:has_vat_id_input]).to be(true)
end
it "serializes a valid tax calculation for Australia" do
zip_tax_rate = create(:zip_tax_rate, country: "AU", is_seller_responsible: 0)
actual_hash = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 10,
zip_tax_rate:).to_hash
expect(actual_hash[:price_cents]).to eq(100)
expect(actual_hash[:tax_cents]).to eq(10)
expect(actual_hash[:has_vat_id_input]).to be(true)
end
it "serializes a valid tax calculation for Singapore" do
zip_tax_rate = create(:zip_tax_rate, country: "SG", is_seller_responsible: 0)
actual_hash = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 8,
zip_tax_rate:).to_hash
expect(actual_hash[:price_cents]).to eq(100)
expect(actual_hash[:tax_cents]).to eq(8)
expect(actual_hash[:has_vat_id_input]).to be(true)
end
it "serializes a valid tax calculation for Canada province Quebec" do
actual_hash = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 8,
zip_tax_rate: nil,
is_quebec: true).to_hash
expect(actual_hash[:price_cents]).to eq(100)
expect(actual_hash[:tax_cents]).to eq(8)
expect(actual_hash[:has_vat_id_input]).to be(true)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/sales_tax/sales_tax_calculator_spec.rb | spec/business/sales_tax/sales_tax_calculator_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SalesTaxCalculator do
describe "input validation" do
it "only accepts a hash for buyer location info" do
expect do
SalesTaxCalculator.new(product: create(:product),
price_cents: 100,
buyer_location: 123_456).calculate
end.to raise_error(SalesTaxCalculatorValidationError, "Buyer Location should be a Hash")
end
it "only accepts an integer for base price in cents" do
expect do
SalesTaxCalculator.new(product: create(:product),
price_cents: 100.0,
buyer_location: { postal_code: "12345", country: "US" }).calculate
end.to raise_error(SalesTaxCalculatorValidationError, "Price (cents) should be an Integer")
end
it "requires product to be an instance of the class" do
expect do
SalesTaxCalculator.new(product: [],
price_cents: 100,
buyer_location: { postal_code: "12345", country: "US" },).calculate
end.to raise_error(SalesTaxCalculatorValidationError, "Product should be a Link instance")
end
end
describe "#calculate" do
before(:each) do
@seller = create(:user)
end
it "returns zero tax if the base price is 0" do
sales_tax = SalesTaxCalculator.new(product: create(:product, user: @seller),
price_cents: 0,
buyer_location: { postal_code: "12345", country: "US" }).calculate
compare_calculations(expected: SalesTaxCalculation.zero_tax(0), actual: sales_tax)
end
it "returns zero tax if product is physical and in the EU" do
create(:zip_tax_rate, country: "DE", zip_code: nil, state: nil)
sales_tax = SalesTaxCalculator.new(product: create(:physical_product, user: @seller),
price_cents: 100,
buyer_location: { country: "DE" }).calculate
compare_calculations(expected: SalesTaxCalculation.zero_tax(100), actual: sales_tax)
end
it "ignores seller taxable regions and overrides inclusive taxation when applicable (non-US)" do
expected_tax_rate = create(:zip_tax_rate, country: "ES", zip_code: nil, state: nil, combined_rate: 0.21, is_seller_responsible: false)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 21,
zip_tax_rate: expected_tax_rate)
actual_sales_tax = SalesTaxCalculator.new(product: create(:product, user: @seller),
price_cents: 100,
buyer_location: { country: "ES" },).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
describe "with TaxJar", :vcr do
before do
@creator = create(:user_with_compliance_info)
@product = create(:physical_product, user: @creator, require_shipping: true, price_cents: 1000)
@product.shipping_destinations << ShippingDestination.new(country_code: "US", one_item_rate_cents: 100, multiple_items_rate_cents: 200)
@product.save!
end
it "calculates with TaxJar for a state where shipping is taxable" do
expected_rate = 0.1025.to_d
expected_tax_cents = ((@product.price_cents + @product.shipping_destinations.last.one_item_rate_cents) * expected_rate).round.to_d
expected_calculation = SalesTaxCalculation.new(price_cents: @product.price_cents,
tax_cents: expected_tax_cents,
zip_tax_rate: nil,
used_taxjar: true,
taxjar_info: {
combined_tax_rate: expected_rate,
state_tax_rate: 0.065,
county_tax_rate: 0.003,
city_tax_rate: 0.0115,
gst_tax_rate: nil,
pst_tax_rate: nil,
qst_tax_rate: nil,
jurisdiction_state: "WA",
jurisdiction_county: "KING",
jurisdiction_city: "SEATTLE",
})
calculation = SalesTaxCalculator.new(product: @product,
price_cents: @product.price_cents,
shipping_cents: @product.shipping_destinations.last.one_item_rate_cents,
quantity: 1,
buyer_location: { postal_code: "98121", country: "US" }).calculate
compare_calculations(expected: expected_calculation, actual: calculation)
end
it "does not call TaxJar and returns zero tax when customer zip code is invalid" do
expect_any_instance_of(TaxjarApi).to_not receive(:calculate_tax_for_order)
calculation = SalesTaxCalculator.new(product: @product,
price_cents: @product.price_cents,
shipping_cents: @product.shipping_destinations.last.one_item_rate_cents,
quantity: 1,
buyer_location: { postal_code: "invalidzip", country: "US" }).calculate
compare_calculations(expected: SalesTaxCalculation.zero_tax(@product.price_cents), actual: calculation)
end
it "does not call TaxJar and returns zero tax when creator doesn't have nexus in the state of the customer zip" do
expect_any_instance_of(TaxjarApi).to_not receive(:calculate_tax_for_order)
calculation = SalesTaxCalculator.new(product: @product,
price_cents: @product.price_cents,
shipping_cents: @product.shipping_destinations.last.one_item_rate_cents,
quantity: 1,
buyer_location: { postal_code: "94107", country: "US" }).calculate
compare_calculations(expected: SalesTaxCalculation.zero_tax(@product.price_cents), actual: calculation)
end
it "does not charge tax for purchases in situations where Gumroad is not responsible for tax" do
actual_sales_tax = SalesTaxCalculator.new(product: create(:product, user: @seller),
price_cents: 100,
buyer_location: { country: "US", postal_code: "94104" },
from_discover: true).calculate
compare_calculations(expected: SalesTaxCalculation.zero_tax(100), actual: actual_sales_tax)
end
shared_examples "valid tax calculation for a US state" do |state, county, city, zip_code, combined_rate, state_rate, county_rate, city_rate|
it "performs a valid tax calculation for #{state} when the sale is recommended" do
expected_tax_amount = (100 * combined_rate).round
expected_sales_tax = SalesTaxCalculation.new(
price_cents: 100,
tax_cents: expected_tax_amount,
zip_tax_rate: nil,
used_taxjar: true,
taxjar_info: {
combined_tax_rate: combined_rate,
state_tax_rate: state_rate,
county_tax_rate: county_rate,
city_tax_rate: city_rate,
gst_tax_rate: nil,
pst_tax_rate: nil,
qst_tax_rate: nil,
jurisdiction_state: state,
jurisdiction_county: county,
jurisdiction_city: city,
}
)
actual_sales_tax = SalesTaxCalculator.new(
product: create(:product, user: @seller),
price_cents: 100,
buyer_location: { country: "US", postal_code: zip_code },
from_discover: true
).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
include_examples "valid tax calculation for a US state", "WI", "SHEBOYGAN", "WALDO", "53093", 0.055, 0.05, 0.005, 0.0
include_examples "valid tax calculation for a US state", "WA", "FRANKLIN", nil, "99301", 0.081, 0.065, 0.006, 0.01
include_examples "valid tax calculation for a US state", "NC", "WAKE", "CARY", "27513", 0.0725, 0.0475, 0.02, 0.0
include_examples "valid tax calculation for a US state", "NJ", "ESSEX", "NEWARK", "07101", 0.06625, 0.06625, 0.0, 0.0
include_examples "valid tax calculation for a US state", "OH", "LICKING", "BLACKLICK", "43004", 0.0725, 0.0575, 0.015, 0.0
include_examples "valid tax calculation for a US state", "PA", "PHILADELPHIA", "PHILADELPHIA", "19019", 0.06, 0.06, 0.0, 0.0
include_examples "valid tax calculation for a US state", "AR", "PULASKI", "LITTLE ROCK", "72201", 0.075, 0.065, 0.01, 0.0
include_examples "valid tax calculation for a US state", "AZ", "MARICOPA", nil, "85001", 0.063, 0.056, 0.007, 0.0
include_examples "valid tax calculation for a US state", "CO", "DENVER", "DENVER", "80202", 0.04, 0.029, 0.0, 0.0
include_examples "valid tax calculation for a US state", "CT", "HARTFORD", "CENTRAL", "06103", 0.0635, 0.0635, 0.0, 0.0
include_examples "valid tax calculation for a US state", "DC", "DISTRICT OF COLUMBIA", "WASHINGTON", "20001", 0.06, 0.06, 0.0, 0.0
include_examples "valid tax calculation for a US state", "GA", "FULTON", "ATLANTA", "30301", 0.0, 0.0, 0.0, 0.0
include_examples "valid tax calculation for a US state", "HI", "HONOLULU", "URBAN HONOLULU", "96813", 0.045, 0.04, 0.005, 0.0
include_examples "valid tax calculation for a US state", "IL", "COOK", "CHICAGO", "60601", 0.0, 0.0, 0.0, 0.0
include_examples "valid tax calculation for a US state", "IN", "MARION", "INDIANAPOLIS", "46201", 0.07, 0.07, 0.0, 0.0
include_examples "valid tax calculation for a US state", "KY", "JEFFERSON", "LOUISVILLE", "40201", 0.06, 0.06, 0.0, 0.0
include_examples "valid tax calculation for a US state", "LA", "ORLEANS", "NEW ORLEANS", "70112", 0.0945, 0.0445, 0.0, 0.0
include_examples "valid tax calculation for a US state", "MA", "SUFFOLK", "BOSTON", "02108", 0.0, 0.0, 0.0, 0.0
include_examples "valid tax calculation for a US state", "MD", "BALTIMORE CITY", "BALTIMORE", "21201", 0.0, 0.0, 0.0, 0.0
include_examples "valid tax calculation for a US state", "MN", "HENNEPIN", "MINNEAPOLIS", "55401", 0.09025, 0.06875, 0.0015, 0.005
include_examples "valid tax calculation for a US state", "NE", "DOUGLAS", "OMAHA", "68102", 0.07, 0.055, 0.0, 0.015
include_examples "valid tax calculation for a US state", "NY", "NEW YORK", "NEW YORK", "10001", 0.0, 0.0, 0.0, 0.0
include_examples "valid tax calculation for a US state", "RI", "PROVIDENCE", "PROVIDENCE", "02903", 0.07, 0.07, 0.0, 0.0
include_examples "valid tax calculation for a US state", "SD", "MINNEHAHA", "SIOUX FALLS", "57101", 0.062, 0.042, 0.0, 0.02
include_examples "valid tax calculation for a US state", "TN", "DAVIDSON", "NASHVILLE-DAVIDSON METROPOLITAN GOVERNMENT (BALANCE)", "37201", 0.1, 0.07, 0.025, 0.0
include_examples "valid tax calculation for a US state", "TX", "TRAVIS", "AUSTIN", "78701", 0.0825, 0.0625, 0.00, 0.01
include_examples "valid tax calculation for a US state", "UT", "SALT LAKE", "SALT LAKE CITY", "84101", 0.0775, 0.0485, 0.024, 0.005
include_examples "valid tax calculation for a US state", "VT", "CHITTENDEN", "BURLINGTON", "05401", 0.07, 0.06, 0.0, 0.01
shared_examples "valid tax calculation for US state" do |state, county, city, zip_code, combined_rate, state_rate, county_rate, city_rate|
it "performs a valid tax calculation for #{state} when the sale is not recommended" do
expected_tax_amount = (100 * combined_rate).round
expected_sales_tax = SalesTaxCalculation.new(
price_cents: 100,
tax_cents: expected_tax_amount,
zip_tax_rate: nil,
used_taxjar: true,
taxjar_info: {
combined_tax_rate: combined_rate,
state_tax_rate: state_rate,
county_tax_rate: county_rate,
city_tax_rate: city_rate,
gst_tax_rate: nil,
pst_tax_rate: nil,
qst_tax_rate: nil,
jurisdiction_state: state,
jurisdiction_county: county,
jurisdiction_city: city,
}
)
actual_sales_tax = SalesTaxCalculator.new(
product: create(:product, user: @seller),
price_cents: 100,
buyer_location: { country: "US", postal_code: zip_code },
from_discover: false
).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
include_examples "valid tax calculation for US state", "WI", "SHEBOYGAN", "WALDO", "53093", 0.055, 0.05, 0.005, 0.0
include_examples "valid tax calculation for US state", "WA", "FRANKLIN", nil, "99301", 0.081, 0.065, 0.006, 0.01
include_examples "valid tax calculation for US state", "NC", "WAKE", "CARY", "27513", 0.0725, 0.0475, 0.02, 0.0
include_examples "valid tax calculation for US state", "NJ", "HUDSON", "JERSEY CITY", "07302", 0.06625, 0.06625, 0.0, 0.0
include_examples "valid tax calculation for US state", "OH", "LICKING", "BLACKLICK", "43004", 0.0725, 0.0575, 0.015, 0.0
include_examples "valid tax calculation for US state", "PA", "PHILADELPHIA", "PHILADELPHIA", "19019", 0.06, 0.06, 0.0, 0.0
include_examples "valid tax calculation for US state", "AR", "PULASKI", "LITTLE ROCK", "72201", 0.075, 0.065, 0.01, 0.0
include_examples "valid tax calculation for US state", "AZ", "MARICOPA", nil, "85001", 0.063, 0.056, 0.007, 0.0
include_examples "valid tax calculation for US state", "CO", "DENVER", "DENVER", "80202", 0.04, 0.029, 0.0, 0.0
include_examples "valid tax calculation for US state", "CT", "HARTFORD", "CENTRAL", "06103", 0.0635, 0.0635, 0.0, 0.0
include_examples "valid tax calculation for US state", "DC", "DISTRICT OF COLUMBIA", "WASHINGTON", "20001", 0.06, 0.06, 0.0, 0.0
include_examples "valid tax calculation for US state", "GA", "FULTON", "ATLANTA", "30301", 0.0, 0.0, 0.0, 0.0
include_examples "valid tax calculation for US state", "HI", "HONOLULU", "URBAN HONOLULU", "96813", 0.045, 0.04, 0.005, 0.0
include_examples "valid tax calculation for US state", "IL", "COOK", "CHICAGO", "60601", 0.0, 0.0, 0.0, 0.0
include_examples "valid tax calculation for US state", "IN", "MARION", "INDIANAPOLIS", "46201", 0.07, 0.07, 0.0, 0.0
include_examples "valid tax calculation for US state", "KY", "JEFFERSON", "LOUISVILLE", "40201", 0.06, 0.06, 0.0, 0.0
include_examples "valid tax calculation for US state", "LA", "ORLEANS", "NEW ORLEANS", "70112", 0.1, 0.05, 0.0, 0.0
include_examples "valid tax calculation for US state", "MA", "SUFFOLK", "BOSTON", "02108", 0.0, 0.0, 0.0, 0.0
include_examples "valid tax calculation for US state", "MD", "BALTIMORE CITY", "BALTIMORE", "21201", 0.0, 0.0, 0.0, 0.0
include_examples "valid tax calculation for US state", "MN", "HENNEPIN", "MINNEAPOLIS", "55401", 0.09025, 0.06875, 0.0015, 0.005
include_examples "valid tax calculation for US state", "NE", "DOUGLAS", "OMAHA", "68102", 0.07, 0.055, 0.0, 0.015
include_examples "valid tax calculation for US state", "NY", "NEW YORK", "NEW YORK", "10001", 0.0, 0.0, 0.0, 0.0
include_examples "valid tax calculation for US state", "RI", "PROVIDENCE", "PROVIDENCE", "02903", 0.07, 0.07, 0.0, 0.0
include_examples "valid tax calculation for US state", "SD", "MINNEHAHA", "SIOUX FALLS", "57101", 0.062, 0.042, 0.0, 0.02
include_examples "valid tax calculation for US state", "TN", "DAVIDSON", "NASHVILLE-DAVIDSON METROPOLITAN GOVERNMENT (BALANCE)", "37201", 0.1, 0.07, 0.025, 0.0
include_examples "valid tax calculation for US state", "TX", "TRAVIS", "AUSTIN", "78701", 0.0825, 0.0625, 0.00, 0.01
include_examples "valid tax calculation for US state", "UT", "SALT LAKE", "SALT LAKE CITY", "84101", 0.0825, 0.0485, 0.024, 0.01
include_examples "valid tax calculation for US state", "VT", "CHITTENDEN", "BURLINGTON", "05401", 0.07, 0.06, 0.0, 0.01
it "performs a valid tax calculation for Ontario Canada purchases" do
expected_tax_amount = 13
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: expected_tax_amount,
zip_tax_rate: nil,
used_taxjar: true,
taxjar_info: {
combined_tax_rate: 0.13,
state_tax_rate: nil,
county_tax_rate: nil,
city_tax_rate: nil,
gst_tax_rate: 0.05,
pst_tax_rate: 0.08,
qst_tax_rate: 0.0,
jurisdiction_state: "ON",
jurisdiction_county: nil,
jurisdiction_city: nil,
})
actual_sales_tax = SalesTaxCalculator.new(product: create(:product, user: @seller),
price_cents: 100,
buyer_location: { country: "CA", state: "ON" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
it "does not assess Canada Tax when a valid QST ID is provided on a sale into Quebec" do
expected_sales_tax = SalesTaxCalculation.zero_business_vat(100)
actual_sales_tax = SalesTaxCalculator.new(product: create(:product, user: @seller),
price_cents: 100,
buyer_location: { country: "CA", state: QUEBEC },
from_discover: true,
buyer_vat_id: "1002092821TQ0001").calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
describe "AU GST" do
it "assesses GST in Australia" do
product = create(:product, user: @seller)
expected_tax_rate = create(:zip_tax_rate, country: "AU", state: nil, zip_code: nil, combined_rate: 0.10, is_seller_responsible: false)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 10,
zip_tax_rate: expected_tax_rate)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "AU" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
it "assesses GST for direct to customer sales in Australia" do
product = create(:physical_product, user: @seller)
expected_tax_rate = create(:zip_tax_rate, country: "AU", state: nil, zip_code: nil, combined_rate: 0.10, is_seller_responsible: false)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 10,
zip_tax_rate: expected_tax_rate)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "AU" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
describe "Singapore GST" do
before do
@tax_rate_2023 = create(:zip_tax_rate, country: "SG", state: nil, zip_code: nil, combined_rate: 0.08, is_seller_responsible: false, applicable_years: [2023])
@tax_rate_2024 = create(:zip_tax_rate, country: "SG", state: nil, zip_code: nil, combined_rate: 0.09, is_seller_responsible: false, applicable_years: [2024])
end
it "assesses GST in Singapore in 2023" do
travel_to(Time.find_zone("UTC").local(2023, 4, 1)) do
product = create(:product, user: @seller)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 8,
zip_tax_rate: @tax_rate_2023)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "SG" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
it "assesses GST in Singapore in 2024" do
travel_to(Time.find_zone("UTC").local(2024, 4, 1)) do
product = create(:product, user: @seller)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 9,
zip_tax_rate: @tax_rate_2024)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "SG" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
it "assesses GST in Singapore after 2024 even if we did not add a tax rate for that year" do
travel_to(Time.find_zone("UTC").local(2025, 4, 1)) do
product = create(:product, user: @seller)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 9,
zip_tax_rate: @tax_rate_2024)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "SG" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
it "assesses GST for direct to customer sales in Singapore" do
product = create(:physical_product, user: @seller)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 9,
zip_tax_rate: @tax_rate_2024)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "SG" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
describe "Norway VAT" do
it "assesses VAT in Norway" do
product = create(:product, user: @seller)
expected_tax_rate = create(:zip_tax_rate, country: "NO", state: nil, zip_code: nil, combined_rate: 0.25, is_seller_responsible: false)
create(:zip_tax_rate, country: "NO", state: nil, zip_code: nil, combined_rate: 0.00, is_seller_responsible: false, is_epublication_rate: true)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 25,
zip_tax_rate: expected_tax_rate)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "NO" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
it "uses the epublication VAT rate for ebpublication products in Norway" do
product = create(:product, user: @seller, is_epublication: true)
create(:zip_tax_rate, country: "NO", state: nil, zip_code: nil, combined_rate: 0.25, is_seller_responsible: false, is_epublication_rate: false)
expected_tax_rate = create(:zip_tax_rate, country: "NO", state: nil, zip_code: nil, combined_rate: 0.00, is_seller_responsible: false, is_epublication_rate: true)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 0,
zip_tax_rate: expected_tax_rate)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "NO" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
describe "Iceland VAT" do
let!(:standard_tax_rate) { create(:zip_tax_rate, country: "IS", state: nil, zip_code: nil, combined_rate: 0.24, is_seller_responsible: false) }
let!(:epublication_tax_rate) { create(:zip_tax_rate, country: "IS", state: nil, zip_code: nil, combined_rate: 0.11, is_seller_responsible: false, is_epublication_rate: true) }
context "when collect_tax_is feature flag is off" do
it "does not assess VAT in Iceland" do
product = create(:product, user: @seller)
expected_sales_tax = SalesTaxCalculation.zero_tax(100)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "IS" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
it "does not assess VAT for epublication products in Iceland" do
product = create(:product, user: @seller, is_epublication: true)
expected_sales_tax = SalesTaxCalculation.zero_tax(100)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "IS" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
context "when collect_tax_is feature flag is on" do
before do
Feature.activate(:collect_tax_is)
end
it "assesses VAT in Iceland" do
product = create(:product, user: @seller)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 24,
zip_tax_rate: standard_tax_rate)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "IS" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
it "uses the epublication VAT rate for epublication products in Iceland" do
product = create(:product, user: @seller, is_epublication: true)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 11,
zip_tax_rate: epublication_tax_rate)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "IS" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
end
describe "Japan CT" do
let!(:standard_tax_rate) { create(:zip_tax_rate, country: "JP", state: nil, zip_code: nil, combined_rate: 0.10, is_seller_responsible: false) }
context "when collect_tax_jp feature flag is off" do
it "does not assess CT in Japan" do
product = create(:product, user: @seller)
expected_sales_tax = SalesTaxCalculation.zero_tax(100)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "JP" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
context "when collect_tax_jp feature flag is on" do
before do
Feature.activate(:collect_tax_jp)
end
it "assesses CT in Japan" do
product = create(:product, user: @seller)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 10,
zip_tax_rate: standard_tax_rate)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "JP" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
end
describe "New Zealand GST" do
let!(:standard_tax_rate) { create(:zip_tax_rate, country: "NZ", state: nil, zip_code: nil, combined_rate: 0.15, is_seller_responsible: false) }
context "when collect_tax_nz feature flag is off" do
it "does not assess GST in New Zealand" do
product = create(:product, user: @seller)
expected_sales_tax = SalesTaxCalculation.zero_tax(100)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "NZ" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
context "when collect_tax_nz feature flag is on" do
before do
Feature.activate(:collect_tax_nz)
end
it "assesses GST in New Zealand" do
product = create(:product, user: @seller)
expected_sales_tax = SalesTaxCalculation.new(price_cents: 100,
tax_cents: 15,
zip_tax_rate: standard_tax_rate)
actual_sales_tax = SalesTaxCalculator.new(product:,
price_cents: 100,
buyer_location: { country: "NZ" }).calculate
compare_calculations(expected: expected_sales_tax, actual: actual_sales_tax)
end
end
end
describe "South Africa VAT" do
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/sales_tax/taxjar/taxjar_api_spec.rb | spec/business/sales_tax/taxjar/taxjar_api_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe TaxjarApi, :vcr do
let(:origin) do
{
country: "US",
state: "CA",
zip: "94104"
}
end
let(:destination) do
{
country: "US",
state: "CA",
zip: "94107"
}
end
let(:nexus_address) do
{
country: "US",
state: "CA"
}
end
let(:expected_calculation) do
{
"order_total_amount" => 120.0,
"shipping" => 20.0,
"taxable_amount" => 100.0,
"amount_to_collect" => 8.63,
"rate" => 0.08625,
"has_nexus" => true,
"freight_taxable" => false,
"tax_source" => "destination",
"jurisdictions" => {
"country" => "US",
"state" => "CA",
"county" => "SAN FRANCISCO",
"city" => "SAN FRANCISCO"
},
"breakdown" => {
"taxable_amount" => 100.0,
"tax_collectable" => 8.63,
"combined_tax_rate" => 0.08625,
"state_taxable_amount" => 100.0,
"state_tax_rate" => 0.0625,
"state_tax_collectable" => 6.25,
"county_taxable_amount" => 100.0,
"county_tax_rate" => 0.01,
"county_tax_collectable" => 1.0,
"city_taxable_amount" => 0.0,
"city_tax_rate" => 0.0,
"city_tax_collectable" => 0.0,
"special_district_taxable_amount" => 100.0,
"special_tax_rate" => 0.01375,
"special_district_tax_collectable" => 1.38,
"line_items" => [
{
"id" => "1",
"taxable_amount" => 100.0,
"tax_collectable" => 8.63,
"combined_tax_rate" => 0.08625,
"state_taxable_amount" => 100.0,
"state_sales_tax_rate" => 0.0625,
"state_amount" => 6.25,
"county_taxable_amount" => 100.0,
"county_tax_rate" => 0.01,
"county_amount" => 1.0,
"city_taxable_amount" => 0.0,
"city_tax_rate" => 0.0,
"city_amount" => 0.0,
"special_district_taxable_amount" => 100.0,
"special_tax_rate" => 0.01375,
"special_district_amount" => 1.38
}
]
}
}
end
let(:expected_calculation_digital_product) do
{
"order_total_amount" => 120.0,
"shipping" => 20.0,
"taxable_amount" => 0.0,
"amount_to_collect" => 0.0,
"rate" => 0.0,
"has_nexus" => true,
"freight_taxable" => false,
"tax_source" => "destination",
"jurisdictions" => {
"country" => "US",
"state" => "CA",
"county" => "SAN FRANCISCO",
"city" => "SAN FRANCISCO"
},
"breakdown" => {
"taxable_amount" => 0.0,
"tax_collectable" => 0.0,
"combined_tax_rate" => 0.0,
"state_taxable_amount" => 0.0,
"state_tax_rate" => 0.0,
"state_tax_collectable" => 0.0,
"county_taxable_amount" => 0.0,
"county_tax_rate" => 0.0,
"county_tax_collectable" => 0.0,
"city_taxable_amount" => 0.0,
"city_tax_rate" => 0.0,
"city_tax_collectable" => 0.0,
"special_district_taxable_amount" => 0.0,
"special_tax_rate" => 0.0,
"special_district_tax_collectable" => 0.0,
"line_items" => [
{
"id" => "1",
"taxable_amount" => 0.0,
"tax_collectable" => 0.0,
"combined_tax_rate" => 0.0,
"state_taxable_amount" => 0.0,
"state_sales_tax_rate" => 0.0,
"state_amount" => 0.0,
"county_taxable_amount" => 0.0,
"county_tax_rate" => 0.0,
"county_amount" => 0.0,
"city_taxable_amount" => 0.0,
"city_tax_rate" => 0.0,
"city_amount" => 0.0,
"special_district_taxable_amount" => 0.0,
"special_tax_rate" => 0.0,
"special_district_amount" => 0.0
}
]
}
}
end
let(:expected_calculation_quantity_three) do
{
"order_total_amount" => 320.0,
"shipping" => 20.0,
"taxable_amount" => 300.0,
"amount_to_collect" => 25.88,
"rate" => 0.08625,
"has_nexus" => true,
"freight_taxable" => false,
"tax_source" => "destination",
"jurisdictions" => {
"country" => "US",
"state" => "CA",
"county" => "SAN FRANCISCO",
"city" => "SAN FRANCISCO"
},
"breakdown" => {
"taxable_amount" => 300.0,
"tax_collectable" => 25.88,
"combined_tax_rate" => 0.08625,
"state_taxable_amount" => 300.0,
"state_tax_rate" => 0.0625,
"state_tax_collectable" => 18.75,
"county_taxable_amount" => 300.0,
"county_tax_rate" => 0.01,
"county_tax_collectable" => 3.0,
"city_taxable_amount" => 0.0,
"city_tax_rate" => 0.0,
"city_tax_collectable" => 0.0,
"special_district_taxable_amount" => 300.0,
"special_tax_rate" => 0.01375,
"special_district_tax_collectable" => 4.13,
"line_items" => [
{
"id" => "1",
"taxable_amount" => 300.0,
"tax_collectable" => 25.88,
"combined_tax_rate" => 0.08625,
"state_taxable_amount" => 300.0,
"state_sales_tax_rate" => 0.0625,
"state_amount" => 18.75,
"county_taxable_amount" => 300.0,
"county_tax_rate" => 0.01,
"county_amount" => 3.0,
"city_taxable_amount" => 0.0,
"city_tax_rate" => 0.0,
"city_amount" => 0.0,
"special_district_taxable_amount" => 300.0,
"special_tax_rate" => 0.01375,
"special_district_amount" => 4.13
}
]
}
}
end
let(:expected_create_order_transaction_response) do
{
"transaction_id" => "G_-mnBf9b1j9A7a4ub4nFQ==",
"user_id" => 126159,
"provider" => "api",
"transaction_date" => "2023-08-28T20:06:20.000Z",
"transaction_reference_id" => nil,
"customer_id" => nil,
"exemption_type" => nil,
"from_country" => "US",
"from_zip" => "94104",
"from_state" => "CA",
"from_city" => nil,
"from_street" => nil,
"to_country" => "US",
"to_zip" => "19106",
"to_state" => "PA",
"to_city" => nil,
"to_street" => nil,
"amount" => "15.0",
"shipping" => "5.0",
"sales_tax" => "1.0",
"line_items" =>
[
{
"id" => 0,
"quantity" => 1,
"product_identifier" => nil,
"product_tax_code" => "31000",
"description" => nil,
"unit_price" => "10.0",
"discount" => "0.0",
"sales_tax" => "1.0"
}
]
}
end
describe "#calculate_tax_for_order" do
it "calculates the tax" do
expect(described_class.new.calculate_tax_for_order(origin:,
destination:,
nexus_address:,
quantity: 1,
product_tax_code: nil,
unit_price_dollars: 100.0,
shipping_dollars: 20.0)).to eq(expected_calculation)
end
it "calculates the tax for quantity greater than 1" do
expect(described_class.new.calculate_tax_for_order(origin:,
destination:,
nexus_address:,
quantity: 3,
product_tax_code: nil,
unit_price_dollars: 100.0,
shipping_dollars: 20.0)).to eq(expected_calculation_quantity_three)
end
it "calculates the tax for product tax code 31000" do
expect(described_class.new.calculate_tax_for_order(origin:,
destination:,
nexus_address:,
quantity: 1,
product_tax_code: "31000",
unit_price_dollars: 100.0,
shipping_dollars: 20.0)).to eq(expected_calculation_digital_product)
end
it "caches the response and returns a cache hit on the next request" do
expect(described_class.new.calculate_tax_for_order(origin:,
destination:,
nexus_address:,
quantity: 1,
product_tax_code: nil,
unit_price_dollars: 100.0,
shipping_dollars: 20.0)).to eq(expected_calculation)
expect_any_instance_of(Taxjar::Client).to_not receive(:tax_for_order)
expect(described_class.new.calculate_tax_for_order(origin:,
destination:,
nexus_address:,
quantity: 1,
product_tax_code: nil,
unit_price_dollars: 100.0,
shipping_dollars: 20.0)).to eq(expected_calculation)
end
it "notifies Bugsnag and propagates a TaxJar client error" do
expect_any_instance_of(Taxjar::Client).to receive(:tax_for_order).and_raise(Taxjar::Error::BadRequest)
expect(Bugsnag).to receive(:notify).exactly(:once)
expect do
described_class.new.calculate_tax_for_order(origin:,
destination: destination.except(:zip),
nexus_address:,
quantity: 1,
product_tax_code: nil,
unit_price_dollars: 100.0,
shipping_dollars: 20.0)
end.to raise_error(Taxjar::Error::BadRequest)
end
it "propagates a TaxJar server error" do
allow_any_instance_of(Taxjar::Client).to receive(:tax_for_order).and_raise(Taxjar::Error::InternalServerError)
expect do
described_class.new.calculate_tax_for_order(origin:,
destination:,
nexus_address:,
quantity: 1,
product_tax_code: nil,
unit_price_dollars: 100.0,
shipping_dollars: 20.0)
end.to raise_error(Taxjar::Error::InternalServerError)
end
end
describe "#create_order_transaction" do
it "creates an order transaction in TaxJar" do
expect(described_class.new.create_order_transaction(transaction_id: "G_-mnBf9b1j9A7a4ub4nFQ==",
transaction_date: "2023-08-28T20:06:20Z",
destination: { country: "US", state: "PA", zip: "19106" },
quantity: 1,
product_tax_code: "31000",
amount_dollars: 15.0,
shipping_dollars: 5.0,
sales_tax_dollars: 1.0,
unit_price_dollars: 10.0)).to eq(expected_create_order_transaction_response)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/card_data_handling/card_data_handling_mode_spec.rb | spec/business/card_data_handling/card_data_handling_mode_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CardDataHandlingMode do
it "has the correct value for modes" do
expect(CardDataHandlingMode::TOKENIZE_VIA_STRIPEJS).to eq "stripejs.0"
end
it "has the correct valid modes" do
expect(CardDataHandlingMode::VALID_MODES).to include("stripejs.0")
end
it "maps each card data handling modeo to the correct charge processor" do
expect(CardDataHandlingMode::VALID_MODES).to include("stripejs.0" => StripeChargeProcessor.charge_processor_id)
end
describe ".is_valid" do
context "with valid modes" do
context "stripejs.0" do
let(:mode) { "stripejs.0" }
it "returns true" do
expect(CardDataHandlingMode.is_valid(mode)).to eq(true)
end
end
end
context "with a invalid modes" do
context "clearly invalid mode" do
let(:mode) { "jedi-mode" }
it "returns false" do
expect(CardDataHandlingMode.is_valid(mode)).to eq(false)
end
end
context "mix valid and invalid modes" do
let(:mode) { "stripejs.0,jedi-mode" }
it "returns false" do
expect(CardDataHandlingMode.is_valid(mode)).to eq(false)
end
end
end
end
describe ".get_card_data_handling_mode" do
it "returns stripejs" do
expect(CardDataHandlingMode.get_card_data_handling_mode(nil)).to eq "stripejs.0"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/business/card_data_handling/card_data_handling_error_spec.rb | spec/business/card_data_handling/card_data_handling_error_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CardDataHandlingError do
describe "with message" do
let(:subject) { CardDataHandlingError.new("the-error-message") }
it "message should be accessible" do
expect(subject.error_message).to eq "the-error-message"
end
it "card error code should be nil" do
expect(subject.card_error_code).to be(nil)
end
it "is not a card error" do
expect(subject.is_card_error?).to be(false)
end
end
describe "with message and card data code" do
let(:subject) { CardDataHandlingError.new("the-error-message", "card-error-code") }
it "message should be accessible" do
expect(subject.error_message).to eq "the-error-message"
end
it "card error code should be accessible" do
expect(subject.card_error_code).to eq "card-error-code"
end
it "is a card error" do
expect(subject.is_card_error?).to be(true)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/discover_domain_constraint_spec.rb | spec/lib/discover_domain_constraint_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DiscoverDomainConstraint do
describe ".matches?" do
before do
@discover_domain_request = double("request")
allow(@discover_domain_request).to receive(:host).and_return("discover.gumroad.com")
@non_discover_domain_request = double("request")
allow(@non_discover_domain_request).to receive(:host).and_return("gumroad.com")
stub_const("VALID_DISCOVER_REQUEST_HOST", "discover.gumroad.com")
end
context "when requests come from valid discover domain" do
it "returns true" do
expect(described_class.matches?(@discover_domain_request)).to eq(true)
end
end
context "when requests come from non-discover domain" do
it "returns false" do
expect(described_class.matches?(@non_discover_domain_request)).to eq(false)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/user_custom_domain_constraint_spec.rb | spec/lib/user_custom_domain_constraint_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UserCustomDomainConstraint do
describe ".matches?" do
context "when request doesn't come from subdomain or custom domain" do
before do
@gumroad_domain_request = double("request")
allow(@gumroad_domain_request).to receive(:host).and_return("gumroad.com")
allow(@gumroad_domain_request).to receive(:fullpath).and_return("/")
end
it "returns false" do
expect(described_class.matches?(@gumroad_domain_request)).to eq(false)
end
end
context "when request comes from subdomain" do
before do
@subdomain_request = double("request")
allow(@subdomain_request).to receive(:host).and_return("sample.gumroad.com")
allow(@subdomain_request).to receive(:subdomains).and_return(["sample"])
stub_const("ROOT_DOMAIN", "gumroad.com")
create(:user, username: "sample")
end
it "returns true" do
expect(described_class.matches?(@subdomain_request)).to eq(true)
end
end
context "when request comes from custom domain" do
before do
@custom_domain_request = double("request")
allow(@custom_domain_request).to receive(:host).and_return("example.com")
create(:custom_domain, domain: "example.com", user: create(:user, username: "sample"))
end
it "returns true" do
expect(described_class.matches?(@custom_domain_request)).to eq(true)
end
end
context "when request comes from a host that's configured to redirect" do
before do
allow_any_instance_of(SubdomainRedirectorService).to receive(:redirects).and_return({ "live.gumroad.com" => "https://example.com" })
@custom_domain_request = double("request")
allow(@custom_domain_request).to receive(:host).and_return("live.gumroad.com")
allow(@custom_domain_request).to receive(:fullpath).and_return("/")
end
it "returns true" do
expect(described_class.matches?(@custom_domain_request)).to eq(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/lib/gumroad_domain_constraint_spec.rb | spec/lib/gumroad_domain_constraint_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GumroadDomainConstraint do
describe ".matches?" do
before do
@gumroad_domain_request = double("request")
allow(@gumroad_domain_request).to receive(:host).and_return("gumroad.com")
@non_gumroad_domain_request = double("request")
allow(@non_gumroad_domain_request).to receive(:host).and_return("api.gumroad.com")
stub_const("VALID_REQUEST_HOSTS", ["gumroad.com"])
end
context "when requests come from Gumroad root domain" do
it "returns true" do
expect(described_class.matches?(@gumroad_domain_request)).to eq(true)
end
end
context "when requests come from non-Gumroad root domain" do
it "returns false" do
expect(described_class.matches?(@non_gumroad_domain_request)).to eq(false)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/product_custom_domain_constraint_spec.rb | spec/lib/product_custom_domain_constraint_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ProductCustomDomainConstraint do
describe ".matches?" do
context "when request host is a user custom domain" do
before do
@custom_domain_request = double("request")
allow(@custom_domain_request).to receive(:host).and_return("example.com")
create(:custom_domain, domain: "example.com")
end
it "returns false" do
expect(described_class.matches?(@custom_domain_request)).to eq(false)
end
end
context "when request host is a product custom domain" do
before do
@custom_domain_request = double("request")
allow(@custom_domain_request).to receive(:host).and_return("example.com")
create(:custom_domain, :with_product, domain: "example.com")
end
it "returns true" do
expect(described_class.matches?(@custom_domain_request)).to eq(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/lib/api_domain_constraint_spec.rb | spec/lib/api_domain_constraint_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ApiDomainConstraint do
describe ".matches?" do
before do
@api_domain_request = double("request")
allow(@api_domain_request).to receive(:host).and_return("api.gumroad.com")
@non_api_domain_request = double("request")
allow(@non_api_domain_request).to receive(:host).and_return("gumroad.com")
end
context "when in development environment" do
before do
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("development"))
end
it "returns true" do
expect(described_class.matches?(@api_domain_request)).to eq(true)
expect(described_class.matches?(@non_api_domain_request)).to eq(true)
end
end
context "when in non-development environments" do
before do
stub_const("VALID_API_REQUEST_HOSTS", ["api.gumroad.com"])
end
context "when requests come from valid API domain" do
it "returns true" do
expect(described_class.matches?(@api_domain_request)).to eq(true)
end
end
context "when requests come from non-API domain" do
it "returns false" do
expect(described_class.matches?(@non_api_domain_request)).to eq(false)
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/lib/js_error_reporter_spec.rb | spec/lib/js_error_reporter_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe JSErrorReporter do
before(:all) do
options = Selenium::WebDriver::Chrome::Options.new.tap do |opts|
opts.add_argument("--headless=new")
opts.add_argument("--disable-gpu")
opts.add_argument("--no-sandbox")
opts.add_argument("--disable-dev-shm-usage")
opts.add_argument("--user-data-dir=/tmp/chrome")
opts.add_option("goog:loggingPrefs", { driver: "DEBUG" })
end
@driver = Selenium::WebDriver.for(:chrome, options: options)
@html_tempfiles = []
end
after(:each) do
@html_tempfiles.shift.close(true) while @html_tempfiles.size > 0
end
around do |example|
JSErrorReporter.enabled = true
example.run
ensure
JSErrorReporter.enabled = nil
end
def create_html_file(content)
tempfile = Tempfile.new(["", ".html"])
tempfile.write(content)
tempfile.rewind
@html_tempfiles << tempfile
"file://#{tempfile.path}"
end
it "reports raised Error exceptions with stack trace" do
url = create_html_file %{
<script>
function add(a, b) {
throw new Error("Cannot add")
}
add(1, 2)
</script>
}
@driver.navigate.to url
errors = JSErrorReporter.instance.read_errors! @driver
expect(errors.size).to eq 1
line, first_trace = errors[0].split("\n")
expect(line).to eq "Error: Cannot add"
expect(first_trace).to eq "\tadd (#{url}:3:16)"
end
it "reports raised primitive value exceptions with stack trace" do
url = create_html_file %{
<script>
function add(a, b) {
throw "Cannot add"
}
add(1, 2)
</script>
}
@driver.navigate.to url
errors = JSErrorReporter.instance.read_errors! @driver
expect(errors.size).to eq 1
line, first_trace = errors[0].split("\n")
expect(line).to eq "Error: Cannot add"
expect(first_trace).to eq "\tadd (#{url}:3:10)"
end
it "reports console.error entries, including with multiple or complex arguments, with stack trace" do
url = create_html_file %{
<script>
console.error("Test error log", 42, [null, false], { x: 1 }, { test: ["a", "b", "c"] });
</script>
}
@driver.navigate.to url
errors = JSErrorReporter.instance.read_errors! @driver
expect(errors.size).to eq 1
line, first_trace = errors[0].split("\n")
# FIXME nested objects - can't format properly because Chrome WebDriver log data does not include properties for this level of nesting
expect(line).to eq %{Console error: Test error log, 42, [null,false], {"x":1}, {"test":"Array(3)"}}
expect(first_trace).to eq "\t (#{url}:2:16)"
end
# TODO see above
pending "it formats nested objects in console.error properly"
it "does not report console.log and console.warn entries" do
url = create_html_file %{
<script>
console.log("Test info log")
console.warn("Test warn log")
</script>
}
@driver.navigate.to url
errors = JSErrorReporter.instance.read_errors! @driver
expect(errors.size).to eq 0
end
it "reports combinations of these properly" do
url = create_html_file %{
<script>
console.log("Test info log")
console.error("Sample error info")
function add(a, b) {
console.warn("Warning")
throw new Error("Cannot add")
}
add(1, 2)
</script>
}
@driver.navigate.to url
errors = JSErrorReporter.instance.read_errors! @driver
expect(errors.size).to eq 2
line, first_trace = errors[0].split("\n")
expect(line).to eq "Console error: Sample error info"
expect(first_trace).to eq "\t (#{url}:4:16)"
line, first_trace = errors[1].split("\n")
expect(line).to eq "Error: Cannot add"
expect(first_trace).to eq "\tadd (#{url}:8:16)"
end
# TODO
pending "it presents source-mapped stack traces instead of raw ones"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/errors/gumroad_runtime_error_spec.rb | spec/lib/errors/gumroad_runtime_error_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GumroadRuntimeError do
describe "without message or original error" do
before do
raise GumroadRuntimeError
rescue GumroadRuntimeError => error
@error = error
end
it "has the default message" do
expect(@error.message).to eq "GumroadRuntimeError"
end
it "has its own backtrace" do
expect(@error.backtrace[0]).to include("gumroad_runtime_error_spec.rb")
end
end
describe "with message" do
before do
raise GumroadRuntimeError, "the-message"
rescue GumroadRuntimeError => error
@error = error
end
it "has the message" do
expect(@error.message).to eq "the-message"
end
end
describe "with original error" do
before do
begin
raise StandardError
rescue StandardError => original_error
raise GumroadRuntimeError.new(original_error:)
end
rescue GumroadRuntimeError => error
@error = error
end
it "has the message of the original error" do
expect(@error.message).to eq "StandardError"
end
end
describe "with original error that has a message" do
before do
begin
raise StandardError, "standard error message"
rescue StandardError => original_error
raise GumroadRuntimeError.new(original_error:)
end
rescue GumroadRuntimeError => error
@error = error
end
it "has the message of the original error" do
expect(@error.message).to eq "standard error message"
end
end
describe "with message and original error" do
before do
begin
raise StandardError
rescue StandardError => original_error
raise GumroadRuntimeError.new("the-error-message", original_error:)
end
rescue GumroadRuntimeError => error
@error = error
end
it "has the message of the original error" do
expect(@error.message).to eq "the-error-message"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/d3_spec.rb | spec/lib/utilities/d3_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe D3 do
describe ".formatted_date" do
it "returns 'Today' if date is today" do
expect(described_class.formatted_date(Date.today)).to eq("Today")
expect(described_class.formatted_date(Date.yesterday)).not_to eq("Today")
expect(described_class.formatted_date(Date.new(2020, 1, 2), today_date: Date.new(2020, 1, 2))).to eq("Today")
end
it "returns date formatted" do
expect(described_class.formatted_date(Date.new(2020, 5, 4))).to eq("May 4, 2020")
expect(described_class.formatted_date(Date.new(2020, 12, 13))).to eq("Dec 13, 2020")
end
end
describe ".formatted_date_with_timezone" do
it "returns 'Today' if date is today" do
expect(described_class.formatted_date_with_timezone(Date.today, Time.current.zone)).to eq("Today")
expect(described_class.formatted_date_with_timezone(Date.yesterday, Time.current.zone)).not_to eq("Today")
end
it "returns date formatted" do
expect(described_class.formatted_date_with_timezone(Time.utc(2020, 5, 4), "UTC")).to eq("May 4, 2020")
expect(described_class.formatted_date_with_timezone(Time.utc(2020, 5, 4), "America/Los_Angeles")).to eq("May 3, 2020")
end
end
describe "#date_domain" do
it "returns date strings in 'Sunday, April 20th' format for given dates" do
dates = Date.parse("2013-03-01")..Date.parse("2013-03-02")
expect(D3.date_domain(dates)).to eq ["Friday, March 1st", "Saturday, March 2nd"]
end
end
describe "#date_month_domain" do
it "returns proper months for given dates in two different years" do
dates = Date.parse("2018-12-31")..Date.parse("2019-01-01")
expect(D3.date_month_domain(dates)).to eq [{ date: "Monday, December 31st", month: "December 2018", month_index: 0 }, { date: "Tuesday, January 1st", month: "January 2019", month_index: 1 }]
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/with_max_execution_time_spec.rb | spec/lib/utilities/with_max_execution_time_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe WithMaxExecutionTime do
describe ".timeout_queries" do
it "raises Timeout error if query took longer than allowed" do
# Note: MySQL max_execution_time ignores SLEEP(), so we have to manufacture a real slow query.
create(:user)
slow_query = "select * from users " + 50.times.map { |i| "join users u#{i}" }.join(" ")
expect do
described_class.timeout_queries(seconds: 0.001) do
ActiveRecord::Base.connection.execute(slow_query)
end
end.to raise_error(described_class::QueryTimeoutError)
end
it "returns block value if no error occurred" do
returned_value = described_class.timeout_queries(seconds: 5) do
ActiveRecord::Base.connection.execute("select 1")
:foo
end
expect(returned_value).to eq(:foo)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/credit_card_utility_spec.rb | spec/lib/utilities/credit_card_utility_spec.rb | # frozen_string_literal: true
describe "#extract_month_and_year" do
before do
@expiry_date = "05 / 15"
end
describe "valid expiry_date" do
it "extracts the month and year from a date" do
expiry_month, expiry_year = CreditCardUtility.extract_month_and_year(@expiry_date)
expect(expiry_month).to eq "05"
expect(expiry_year).to eq "15"
end
end
describe "invalid expiry date" do
before do
@expiry_date = "05 /"
end
it "returns nil" do
expect(CreditCardUtility.extract_month_and_year(@expiry_date)).to eq [nil, nil]
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/referrer_spec.rb | spec/lib/utilities/referrer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Referrer do
describe ".extract_domain" do
it "extracts domain from url" do
expect(Referrer.extract_domain("http://twitter.com/ads")).to eq "twitter.com"
end
it "returns direct if url is invalid" do
allow(URI).to receive(:parse).and_raise(URI::InvalidURIError)
expect(Referrer.extract_domain("invalid")).to eq "direct"
end
it "returns direct if url is nil" do
expect(Referrer.extract_domain(nil)).to eq "direct"
end
it "returns direct if url is direct" do
expect(Referrer.extract_domain("direct")).to eq "direct"
end
it "returns direct if parsed host is blank" do
# URI.parse('file:///').host == ""
expect(Referrer.extract_domain("file:///C:/Users/FARHAN/Downloads/New%20folder/ok.html")).to eq "direct"
end
it "still works even with url escaped urls" do
expect(Referrer.extract_domain(CGI.escape("http://graceburrowes.com/"))).to eq "graceburrowes.com"
end
it "still works even with japanese characters that may cause UTF-8 errors" do
expect(Referrer.extract_domain("http://www2.mensnet.jp/navi/ps_search.cgi?word=%8B%D8%93%F7&cond=0&metasearch=&line=&indi=&act=search"))
.to eq "www2.mensnet.jp"
end
it "still works even with exotic unicode characters" do
expect(Referrer.extract_domain("http://google.com/search?query=☃")).to eq "google.com"
end
it "still works even with exotic unicode characters and if the url is escaped" do
expect(Referrer.extract_domain(CGI.escape("http://google.com/search?query=☃"))).to eq "google.com"
end
it "catches Encoding::CompatibilityError when applicable" do
str = "http://動画素材怎么解决的!`.com/blog/%E3%83%95%E3%83%AA%E3%83%BC%E5%8B%95%E7%94%BB%E7%B4%A0%E6%9D%90%E8%BF%BD%E5%8A%A0%EF%"
str += "BC%88%E5%8B%95%E7%94%BB%E7%B4%A0%E6%9D%90-com%EF%BC%89%EF%BC%86-4k2k%E5%8B%95%E7%94%BB%E7%B4%A0%E6%9D%90%E3%82%92/"
expect(Referrer.extract_domain(str.force_encoding("ASCII-8BIT"))).to eq "direct"
end
it "handles whitespace properly" do
url = "http://www.bing.com/search?q=shady%20record"
expect(Referrer.extract_domain(url)).to eq("bing.com")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/global_config_spec.rb | spec/lib/utilities/global_config_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe GlobalConfig do
describe ".get" do
context "when the environment variable is set" do
it "returns the value of the environment variable" do
allow(ENV).to receive(:fetch).with("TEST_VAR", anything).and_return("test_value")
expect(described_class.get("TEST_VAR")).to eq("test_value")
end
end
context "when the environment variable is not set" do
it "returns the default value if provided" do
allow(ENV).to receive(:fetch).with("MISSING_VAR", anything).and_return("default")
expect(described_class.get("MISSING_VAR", "default")).to eq("default")
end
it "returns nil if no default is provided and no credentials match" do
allow(ENV).to receive(:fetch).with("MISSING_VAR", nil).and_return(nil)
expect(described_class.get("MISSING_VAR")).to be_nil
end
it "falls back to Rails credentials" do
allow(ENV).to receive(:fetch).with("CREDENTIAL_KEY", anything) do |name, fallback|
fallback
end
# Mock the private method that accesses Rails credentials
allow(described_class).to receive(:fetch_from_credentials).with("CREDENTIAL_KEY").and_return("credential_value")
expect(described_class.get("CREDENTIAL_KEY")).to eq("credential_value")
end
it "falls back to Rails credentials for multi-level keys with __ separator" do
allow(ENV).to receive(:fetch).with("HELLO_WORLD__FOO_BAR", anything) do |name, fallback|
fallback
end
# Mock the private method that accesses Rails credentials
allow(described_class).to receive(:fetch_from_credentials).with("HELLO_WORLD__FOO_BAR").and_return("123")
expect(described_class.get("HELLO_WORLD__FOO_BAR")).to eq("123")
end
end
context "when the environment variable is empty or blank" do
it "returns nil if the environment variable is empty" do
allow(ENV).to receive(:fetch).with("EMPTY_VAR", anything).and_return("")
expect(described_class.get("EMPTY_VAR")).to be_nil
end
it "returns nil if the environment variable is blank" do
allow(ENV).to receive(:fetch).with("BLANK_VAR", anything).and_return(" ")
expect(described_class.get("BLANK_VAR")).to be_nil
end
it "doesn't check for blank values when default is provided" do
allow(ENV).to receive(:fetch).with("BLANK_VAR", anything).and_return("")
expect(described_class.get("BLANK_VAR", "default")).to eq("")
end
end
end
describe ".dig" do
context "when the nested environment variable is set" do
it "joins the parts with double underscores and returns the value" do
allow(ENV).to receive(:fetch).with("PART1__PART2__PART3", anything).and_return("nested_value")
expect(described_class.dig("part1", "part2", "part3")).to eq("nested_value")
end
it "converts all parts to uppercase" do
allow(ENV).to receive(:fetch).with("LOWERCASE__PARTS", anything).and_return("uppercase_result")
expect(described_class.dig("lowercase", "parts")).to eq("uppercase_result")
end
it "handles mixed case parts correctly" do
allow(ENV).to receive(:fetch).with("MIXED__CASE__PARTS", anything).and_return("result")
expect(described_class.dig("MiXeD", "cAsE", "PaRtS")).to eq("result")
end
it "works with a single part" do
allow(ENV).to receive(:fetch).with("SINGLE", anything).and_return("value")
expect(described_class.dig("single")).to eq("value")
end
end
context "when the nested environment variable is not set" do
it "returns the default value if provided" do
allow(ENV).to receive(:fetch).with("MISSING__NESTED__VAR", anything).and_return("default")
expect(described_class.dig("missing", "nested", "var", default: "default")).to eq("default")
end
it "returns nil if no default is provided and credentials return nil" do
allow(ENV).to receive(:fetch).with("MISSING__NESTED__VAR", nil).and_return(nil)
expect(described_class.dig("missing", "nested", "var")).to be_nil
end
it "falls back to Rails credentials for nested keys" do
allow(ENV).to receive(:fetch).with("PART1__PART2__PART3", anything) do |name, fallback|
fallback
end
# Mock the private method that accesses Rails credentials
allow(described_class).to receive(:fetch_from_credentials).with("PART1__PART2__PART3").and_return("credential_value")
expect(described_class.dig("part1", "part2", "part3")).to eq("credential_value")
end
end
context "when the nested environment variable is blank" do
it "returns nil" do
allow(ENV).to receive(:fetch).with("NESTED__BLANK__VAR", anything).and_return(" ")
expect(described_class.dig("nested", "blank", "var")).to be_nil
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/xml_helpers_spec.rb | spec/lib/utilities/xml_helpers_spec.rb | # frozen_string_literal: true
describe XmlHelpers do
describe "text_at_xpath" do
describe "simple xml" do
let(:xml_raw) { %(<?xml version="1.0" encoding="utf-8"?><root><element>the text</element></root>) }
let(:xml_document) { REXML::Document.new(xml_raw) }
it "gets the text of the element" do
expect(XmlHelpers.text_at_xpath(xml_document, "root/element")).to eq("the text")
end
it "returns nil when not found" do
expect(XmlHelpers.text_at_xpath(xml_document, "root/elements")).to be_nil
end
end
describe "xml with repeating elements" do
let(:xml_raw) { %(<?xml version="1.0" encoding="utf-8"?><root><element>a text block</element><element>the text</element></root>) }
let(:xml_document) { REXML::Document.new(xml_raw) }
it "gets the text of the element of the first" do
expect(XmlHelpers.text_at_xpath(xml_document, "root/element")).to eq("a text block")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/us_zip_codes_spec.rb | spec/lib/utilities/us_zip_codes_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UsZipCodes do
describe "#identify_state_code" do
it "returns the state for a zip code that exists" do
expect(UsZipCodes.identify_state_code("94104")).to eq("CA")
end
it "returns the state for a zip code with space in front" do
expect(UsZipCodes.identify_state_code(" 94104")).to eq("CA")
end
it "returns the state for a zip code with space in back" do
expect(UsZipCodes.identify_state_code("94104 ")).to eq("CA")
end
it "returns the state for a zip+4" do
expect(UsZipCodes.identify_state_code("94104-5401")).to eq("CA")
end
it "returns the state for a zip+4 with single space in between" do
expect(UsZipCodes.identify_state_code("94104 5401")).to eq("CA")
end
it "returns the state for a zip+4 with no character in between" do
expect(UsZipCodes.identify_state_code("941045401")).to eq("CA")
end
it "returns nil when zip code is less than 5 digits" do
expect(UsZipCodes.identify_state_code("9410")).to be_nil
end
it "returns nil when zip code contains non-digits" do
expect(UsZipCodes.identify_state_code("94l04")).to be_nil
end
it "returns nil when zip code is not a valid zip+4 structure" do
expect(UsZipCodes.identify_state_code("94104-540")).to be_nil
end
it "returns nil when zip code is nil" do
expect(UsZipCodes.identify_state_code(nil)).to be_nil
end
it "returns nil when zip code is empty" do
expect(UsZipCodes.identify_state_code("")).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/lib/utilities/compliance_spec.rb | spec/lib/utilities/compliance_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Compliance do
describe Countries do
describe ".mapping" do
it "returns a Hash of country codes to countries" do
expect(Compliance::Countries.mapping).to eq(mapping_expected)
end
end
describe ".find_by_name" do
it "returns the country for a country whose name is the same for `countries` gem and `iso_country_codes` gem" do
expect(Compliance::Countries.find_by_name("Mexico")).to eq(Compliance::Countries::MEX)
end
it "returns the country for a country whose name is different for `countries` gem and `iso_country_codes` gem" do
expect(Compliance::Countries.find_by_name("South Korea")).to eq(Compliance::Countries::KOR)
expect(Compliance::Countries.find_by_name("Korea, Republic of")).to eq(Compliance::Countries::KOR)
end
it "returns the country for a country whose name is different for `countries` gem and `maxmind/geoip2`" do
expect(Compliance::Countries.find_by_name("Micronesia, Federated States of")).to eq(Compliance::Countries::FSM)
expect(Compliance::Countries.find_by_name("Federated States of Micronesia")).to eq(Compliance::Countries::FSM)
end
it "returns nil for a nil country name" do
expect(Compliance::Countries.find_by_name(nil)).to be_nil
end
it "returns nil for an empty country name" do
expect(Compliance::Countries.find_by_name("")).to be_nil
end
end
describe ".historical_names" do
it "returns an empty array for a nil country name" do
expect(Compliance::Countries.historical_names(nil)).to eq([])
end
it "returns the common name and gumroad historical names" do
expected_historical_names = ["United States"]
expect(Compliance::Countries.historical_names("United States")).to eq(expected_historical_names)
end
it "returns the common name and gumroad historical names for a country whose name is different for `countries` gem and `iso_country_codes` gem" do
expected_historical_names = ["South Korea", "Korea, Republic of"]
expect(Compliance::Countries.historical_names("South Korea")).to eq(expected_historical_names)
expect(Compliance::Countries.historical_names("Korea, Republic of")).to eq(expected_historical_names)
end
it "returns the known names for a country whose name is different for `countries` gem and `maxmind/geoip2`" do
expected_historical_names = ["Micronesia, Federated States of", "Federated States of Micronesia"]
expect(Compliance::Countries.historical_names("Micronesia, Federated States of")).to eq(expected_historical_names)
expect(Compliance::Countries.historical_names("Federated States of Micronesia")).to eq(expected_historical_names)
end
end
describe ".blocked?" do
it "returns false for United States" do
expect(Compliance::Countries.blocked?("US")).to be false
end
it "returns true for Afghanistan" do
expect(Compliance::Countries.blocked?("AF")).to be true
end
it "returns true for Cuba" do
expect(Compliance::Countries.blocked?("CU")).to be true
end
it "returns true for Congo, the Democratic Republic of the" do
expect(Compliance::Countries.blocked?("CD")).to be true
end
it "returns true for Côte d'Ivoire" do
expect(Compliance::Countries.blocked?("CI")).to be true
end
it "returns true for Iraq" do
expect(Compliance::Countries.blocked?("IQ")).to be true
end
it "returns true for Iran" do
expect(Compliance::Countries.blocked?("IR")).to be true
end
it "returns true for Lebanon" do
expect(Compliance::Countries.blocked?("LB")).to be true
end
it "returns true for Liberia" do
expect(Compliance::Countries.blocked?("LR")).to be true
end
it "returns true for Libya" do
expect(Compliance::Countries.blocked?("LY")).to be true
end
it "returns true for Myanmar" do
expect(Compliance::Countries.blocked?("MM")).to be true
end
it "returns true for North Korea" do
expect(Compliance::Countries.blocked?("KP")).to be true
end
it "returns true for Somalia" do
expect(Compliance::Countries.blocked?("SO")).to be true
end
it "returns true for Sudan" do
expect(Compliance::Countries.blocked?("SD")).to be true
end
it "returns true for Syrian Arab Republic" do
expect(Compliance::Countries.blocked?("SY")).to be true
end
it "returns true for Yemen" do
expect(Compliance::Countries.blocked?("YE")).to be true
end
it "returns true for Zimbabwe" do
expect(Compliance::Countries.blocked?("ZW")).to be true
end
end
describe ".for_select" do
it "returns a sorted array of country names and codes" do
expect(Compliance::Countries.for_select).to eq(for_select_expected)
end
end
describe ".country_with_flag_by_name" do
context "for a valid country name" do
it "returns a country with its corresponding flag" do
expect(Compliance::Countries.country_with_flag_by_name("United States")).to eq("🇺🇸 United States")
end
end
context "for an invalid country name" do
it "returns 'Elsewhere'" do
expect(Compliance::Countries.country_with_flag_by_name("Mordor")).to eq("🌎 Elsewhere")
end
end
context "when country name is nil" do
it "returns 'Elsewhere'" do
expect(Compliance::Countries.country_with_flag_by_name(nil)).to eq("🌎 Elsewhere")
end
end
end
describe ".elsewhere_with_flag" do
it "returns 'Elsewhere' with globe emoji" do
expect(Compliance::Countries.elsewhere_with_flag).to eq("🌎 Elsewhere")
end
end
describe ".subdivisions_for_select" do
it "returns expected subdivisions for united states" do
expect(Compliance::Countries.subdivisions_for_select(Compliance::Countries::USA.alpha2)).to eq(united_states_subdivisions_for_select_expected)
end
it "returns expected subdivisions for canada" do
expect(Compliance::Countries.subdivisions_for_select(Compliance::Countries::CAN.alpha2)).to eq(canada_subdivisions_for_select_expected)
end
it "returns expected subdivisions for australia" do
expect(Compliance::Countries.subdivisions_for_select(Compliance::Countries::AUS.alpha2)).to eq(australia_subdivisions_for_select_expected)
end
it "returns expected subdivisions for united arab emirates" do
expect(Compliance::Countries.subdivisions_for_select(Compliance::Countries::ARE.alpha2)).to eq(united_arab_emirates_subdivisions_for_select_expected)
end
it "returns expected subdivisions for mexico" do
expect(Compliance::Countries.subdivisions_for_select(Compliance::Countries::MEX.alpha2)).to eq(mexico_subdivisions_for_select_expected)
end
it "returns expected subdivisions for ireland" do
expect(Compliance::Countries.subdivisions_for_select(Compliance::Countries::IRL.alpha2)).to eq(ireland_subdivisions_for_select_expected)
end
it "raises an ArgumentError for a country we haven't added subdivision support for yet" do
expect do
Compliance::Countries.subdivisions_for_select(Compliance::Countries::QAT.alpha2)
end.to raise_error(ArgumentError).with_message("Country subdivisions not supported")
end
end
describe ".find_subdivision_code" do
it "returns the subdivision code for a valid subdivision code" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::USA.alpha2, "CA")).to eq("CA")
end
it "returns the subdivision code for a valid subdivision name" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::USA.alpha2, "California")).to eq("CA")
end
it "returns a subdivision code for a valid subdivision name with more than one word" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::USA.alpha2, "North Dakota")).to eq("ND")
end
it "returns a subdivision code for a valid but mixed case subdivision name" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::USA.alpha2, "caliFornia")).to eq("CA")
end
it "returns a subdivision code for a valid but mixed case subdivision name with more than one word" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::USA.alpha2, "north dakota")).to eq("ND")
end
it "returns a subdivision code for mixed case District of Columbia" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::USA.alpha2, "distriCt of columbiA")).to eq("DC")
end
it "returns nil for an invalid subdivision name" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::USA.alpha2, nil)).to eq(nil)
end
it "returns nil for a nil country code" do
expect(Compliance::Countries.find_subdivision_code(nil, "California")).to eq(nil)
end
it "returns nil for a mismatched country and subdivision combination" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::AUS.alpha2, "California")).to eq(nil)
end
it "returns a subdivision code for mixed case Newfoundland and Labrador" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::CAN.alpha2, "newfoundlanD and labraDor")).to eq("NL")
end
it "returns nil for a country without any subdivisions" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::PRI.alpha2, "Puerto Rico")).to eq(nil)
end
it "returns the expected subdivision code for a subdivision name given in the `countries` gem" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::ARE.alpha2, "Dubayy")).to eq("DU")
end
it "returns the expected subdivision code for a subdivision name's English translation in the `countries` gem" do
expect(Compliance::Countries.find_subdivision_code(Compliance::Countries::ARE.alpha2, "Dubai")).to eq("DU")
end
end
end
def mapping_expected
{
"AD" => "Andorra",
"AE" => "United Arab Emirates",
"AF" => "Afghanistan",
"AG" => "Antigua and Barbuda",
"AI" => "Anguilla",
"AL" => "Albania",
"AM" => "Armenia",
"AO" => "Angola",
"AQ" => "Antarctica",
"AR" => "Argentina",
"AS" => "American Samoa",
"AT" => "Austria",
"AU" => "Australia",
"AW" => "Aruba",
"AX" => "Åland Islands",
"AZ" => "Azerbaijan",
"BA" => "Bosnia and Herzegovina",
"BB" => "Barbados",
"BD" => "Bangladesh",
"BE" => "Belgium",
"BF" => "Burkina Faso",
"BG" => "Bulgaria",
"BH" => "Bahrain",
"BI" => "Burundi",
"BJ" => "Benin",
"BL" => "Saint Barthélemy",
"BM" => "Bermuda",
"BN" => "Brunei Darussalam",
"BO" => "Bolivia",
"BQ" => "Bonaire, Sint Eustatius and Saba",
"BR" => "Brazil",
"BS" => "Bahamas",
"BT" => "Bhutan",
"BV" => "Bouvet Island",
"BW" => "Botswana",
"BY" => "Belarus",
"BZ" => "Belize",
"CA" => "Canada",
"CC" => "Cocos (Keeling) Islands",
"CD" => "Congo, The Democratic Republic of the",
"CF" => "Central African Republic",
"CG" => "Congo",
"CH" => "Switzerland",
"CI" => "Côte d'Ivoire",
"CK" => "Cook Islands",
"CL" => "Chile",
"CM" => "Cameroon",
"CN" => "China",
"CO" => "Colombia",
"CR" => "Costa Rica",
"CU" => "Cuba",
"CV" => "Cabo Verde",
"CW" => "Curaçao",
"CX" => "Christmas Island",
"CY" => "Cyprus",
"CZ" => "Czechia",
"DE" => "Germany",
"DJ" => "Djibouti",
"DK" => "Denmark",
"DM" => "Dominica",
"DO" => "Dominican Republic",
"DZ" => "Algeria",
"EC" => "Ecuador",
"EE" => "Estonia",
"EG" => "Egypt",
"EH" => "Western Sahara",
"ER" => "Eritrea",
"ES" => "Spain",
"ET" => "Ethiopia",
"FI" => "Finland",
"FJ" => "Fiji",
"FK" => "Falkland Islands (Malvinas)",
"FM" => "Micronesia, Federated States of",
"FO" => "Faroe Islands",
"FR" => "France",
"GA" => "Gabon",
"GB" => "United Kingdom",
"GD" => "Grenada",
"GE" => "Georgia",
"GF" => "French Guiana",
"GG" => "Guernsey",
"GH" => "Ghana",
"GI" => "Gibraltar",
"GL" => "Greenland",
"GM" => "Gambia",
"GN" => "Guinea",
"GP" => "Guadeloupe",
"GQ" => "Equatorial Guinea",
"GR" => "Greece",
"GS" => "South Georgia and the South Sandwich Islands",
"GT" => "Guatemala",
"GU" => "Guam",
"GW" => "Guinea-Bissau",
"GY" => "Guyana",
"HK" => "Hong Kong",
"HM" => "Heard Island and McDonald Islands",
"HN" => "Honduras",
"HR" => "Croatia",
"HT" => "Haiti",
"HU" => "Hungary",
"ID" => "Indonesia",
"IE" => "Ireland",
"IL" => "Israel",
"IM" => "Isle of Man",
"IN" => "India",
"IO" => "British Indian Ocean Territory",
"IQ" => "Iraq",
"IR" => "Iran",
"IS" => "Iceland",
"IT" => "Italy",
"JE" => "Jersey",
"JM" => "Jamaica",
"JO" => "Jordan",
"JP" => "Japan",
"KE" => "Kenya",
"KG" => "Kyrgyzstan",
"KH" => "Cambodia",
"KI" => "Kiribati",
"KM" => "Comoros",
"KN" => "Saint Kitts and Nevis",
"KP" => "North Korea",
"KR" => "South Korea",
"KW" => "Kuwait",
"KY" => "Cayman Islands",
"KZ" => "Kazakhstan",
"LA" => "Lao People's Democratic Republic",
"LB" => "Lebanon",
"LC" => "Saint Lucia",
"LI" => "Liechtenstein",
"LK" => "Sri Lanka",
"LR" => "Liberia",
"LS" => "Lesotho",
"LT" => "Lithuania",
"LU" => "Luxembourg",
"LV" => "Latvia",
"LY" => "Libya",
"MA" => "Morocco",
"MC" => "Monaco",
"MD" => "Moldova",
"ME" => "Montenegro",
"MF" => "Saint Martin (French part)",
"MG" => "Madagascar",
"MH" => "Marshall Islands",
"MK" => "North Macedonia",
"ML" => "Mali",
"MM" => "Myanmar",
"MN" => "Mongolia",
"MO" => "Macao",
"MP" => "Northern Mariana Islands",
"MQ" => "Martinique",
"MR" => "Mauritania",
"MS" => "Montserrat",
"MT" => "Malta",
"MU" => "Mauritius",
"MV" => "Maldives",
"MW" => "Malawi",
"MX" => "Mexico",
"MY" => "Malaysia",
"MZ" => "Mozambique",
"NA" => "Namibia",
"NC" => "New Caledonia",
"NE" => "Niger",
"NF" => "Norfolk Island",
"NG" => "Nigeria",
"NI" => "Nicaragua",
"NL" => "Netherlands",
"NO" => "Norway",
"NP" => "Nepal",
"NR" => "Nauru",
"NU" => "Niue",
"NZ" => "New Zealand",
"OM" => "Oman",
"PA" => "Panama",
"PE" => "Peru",
"PF" => "French Polynesia",
"PG" => "Papua New Guinea",
"PH" => "Philippines",
"PK" => "Pakistan",
"PL" => "Poland",
"PM" => "Saint Pierre and Miquelon",
"PN" => "Pitcairn",
"PR" => "Puerto Rico",
"PS" => "Palestine, State of",
"PT" => "Portugal",
"PW" => "Palau",
"PY" => "Paraguay",
"QA" => "Qatar",
"RE" => "Réunion",
"RO" => "Romania",
"RS" => "Serbia",
"RU" => "Russian Federation",
"RW" => "Rwanda",
"SA" => "Saudi Arabia",
"SB" => "Solomon Islands",
"SC" => "Seychelles",
"SD" => "Sudan",
"SE" => "Sweden",
"SG" => "Singapore",
"SH" => "Saint Helena, Ascension and Tristan da Cunha",
"SI" => "Slovenia",
"SJ" => "Svalbard and Jan Mayen",
"SK" => "Slovakia",
"SL" => "Sierra Leone",
"SM" => "San Marino",
"SN" => "Senegal",
"SO" => "Somalia",
"SR" => "Suriname",
"SS" => "South Sudan",
"ST" => "Sao Tome and Principe",
"SV" => "El Salvador",
"SX" => "Sint Maarten (Dutch part)",
"SY" => "Syrian Arab Republic",
"SZ" => "Eswatini",
"TC" => "Turks and Caicos Islands",
"TD" => "Chad",
"TF" => "French Southern Territories",
"TG" => "Togo",
"TH" => "Thailand",
"TJ" => "Tajikistan",
"TK" => "Tokelau",
"TL" => "Timor-Leste",
"TM" => "Turkmenistan",
"TN" => "Tunisia",
"TO" => "Tonga",
"TR" => "Türkiye",
"TT" => "Trinidad and Tobago",
"TV" => "Tuvalu",
"TW" => "Taiwan",
"TZ" => "Tanzania",
"UA" => "Ukraine",
"UG" => "Uganda",
"UM" => "United States Minor Outlying Islands",
"US" => "United States",
"UY" => "Uruguay",
"UZ" => "Uzbekistan",
"VA" => "Holy See (Vatican City State)",
"VC" => "Saint Vincent and the Grenadines",
"VE" => "Venezuela",
"VG" => "Virgin Islands, British",
"VI" => "Virgin Islands, U.S.",
"VN" => "Vietnam",
"VU" => "Vanuatu",
"WF" => "Wallis and Futuna",
"WS" => "Samoa",
"XK" => "Kosovo",
"YE" => "Yemen",
"YT" => "Mayotte",
"ZA" => "South Africa",
"ZM" => "Zambia",
"ZW" => "Zimbabwe"
}
end
def for_select_expected
[
["AF", "Afghanistan (not supported)"],
["AL", "Albania"],
["DZ", "Algeria"],
["AS", "American Samoa"],
["AD", "Andorra"],
["AO", "Angola"],
["AI", "Anguilla"],
["AQ", "Antarctica"],
["AG", "Antigua and Barbuda"],
["AR", "Argentina"],
["AM", "Armenia"],
["AW", "Aruba"],
["AU", "Australia"],
["AT", "Austria"],
["AZ", "Azerbaijan"],
["BS", "Bahamas"],
["BH", "Bahrain"],
["BD", "Bangladesh"],
["BB", "Barbados"],
["BY", "Belarus"],
["BE", "Belgium"],
["BZ", "Belize"],
["BJ", "Benin"],
["BM", "Bermuda"],
["BT", "Bhutan"],
["BO", "Bolivia"],
["BQ", "Bonaire, Sint Eustatius and Saba"],
["BA", "Bosnia and Herzegovina"],
["BW", "Botswana"],
["BV", "Bouvet Island"],
["BR", "Brazil"],
["IO", "British Indian Ocean Territory"],
["BN", "Brunei Darussalam"],
["BG", "Bulgaria"],
["BF", "Burkina Faso"],
["BI", "Burundi"],
["CV", "Cabo Verde"],
["KH", "Cambodia"],
["CM", "Cameroon"],
["CA", "Canada"],
["KY", "Cayman Islands"],
["CF", "Central African Republic"],
["TD", "Chad"],
["CL", "Chile"],
["CN", "China"],
["CX", "Christmas Island"],
["CC", "Cocos (Keeling) Islands"],
["CO", "Colombia"],
["KM", "Comoros"],
["CG", "Congo"],
["CD", "Congo, The Democratic Republic of the (not supported)"],
["CK", "Cook Islands"],
["CR", "Costa Rica"],
["HR", "Croatia"],
["CU", "Cuba (not supported)"],
["CW", "Curaçao"],
["CY", "Cyprus"],
["CZ", "Czechia"],
["CI", "Côte d'Ivoire (not supported)"],
["DK", "Denmark"],
["DJ", "Djibouti"],
["DM", "Dominica"],
["DO", "Dominican Republic"],
["EC", "Ecuador"],
["EG", "Egypt"],
["SV", "El Salvador"],
["GQ", "Equatorial Guinea"],
["ER", "Eritrea"],
["EE", "Estonia"],
["SZ", "Eswatini"],
["ET", "Ethiopia"],
["FK", "Falkland Islands (Malvinas)"],
["FO", "Faroe Islands"],
["FJ", "Fiji"],
["FI", "Finland"],
["FR", "France"],
["GF", "French Guiana"],
["PF", "French Polynesia"],
["TF", "French Southern Territories"],
["GA", "Gabon"],
["GM", "Gambia"],
["GE", "Georgia"],
["DE", "Germany"],
["GH", "Ghana"],
["GI", "Gibraltar"],
["GR", "Greece"],
["GL", "Greenland"],
["GD", "Grenada"],
["GP", "Guadeloupe"],
["GU", "Guam"],
["GT", "Guatemala"],
["GG", "Guernsey"],
["GN", "Guinea"],
["GW", "Guinea-Bissau"],
["GY", "Guyana"],
["HT", "Haiti"],
["HM", "Heard Island and McDonald Islands"],
["VA", "Holy See (Vatican City State)"],
["HN", "Honduras"],
["HK", "Hong Kong"],
["HU", "Hungary"],
["IS", "Iceland"],
["IN", "India"],
["ID", "Indonesia"],
["IR", "Iran (not supported)"],
["IQ", "Iraq (not supported)"],
["IE", "Ireland"],
["IM", "Isle of Man"],
["IL", "Israel"],
["IT", "Italy"],
["JM", "Jamaica"],
["JP", "Japan"],
["JE", "Jersey"],
["JO", "Jordan"],
["KZ", "Kazakhstan"],
["KE", "Kenya"],
["KI", "Kiribati"],
["XK", "Kosovo"],
["KW", "Kuwait"],
["KG", "Kyrgyzstan"],
["LA", "Lao People's Democratic Republic"],
["LV", "Latvia"],
["LB", "Lebanon (not supported)"],
["LS", "Lesotho"],
["LR", "Liberia (not supported)"],
["LY", "Libya (not supported)"],
["LI", "Liechtenstein"],
["LT", "Lithuania"],
["LU", "Luxembourg"],
["MO", "Macao"],
["MG", "Madagascar"],
["MW", "Malawi"],
["MY", "Malaysia"],
["MV", "Maldives"],
["ML", "Mali"],
["MT", "Malta"],
["MH", "Marshall Islands"],
["MQ", "Martinique"],
["MR", "Mauritania"],
["MU", "Mauritius"],
["YT", "Mayotte"],
["MX", "Mexico"],
["FM", "Micronesia, Federated States of"],
["MD", "Moldova"],
["MC", "Monaco"],
["MN", "Mongolia"],
["ME", "Montenegro"],
["MS", "Montserrat"],
["MA", "Morocco"],
["MZ", "Mozambique"],
["MM", "Myanmar (not supported)"],
["NA", "Namibia"],
["NR", "Nauru"],
["NP", "Nepal"],
["NL", "Netherlands"],
["NC", "New Caledonia"],
["NZ", "New Zealand"],
["NI", "Nicaragua"],
["NE", "Niger"],
["NG", "Nigeria"],
["NU", "Niue"],
["NF", "Norfolk Island"],
["KP", "North Korea (not supported)"],
["MK", "North Macedonia"],
["MP", "Northern Mariana Islands"],
["NO", "Norway"],
["OM", "Oman"],
["PK", "Pakistan"],
["PW", "Palau"],
["PS", "Palestine, State of"],
["PA", "Panama"],
["PG", "Papua New Guinea"],
["PY", "Paraguay"],
["PE", "Peru"],
["PH", "Philippines"],
["PN", "Pitcairn"],
["PL", "Poland"],
["PT", "Portugal"],
["PR", "Puerto Rico"],
["QA", "Qatar"],
["RO", "Romania"],
["RU", "Russian Federation"],
["RW", "Rwanda"],
["RE", "Réunion"],
["BL", "Saint Barthélemy"],
["SH", "Saint Helena, Ascension and Tristan da Cunha"],
["KN", "Saint Kitts and Nevis"],
["LC", "Saint Lucia"],
["MF", "Saint Martin (French part)"],
["PM", "Saint Pierre and Miquelon"],
["VC", "Saint Vincent and the Grenadines"],
["WS", "Samoa"],
["SM", "San Marino"],
["ST", "Sao Tome and Principe"],
["SA", "Saudi Arabia"],
["SN", "Senegal"],
["RS", "Serbia"],
["SC", "Seychelles"],
["SL", "Sierra Leone"],
["SG", "Singapore"],
["SX", "Sint Maarten (Dutch part)"],
["SK", "Slovakia"],
["SI", "Slovenia"],
["SB", "Solomon Islands"],
["SO", "Somalia (not supported)"],
["ZA", "South Africa"],
["GS", "South Georgia and the South Sandwich Islands"],
["KR", "South Korea"],
["SS", "South Sudan"],
["ES", "Spain"],
["LK", "Sri Lanka"],
["SD", "Sudan (not supported)"],
["SR", "Suriname"],
["SJ", "Svalbard and Jan Mayen"],
["SE", "Sweden"],
["CH", "Switzerland"],
["SY", "Syrian Arab Republic (not supported)"],
["TW", "Taiwan"],
["TJ", "Tajikistan"],
["TZ", "Tanzania"],
["TH", "Thailand"],
["TL", "Timor-Leste"],
["TG", "Togo"],
["TK", "Tokelau"],
["TO", "Tonga"],
["TT", "Trinidad and Tobago"],
["TN", "Tunisia"],
["TM", "Turkmenistan"],
["TC", "Turks and Caicos Islands"],
["TV", "Tuvalu"],
["TR", "Türkiye"],
["UG", "Uganda"],
["UA", "Ukraine"],
["AE", "United Arab Emirates"],
["GB", "United Kingdom"],
["US", "United States"],
["UM", "United States Minor Outlying Islands"],
["UY", "Uruguay"],
["UZ", "Uzbekistan"],
["VU", "Vanuatu"],
["VE", "Venezuela"],
["VN", "Vietnam"],
["VG", "Virgin Islands, British"],
["VI", "Virgin Islands, U.S."],
["WF", "Wallis and Futuna"],
["EH", "Western Sahara"],
["YE", "Yemen (not supported)"],
["ZM", "Zambia"],
["ZW", "Zimbabwe (not supported)"],
["AX", "Åland Islands"]
]
end
def united_states_subdivisions_for_select_expected
[
["AL", "Alabama"],
["AK", "Alaska"],
["AZ", "Arizona"],
["AR", "Arkansas"],
["CA", "California"],
["CO", "Colorado"],
["CT", "Connecticut"],
["DE", "Delaware"],
["DC", "District of Columbia"],
["FL", "Florida"],
["GA", "Georgia"],
["HI", "Hawaii"],
["ID", "Idaho"],
["IL", "Illinois"],
["IN", "Indiana"],
["IA", "Iowa"],
["KS", "Kansas"],
["KY", "Kentucky"],
["LA", "Louisiana"],
["ME", "Maine"],
["MD", "Maryland"],
["MA", "Massachusetts"],
["MI", "Michigan"],
["MN", "Minnesota"],
["MS", "Mississippi"],
["MO", "Missouri"],
["MT", "Montana"],
["NE", "Nebraska"],
["NV", "Nevada"],
["NH", "New Hampshire"],
["NJ", "New Jersey"],
["NM", "New Mexico"],
["NY", "New York"],
["NC", "North Carolina"],
["ND", "North Dakota"],
["OH", "Ohio"],
["OK", "Oklahoma"],
["OR", "Oregon"],
["PA", "Pennsylvania"],
["RI", "Rhode Island"],
["SC", "South Carolina"],
["SD", "South Dakota"],
["TN", "Tennessee"],
["TX", "Texas"],
["UT", "Utah"],
["VT", "Vermont"],
["VA", "Virginia"],
["WA", "Washington"],
["WV", "West Virginia"],
["WI", "Wisconsin"],
["WY", "Wyoming"]
]
end
def canada_subdivisions_for_select_expected
[
["AB", "Alberta"],
["BC", "British Columbia"],
["MB", "Manitoba"],
["NB", "New Brunswick"],
["NL", "Newfoundland and Labrador"],
["NT", "Northwest Territories"],
["NS", "Nova Scotia"],
["NU", "Nunavut"],
["ON", "Ontario"],
["PE", "Prince Edward Island"],
["QC", "Quebec"],
["SK", "Saskatchewan"],
["YT", "Yukon"]
]
end
def australia_subdivisions_for_select_expected
[
["ACT", "Australian Capital Territory"],
["NSW", "New South Wales"],
["NT", "Northern Territory"],
["QLD", "Queensland"],
["SA", "South Australia"],
["TAS", "Tasmania"],
["VIC", "Victoria"],
["WA", "Western Australia"]
]
end
def united_arab_emirates_subdivisions_for_select_expected
[
["AZ", "Abu Dhabi"],
["AJ", "Ajman"],
["DU", "Dubai"],
["FU", "Fujairah"],
["RK", "Ras al-Khaimah"],
["SH", "Sharjah"],
["UQ", "Umm al-Quwain"]
]
end
def mexico_subdivisions_for_select_expected
[
["AGU", "Aguascalientes"],
["BCN", "Baja California"],
["BCS", "Baja California Sur"],
["CAM", "Campeche"],
["CHP", "Chiapas"],
["CHH", "Chihuahua"],
["CMX", "Ciudad de México"],
["COA", "Coahuila"],
["COL", "Colima"],
["DUR", "Durango"],
["GUA", "Guanajuato"],
["GRO", "Guerrero"],
["HID", "Hidalgo"],
["JAL", "Jalisco"],
["MIC", "Michoacán"],
["MOR", "Morelos"],
["MEX", "México"],
["NAY", "Nayarit"],
["NLE", "Nuevo León"],
["OAX", "Oaxaca"],
["PUE", "Puebla"],
["QUE", "Querétaro"],
["ROO", "Quintana Roo"],
["SLP", "San Luis Potosí"],
["SIN", "Sinaloa"],
["SON", "Sonora"],
["TAB", "Tabasco"],
["TAM", "Tamaulipas"],
["TLA", "Tlaxcala"],
["VER", "Veracruz"],
["YUC", "Yucatán"],
["ZAC", "Zacatecas"]
]
end
def ireland_subdivisions_for_select_expected
[
["CW", "Carlow"],
["CN", "Cavan"],
["CE", "Clare"],
["CO", "Cork"],
["DL", "Donegal"],
["D", "Dublin"],
["G", "Galway"],
["KY", "Kerry"],
["KE", "Kildare"],
["KK", "Kilkenny"],
["LS", "Laois"],
["LM", "Leitrim"],
["LK", "Limerick"],
["LD", "Longford"],
["LH", "Louth"],
["MO", "Mayo"],
["MH", "Meath"],
["MN", "Monaghan"],
["OY", "Offaly"],
["RN", "Roscommon"],
["SO", "Sligo"],
["TA", "Tipperary"],
["WD", "Waterford"],
["WH", "Westmeath"],
["WX", "Wexford"],
["WW", "Wicklow"]
]
end
def taxable_region_codes_expected
[
"US_AL",
"US_AK",
"US_AZ",
"US_AR",
"US_CA",
"US_CO",
"US_CT",
"US_DE",
"US_DC",
"US_FL",
"US_GA",
"US_HI",
"US_ID",
"US_IL",
"US_IN",
"US_IA",
"US_KS",
"US_KY",
"US_LA",
"US_ME",
"US_MD",
"US_MA",
"US_MI",
"US_MN",
"US_MS",
"US_MO",
"US_MT",
"US_NE",
"US_NV",
"US_NH",
"US_NJ",
"US_NM",
"US_NY",
"US_NC",
"US_ND",
"US_OH",
"US_OK",
"US_OR",
"US_PA",
"US_PR",
"US_RI",
"US_SC",
"US_SD",
"US_TN",
"US_TX",
"US_UT",
"US_VT",
"US_VA",
"US_WA",
"US_WV",
"US_WI",
"US_WY",
]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/replica_lag_watcher_spec.rb | spec/lib/utilities/replica_lag_watcher_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ReplicaLagWatcher do
after do
Thread.current["ReplicaLagWatcher.connections"] = nil
Thread.current["ReplicaLagWatcher.last_checked_at"] = nil
end
describe ".watch" do
it "sleeps if a replica is lagging" do
stub_const("REPLICAS_HOSTS", [double])
expect(described_class).to receive(:connect_to_replicas)
expect(described_class).to receive(:lagging?).with(any_args).and_return(true, true, false)
expect(described_class).to receive(:sleep).with(1).twice
described_class.watch(silence: true)
end
it "does nothing if there are no replicas" do
stub_const("REPLICAS_HOSTS", [])
expect(described_class).not_to receive(:lagging?)
described_class.watch
expect(described_class.last_checked_at).to eq(nil)
end
end
describe ".lagging?" do
before do
@options = { check_every: 1.second, max_lag_allowed: 1.second, silence: true }
allow(described_class).to receive(:check_for_lag?).with(1.second).and_return(true)
described_class.connections = []
end
def set_connections
described_class.connections = [double(query_options: { host: "replica.host" })]
query_response = [{ "Seconds_Behind_Master" => @seconds_behind_master }]
expect(described_class.connections.first).to receive(:query).with("SHOW SLAVE STATUS").and_return(query_response)
end
it "sets last_checked_at" do
described_class.lagging?(@options)
expect(described_class.last_checked_at.is_a?(Float)).to eq(true)
end
it "returns true if one of the replica connections is lagging" do
@seconds_behind_master = 2
set_connections
expect(described_class.lagging?(@options)).to eq(true)
end
it "returns false if no connections are lagging" do
@seconds_behind_master = 0
set_connections
expect(described_class.lagging?(@options)).to eq(false)
end
it "raises an error if the lag can't be determined" do
@seconds_behind_master = nil
set_connections
expect do
described_class.lagging?(@options)
end.to raise_error(/lag = null/)
end
it "returns nil if it doesn't need to check for lag" do
expect(described_class).to receive(:check_for_lag?).with(1).and_return(false)
expect(described_class.lagging?(@options)).to eq(nil)
end
end
describe ".check_for_lag?" do
it "returns true if it was never checked before" do
expect(described_class.check_for_lag?(1)).to eq(true)
end
it "returns true/false whether it was checked more or less than the allowed time" do
check_every = 1
# Test relies on the reasonable assumption that it takes less than a second the two following lines
described_class.last_checked_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
expect(described_class.check_for_lag?(check_every)).to eq(false)
# One second later we should check for lag again
sleep 1
expect(described_class.check_for_lag?(check_every)).to eq(true)
end
end
describe ".connect_to_replicas" do
it "does not set new connections if some exist already" do
described_class.connections = [double]
expect(described_class).not_to receive(:connections=)
described_class.connect_to_replicas
end
it "sets connections if they weren't set before" do
stub_const("REPLICAS_HOSTS", ["web-replica-1.aaaaaa.us-east-1.rds.amazonaws.com"])
connection_double = double
expect(Mysql2::Client).to receive(:new).with(
host: "web-replica-1.aaaaaa.us-east-1.rds.amazonaws.com",
username: ActiveRecord::Base.connection_db_config.configuration_hash[:username],
password: ActiveRecord::Base.connection_db_config.configuration_hash[:password],
database: ActiveRecord::Base.connection_db_config.configuration_hash[:database],
).and_return(connection_double)
described_class.connect_to_replicas
expect(described_class.connections).to eq([connection_double])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/o_embed_finder_spec.rb | spec/lib/utilities/o_embed_finder_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe OEmbedFinder do
describe "#embeddable_from_url" do
before :each do
expect(OEmbed::Providers).to receive(:register_all)
end
it "returns nil if there is an exceptions when getting oembed" do
allow(OEmbed::Providers).to receive(:get).and_raise(StandardError)
expect(OEmbedFinder.embeddable_from_url("some url")).to be(nil)
end
describe "video" do
before :each do
@width = 600
@height = 400
@thumbnail_url = "http://example.com/url-to-thumbnail.jpg"
@response_mock = double(video?: true)
allow(@response_mock).to receive(:fields).and_return("width" => 600,
"height" => 400,
"thumbnail_url" => "http://example.com/url-to-thumbnail.jpg",
"thumbnail_width" => 200,
"thumbnail_height" => 133)
allow(OEmbed::Providers).to receive(:get) { @response_mock }
end
it "returns plain embeddable" do
embeddable = "<oembed/>"
expect(@response_mock).to receive(:html).and_return(embeddable)
result = OEmbedFinder.embeddable_from_url("url")
expect(result[:html]).to eq embeddable
expect(result[:info]).to eq("width" => 600,
"height" => 400,
"thumbnail_url" => "http://example.com/url-to-thumbnail.jpg")
end
describe "soundcloud" do
it "replaces http with https" do
embeddable = "<oembed><author_url>http://w.soundcloud.com</author_url><provider_url>api.soundcloud.com</provider_url></oembed>"
processed_embeddable = "<oembed><author_url>https://w.soundcloud.com</author_url><provider_url>api.soundcloud.com</provider_url></oembed>"
expect(@response_mock).to receive(:html).and_return(embeddable)
expect(OEmbedFinder.embeddable_from_url("url")[:html]).to eq processed_embeddable
end
it "replaces show_artwork payload with all available payloads with false value" do
embeddable = "<oembed><author_url>http://w.soundcloud.com?show_artwork=true</author_url><provider_url>api.soundcloud.com</provider_url></oembed>"
all_payloads_with_false_value = OEmbedFinder::SOUNDCLOUD_PARAMS.map { |k| "#{k}=false" }.join("&")
processed_embeddable = "<oembed><author_url>https://w.soundcloud.com?#{all_payloads_with_false_value}</author_url>"
processed_embeddable += "<provider_url>api.soundcloud.com</provider_url></oembed>"
expect(@response_mock).to receive(:html).and_return(embeddable)
expect(OEmbedFinder.embeddable_from_url("url")[:html]).to eq processed_embeddable
end
end
describe "youtube" do
it "replaces http with https" do
embeddable = "<oembed><author_url>http://www.youtube.com/embed</author_url></oembed>"
processed_embeddable = "<oembed><author_url>https://www.youtube.com/embed</author_url></oembed>"
expect(@response_mock).to receive(:html).and_return(embeddable)
expect(OEmbedFinder.embeddable_from_url("url")[:html]).to eq processed_embeddable
end
it "adds showinfor and controls payloads" do
embeddable = "<oembed><author_url>https://www.youtube.com/embed?feature=oembed</author_url></oembed>"
processed_embeddable = "<oembed><author_url>https://www.youtube.com/embed?feature=oembed&showinfo=0&controls=0&rel=0</author_url></oembed>"
expect(@response_mock).to receive(:html).and_return(embeddable)
expect(OEmbedFinder.embeddable_from_url("url")[:html]).to eq processed_embeddable
end
it "replaces http with https for vimeo" do
embeddable = "<oembed><author_url>http://player.vimeo.com/video/71588076</author_url></oembed>"
processed_embeddable = "<oembed><author_url>https://player.vimeo.com/video/71588076</author_url></oembed>"
expect(@response_mock).to receive(:html).and_return(embeddable)
expect(OEmbedFinder.embeddable_from_url("url")[:html]).to eq processed_embeddable
end
end
end
describe "photo" do
before :each do
@response_mock = double(video?: false, rich?: false, photo?: true)
allow(OEmbed::Providers).to receive(:get) { @response_mock }
end
it "returns nil so that we fallback to default preview container" do
embeddable = "Some image"
new_url = "https://www.flickr.com/id=1"
allow(@response_mock).to receive(:html).and_return(embeddable)
expect(OEmbedFinder.embeddable_from_url(new_url)).to eq nil
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/dev_tools_spec.rb | spec/lib/utilities/dev_tools_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DevTools do
# Very basic tests just to guard for basic runtime errors (method not found, etc).
describe ".reindex_all_for_user" do
it "succeeds after indexing at least one record" do
product = create(:product)
Link.__elasticsearch__.create_index!(force: true)
described_class.reindex_all_for_user(product.user)
expect(get_product_document(product.id)["found"]).to eq(true)
end
it "does not delete the indices" do
product = create(:product)
Link.__elasticsearch__.create_index!(force: true)
EsClient.index(index: Link.index_name, id: "test", body: {})
described_class.reindex_all_for_user(product.user)
expect(get_product_document("test")["found"]).to eq(true)
expect(get_product_document(product.id)["found"]).to eq(true)
end
end
describe ".delete_all_indices_and_reindex_all" do
it "succeeds after indexing at least one record" do
product = create(:product)
Link.__elasticsearch__.delete_index!(force: true)
described_class.delete_all_indices_and_reindex_all
expect(get_product_document(product.id)["found"]).to eq(true)
end
it "does not execute in production" do
allow(Rails.env).to receive(:production?).and_return(true)
Link.__elasticsearch__.create_index!(force: true)
EsClient.index(index: Link.index_name, id: "test", body: {})
expect { described_class.delete_all_indices_and_reindex_all }.to raise_error(StandardError, /production/)
expect(get_product_document("test")["found"]).to eq(true)
end
end
describe ".reimport_follower_events_for_user!" do
let(:index_class) { ConfirmedFollowerEvent }
let(:index_name) { index_class.index_name }
it "delete all events and creates events for every confirmed follower" do
user = create(:user)
EsClient.index(index: index_name, body: { name: "added", followed_user_id: user.id, timestamp: 10.days.ago })
EsClient.index(index: index_name, body: { name: "removed", followed_user_id: user.id, timestamp: 9.days.ago })
EsClient.index(index: index_name, body: { name: "added", followed_user_id: user.id, timestamp: 8.days.ago })
event_belonging_to_another_user_id = SecureRandom.uuid
EsClient.index(index: index_name, id: event_belonging_to_another_user_id, body: { name: "added", timestamp: 10.days.ago })
index_class.__elasticsearch__.refresh_index!
create(:follower, user:)
create(:deleted_follower, user:)
followers = [
create(:active_follower, user:, confirmed_at: Time.utc(2021, 1)),
create(:active_follower, user:, confirmed_at: Time.utc(2021, 2))
]
described_class.reimport_follower_events_for_user!(user)
index_class.__elasticsearch__.refresh_index!
documents = EsClient.search(
index: index_name,
body: { query: { term: { followed_user_id: user.id } }, sort: :timestamp }
)["hits"]["hits"]
expect(documents.size).to eq(2)
expect(documents[0]["_source"]).to eq(
"name" => "added",
"timestamp" => "2021-01-01T00:00:00Z",
"follower_id" => followers[0].id,
"followed_user_id" => followers[0].user.id,
"follower_user_id" => nil,
"email" => followers[0].email
)
expect(documents[1]["_source"]).to eq(
"name" => "added",
"timestamp" => "2021-02-01T00:00:00Z",
"follower_id" => followers[1].id,
"followed_user_id" => followers[1].user.id,
"follower_user_id" => nil,
"email" => followers[1].email
)
# check the event belonging to another user was not deleted
expect do
EsClient.get(index: index_name, id: event_belonging_to_another_user_id)
end.not_to raise_error
end
end
def get_product_document(document_id)
EsClient.get(index: Link.index_name, id: document_id, ignore: [404])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/sidekiq_utility_spec.rb | spec/lib/utilities/sidekiq_utility_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SidekiqUtility do
before do
ENV["SIDEKIQ_GRACEFUL_SHUTDOWN_TIMEOUT"] = "3"
ENV["SIDEKIQ_LIFECYCLE_HOOK_NAME"] = "sample_hook_name"
ENV["SIDEKIQ_ASG_NAME"] = "sample_asg_name"
uri_double = double("uri_double")
allow(URI).to receive(:parse).with(described_class::INSTANCE_ID_ENDPOINT).and_return(uri_double)
allow(Net::HTTP).to receive(:get).with(uri_double).and_return("sample_instance_id")
@aws_instance_profile_double = double("aws_instance_profile_double")
allow(Aws::InstanceProfileCredentials).to receive(:new).and_return(@aws_instance_profile_double)
@asg_double = double("asg_double")
allow(Aws::AutoScaling::Client).to receive(:new).with(credentials: @aws_instance_profile_double).and_return(@asg_double)
@current_time = Time.current
travel_to(@current_time) do
@sidekiq_utility = described_class.new
end
end
after do
ENV.delete("SIDEKIQ_GRACEFUL_SHUTDOWN_TIMEOUT")
ENV.delete("SIDEKIQ_LIFECYCLE_HOOK_NAME")
ENV.delete("SIDEKIQ_ASG_NAME")
end
describe "#initialize" do
it "returns SidekiqUtility object with process_set and timeout_at variables" do
expect(@sidekiq_utility.instance_variable_get(:@process_set).class).to eq Sidekiq::ProcessSet
expect(@sidekiq_utility.instance_variable_get(:@timeout_at).to_i).to eq (@current_time + 3.hours).to_i
end
end
describe "#instance_id" do
it "returns the instance_id" do
expect(@sidekiq_utility.send(:instance_id)).to eq "sample_instance_id"
end
end
describe "#lifecycle_params" do
it "returns lifecycle_params hash" do
lifecycle_params = {
lifecycle_hook_name: "sample_hook_name",
auto_scaling_group_name: "sample_asg_name",
instance_id: "sample_instance_id",
}
expect(@sidekiq_utility.send(:lifecycle_params)).to eq lifecycle_params
end
end
describe "#hostname" do
it "returns hostname of the server" do
expect(@sidekiq_utility.send(:hostname)).to eq Socket.gethostname
end
end
describe "#asg_client" do
it "returns AWS Auto Scaling Group instance" do
expect(Aws::AutoScaling::Client).to receive(:new).with(credentials: @aws_instance_profile_double)
@sidekiq_utility.send(:asg_client)
end
end
describe "sidekiq_process" do
before do
process_set = [
{ "hostname" => "test1", },
{ "hostname" => "test2" }
]
allow(@sidekiq_utility).to receive(:hostname).and_return("test1")
@sidekiq_utility.instance_variable_set(:@process_set, process_set)
end
it "returns the sidekiq process" do
expect(@sidekiq_utility.send(:sidekiq_process)["hostname"]).to eq "test1"
end
end
describe "proceed_with_instance_termination" do
it "completes lifecycle ation" do
params = @sidekiq_utility.send(:lifecycle_params).merge(lifecycle_action_result: "CONTINUE")
expect(@asg_double).to receive(:complete_lifecycle_action).with(params)
@sidekiq_utility.send(:proceed_with_instance_termination)
end
end
describe "#timeout_exceeded?" do
it "returns true if timeout is exceeded" do
@sidekiq_utility.instance_variable_set(:@timeout_at, @current_time - 1.hour)
expect(@sidekiq_utility.send(:timeout_exceeded?)).to be_truthy
end
end
describe "#wait_for_sidekiq_to_process_existing_jobs" do
before do
allow(@sidekiq_utility).to receive(:sidekiq_process).and_return({ "busy" => 2, "identity" => "test_identity" })
end
context "when timeout is exceeded" do
before do
allow(@sidekiq_utility).to receive(:timeout_exceeded?).and_return(true)
end
it "doesn't record the lifecycle heartbeat" do
expect(@asg_double).not_to receive(:record_lifecycle_action_heartbeat)
@sidekiq_utility.send(:wait_for_sidekiq_to_process_existing_jobs)
end
end
context "when timeout is not exceeded" do
before do
allow_any_instance_of(described_class).to receive(:sleep) # Don't sleep!
allow(@sidekiq_utility).to receive(:timeout_exceeded?).and_return(false, false, true) # Return different values per invocation
end
it "records the lifecycle heartbeat until the timeout exceeds" do
expect(@asg_double).to receive(:record_lifecycle_action_heartbeat).twice
@sidekiq_utility.send(:wait_for_sidekiq_to_process_existing_jobs)
end
end
context "when all jobs in the worker belong to ignored classes" do
before do
workers = [
["test_identity", "worker1", { "payload" => { "class" => "HandleSendgridEventJob" }.to_json }],
["test_identity", "worker1", { "payload" => { "class" => "SaveToMongoWorker" }.to_json }]
]
allow(Sidekiq::Workers).to receive(:new).and_return(workers)
allow(Rails.logger).to receive(:info)
end
it "logs the stuck jobs and breaks the loop" do
expect(Rails.logger).to receive(:info).with("[SidekiqUtility] HandleSendgridEventJob, SaveToMongoWorker jobs are stuck. Proceeding with instance termination.")
expect(@asg_double).not_to receive(:record_lifecycle_action_heartbeat)
@sidekiq_utility.send(:wait_for_sidekiq_to_process_existing_jobs)
end
end
context "when not all jobs in the worker belong to ignored classes" do
before do
workers = [
["test_identity", "worker1", { "payload" => { "class" => "HandleSendgridEventJob" }.to_json }],
["test_identity", "worker1", { "payload" => { "class" => "OtherJob" }.to_json }]
]
allow(Sidekiq::Workers).to receive(:new).and_return(workers)
allow(@sidekiq_utility).to receive(:timeout_exceeded?).and_return(false, true)
end
it "continues the loop and records the lifecycle heartbeat" do
expect(Rails.logger).not_to receive(:info).with("[SidekiqUtility] HandleSendgridEventJob, SaveToMongoWorker jobs are stuck. Proceeding with instance termination.")
expect(@asg_double).to receive(:record_lifecycle_action_heartbeat).once
@sidekiq_utility.send(:wait_for_sidekiq_to_process_existing_jobs)
end
end
end
describe "#stop_process" do
before do
@sidekiq_process_double = double("sidekiq process double")
allow(@sidekiq_utility).to receive(:sidekiq_process).and_return(@sidekiq_process_double)
allow(@sidekiq_process_double).to receive(:quiet!)
allow(@sidekiq_utility).to receive(:wait_for_sidekiq_to_process_existing_jobs)
allow(@sidekiq_utility).to receive(:proceed_with_instance_termination)
end
after do
@sidekiq_utility.stop_process
end
it "sets the process to quiet mode" do
expect(@sidekiq_process_double).to receive(:quiet!)
end
it "waits for existing jobs to complete" do
expect(@sidekiq_utility).to receive(:wait_for_sidekiq_to_process_existing_jobs)
end
it "proceeds with instance termination" do
expect(@sidekiq_utility).to receive(:proceed_with_instance_termination)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/text_scrubber_spec.rb | spec/lib/utilities/text_scrubber_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe TextScrubber do
describe "#format" do
it "strips HTML tags and retain the spaces between paragraphs." do
text = " <h1>Hello world!</h1><p>I'm a \n\n text.<br>More text!</p> "
expect(TextScrubber.format(text)).to eq "Hello world!\n\nI'm a \n\n text.\nMore text!"
expect(TextScrubber.format(text).squish).to eq "Hello world! I'm a text. More text!"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/geo_ip_spec.rb | spec/lib/utilities/geo_ip_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GeoIp do
describe ".lookup" do
let(:result) { described_class.lookup(ip) }
describe "an IP to location match is not possible" do
let(:ip) { "127.0.0.1" }
it "returns a nil result" do
expect(result).to eq(nil)
end
end
describe "an IP to location match is possible" do
let(:ip) { "104.193.168.19" }
it "returns a result" do
expect(result.country_name).to eq("United States")
expect(result.country_code).to eq("US")
expect(result.region_name).to eq("CA")
expect(result.city_name).to eq("San Francisco")
expect(result.postal_code).to eq("94110")
expect(result.latitude).to eq(nil)
expect(result.longitude).to eq(nil)
end
end
describe "an IPv6 to location match is possible" do
let(:ip) { "2001:861:5bc0:cb60:500d:3535:e6a7:62a0" }
it "returns a result" do
expect(result.country_name).to eq("France")
expect(result.country_code).to eq("FR")
expect(result.city_name).to eq("Belfort")
expect(result.postal_code).to eq("90000")
expect(result.latitude).to eq(nil)
expect(result.longitude).to eq(nil)
end
end
describe "an IP to location match is possible but the underlying GEOIP has invalid UTF-8 in fields" do
let(:ip) { "104.193.168.19" }
before do
expect(GEOIP).to receive(:city).and_return(
double(
country: double({ name: "Unit\xB7ed States", iso_code: "U\xB7S" }),
most_specific_subdivision: double({ iso_code: "C\xB7A" }),
city: double({ name: "San F\xB7rancisco" }),
postal: double({ code: "941\xB703" }),
location: double({ latitude: "103\xB7103", longitude: "103\xB7103" })
)
)
end
it "returns a result" do
expect(result.country_name).to eq("Unit?ed States")
expect(result.country_code).to eq("U?S")
expect(result.region_name).to eq("C?A")
expect(result.city_name).to eq("San F?rancisco")
expect(result.postal_code).to eq("941?03")
expect(result.latitude).to eq("103?103")
expect(result.longitude).to eq("103?103")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/ffprobe_spec.rb | spec/lib/utilities/ffprobe_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Ffprobe do
describe "#parse" do
context "when a valid movie file is supplied" do
let(:ffprobe_parsed) do
Ffprobe.new(fixture_file_upload("sample.mov")).parse
end
expected_ffprobe_data = {
bit_rate: "27506",
duration: "4.483333",
height: 132,
r_frame_rate: "60/1",
width: 176
}
expected_ffprobe_data.each do |property, value|
it "has the correct value for #{property}" do
expect(ffprobe_parsed.public_send(property)).to eq value
end
end
end
context "when a video file with multiple audio streams encoded before the video stream is supplied" do
#
# The file has three streams:
# streams[0] is an audio track
# streams[1] is another audio track
# streams[2] is the video track
# These specs ensure that the order of streams does not matter and we select the video track correctly
#
let(:ffprobe_parsed) do
Ffprobe.new(file_fixture("video_with_multiple_audio_tracks.mov")).parse
end
expected_ffprobe_data = {
bit_rate: "34638",
duration: "1.016667",
height: 24,
r_frame_rate: "60/1",
width: 28
}
expected_ffprobe_data.each do |property, value|
it "has the correct value for #{property}" do
expect(ffprobe_parsed.public_send(property)).to eq value
end
end
end
context "when an invalid movie file is supplied" do
it "raises a NoMethodError" do
expect { Ffprobe.new(fixture_file("sample.epub")).parse }.to raise_error(NoMethodError)
end
end
context "when a non-existent file is supplied" do
it "raises an ArgumentError" do
file_path = File.join(Rails.root, "spec", "sample_data", "non-existent.mov")
expect { Ffprobe.new(file_path).parse }.to raise_error(ArgumentError, "File not found #{file_path}")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/lib/utilities/feature_spec.rb | spec/lib/utilities/feature_spec.rb | # frozen_string_literal: true
RSpec.describe Feature do
let(:user1) { create(:user) }
let(:user2) { create(:user) }
let(:feature_name) { :new_feature }
describe "#activate" do
it "activates the feature for everyone" do
expect do
described_class.activate(feature_name)
end.to change { Flipper.enabled?(feature_name) }.from(false).to(true)
end
end
describe "#activate_user" do
it "activates the feature for the actor" do
expect do
described_class.activate_user(feature_name, user1)
expect(Flipper.enabled?(feature_name)).to eq(false)
end.to change { Flipper.enabled?(feature_name, user1) }.from(false).to(true)
end
end
describe "#deactivate" do
before { Flipper.enable(feature_name) }
it "deactivates the feature for everyone" do
expect do
described_class.deactivate(feature_name)
end.to change { Flipper.enabled?(feature_name, user1) }.from(true).to(false)
.and change { Flipper.enabled?(feature_name, user2) }.from(true).to(false)
.and change { Flipper.enabled?(feature_name) }.from(true).to(false)
end
end
describe "#deactivate_user" do
before { Flipper.enable_actor(feature_name, user1) }
before { Flipper.enable_actor(feature_name, user2) }
it "deactivates the feature for the actor" do
expect do
described_class.deactivate_user(feature_name, user1)
expect(Flipper.enabled?(feature_name, user2)).to eq(true)
end.to change { Flipper.enabled?(feature_name, user1) }.from(true).to(false)
end
end
describe "#activate_percentage" do
it "activates the feature for the specified percentage of actors" do
expect do
described_class.activate_percentage(feature_name, 100)
end.to change { Flipper[feature_name].percentage_of_actors_value }.from(0).to(100)
end
end
describe "#deactivate_percentage" do
before { described_class.activate_percentage(feature_name, 100) }
it "deactivates the percentage rollout" do
expect do
described_class.deactivate_percentage(feature_name)
end.to change { Flipper[feature_name].percentage_of_actors_value }.from(100).to(0)
end
end
describe "#active?" do
context "when an actor is passed" do
it "returns true if the feature is active for the actor" do
Flipper.enable_actor(feature_name, user1)
expect(described_class.active?(feature_name, user1)).to eq(true)
end
it "returns false if the feature is not active for the actor" do
expect(described_class.active?(feature_name, user1)).to eq(false)
end
end
context "when no actor is passed" do
it "returns true if the feature is active for everyone" do
Flipper.enable(feature_name)
expect(described_class.active?(feature_name)).to eq(true)
end
it "returns false if the feature is not active for everyone" do
expect(described_class.active?(feature_name)).to eq(false)
end
end
end
describe "#inactive?" do
context "when an actor is passed" do
it "returns false if the feature is active for the actor" do
Flipper.enable_actor(feature_name, user1)
expect(described_class.inactive?(feature_name, user1)).to eq(false)
end
it "returns true if the feature is not active for the actor" do
expect(described_class.inactive?(feature_name, user1)).to eq(true)
end
end
context "when no actor is passed" do
it "returns false if the feature is active for everyone" do
Flipper.enable(feature_name)
expect(described_class.inactive?(feature_name)).to eq(false)
end
it "returns true if the feature is not active for everyone" do
expect(described_class.inactive?(feature_name)).to eq(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/lib/extras/bugsnag_handle_sidekiq_retries_callback_spec.rb | spec/lib/extras/bugsnag_handle_sidekiq_retries_callback_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "BugsnagHandleSidekiqRetriesCallback" do
before do
@callback = BugsnagHandleSidekiqRetriesCallback
end
it "ignores report when it is not the last job run attempt" do
report = double(meta_data: { sidekiq: { msg: { "retry" => 1 } } })
expect(report).to receive(:ignore!)
@callback.call(report)
report = double(meta_data: { sidekiq: { msg: { "retry" => 2, "retry_count" => 0 } } })
expect(report).to receive(:ignore!)
@callback.call(report)
end
it "does not ignore report it is the last job run attempt" do
# When retry = retry_count + 1, the job will go to the dead queue if it fails:
# we want to notify bugsnag of errors at this point.
report = double(meta_data: { sidekiq: { msg: { "retry" => 1, "retry_count" => 0 } } })
expect(report).not_to receive(:ignore!)
@callback.call(report)
# retry_count is nil on the first attempt.
# If this is the first attempt AND retry = 0, we don't want to ignore, as it's the last attempt.
report = double(meta_data: { sidekiq: { msg: { "retry" => 0 } } })
expect(report).not_to receive(:ignore!)
@callback.call(report)
end
it "does not ignore report when 'retry' is not configured" do
report = double(meta_data: { sidekiq: { msg: {} } })
expect(report).not_to receive(:ignore!)
@callback.call(report)
end
it "does not ignore report when it does not come from sidekiq" do
report = double(meta_data: {})
expect(report).not_to receive(:ignore!)
@callback.call(report)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/config/mysql_missing_table_handler_spec.rb | spec/config/mysql_missing_table_handler_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe "MySQL missing table handler" do
it "retries query if table is missing" do
client = ActiveRecord::Base.connection_db_config
.configuration_hash
.slice(*%i[host username password database port socket encoding])
.then { |conf| Mysql2::Client.new(conf) }
stub_const("Mysql2::Client::MISSING_TABLE_GRACE_PERIOD", 2)
client.query("DROP TABLE IF EXISTS `foo`, `bar`")
client.query("CREATE TABLE `bar` (id int)")
client.query("INSERT INTO `bar`(id) VALUES (1),(2),(3)")
Thread.new do
sleep 1
client.query("RENAME TABLE `bar` TO `foo`")
end
values = nil
expect do
result = client.query("SELECT id FROM `foo`")
values = result.map { |row| row["id"].to_i }
end.to output(/Error: missing table, retrying in/).to_stderr
expect(values).to contain_exactly(1, 2, 3)
ensure
client.query("DROP TABLE IF EXISTS `foo`, `bar`")
client.close rescue nil
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/config/rendering_extension_spec.rb | spec/config/rendering_extension_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "RenderingExtension" do
describe "#custom_context" do
let(:pundit_user) { SellerContext.new(user:, seller:) }
let(:stubbed_view_context) { StubbedViewContext.new(pundit_user) }
let(:custom_context) { RenderingExtension.custom_context(stubbed_view_context) }
context "when user is not logged in" do
let(:user) { nil }
let(:seller) { nil }
it "generates correct context" do
expect(custom_context).to eq(
{
design_settings: {
font: {
name: "ABC Favorit",
url: stubbed_view_context.font_url("ABCFavorit-Regular.woff2")
}
},
domain_settings: {
scheme: PROTOCOL,
app_domain: DOMAIN,
root_domain: ROOT_DOMAIN,
short_domain: SHORT_DOMAIN,
discover_domain: DISCOVER_DOMAIN,
third_party_analytics_domain: THIRD_PARTY_ANALYTICS_DOMAIN,
api_domain: API_DOMAIN,
},
user_agent_info: { is_mobile: true },
logged_in_user: nil,
current_seller: nil,
csp_nonce: SecureHeaders.content_security_policy_script_nonce(stubbed_view_context.request),
locale: "en-US",
feature_flags: {
require_email_typo_acknowledgment: false
}
}
)
end
end
context "when user is logged in" do
context "with admin role for seller" do
let(:seller) { create(:named_seller) }
let(:admin_for_seller) { create(:user, username: "adminforseller") }
let(:pundit_user) { SellerContext.new(user: admin_for_seller, seller:) }
before do
create(:team_membership, user: admin_for_seller, seller:, role: TeamMembership::ROLE_ADMIN)
end
it "generates correct context" do
expect(custom_context).to eq(
{
design_settings: {
font: {
name: "ABC Favorit",
url: stubbed_view_context.font_url("ABCFavorit-Regular.woff2")
}
},
domain_settings: {
scheme: PROTOCOL,
app_domain: DOMAIN,
root_domain: ROOT_DOMAIN,
short_domain: SHORT_DOMAIN,
discover_domain: DISCOVER_DOMAIN,
third_party_analytics_domain: THIRD_PARTY_ANALYTICS_DOMAIN,
api_domain: API_DOMAIN,
},
user_agent_info: { is_mobile: true },
logged_in_user: {
id: admin_for_seller.external_id,
email: admin_for_seller.email,
name: admin_for_seller.name,
avatar_url: admin_for_seller.avatar_url,
confirmed: true,
team_memberships: UserMembershipsPresenter.new(pundit_user:).props,
policies: {
affiliate_requests_onboarding_form: {
update: true,
},
direct_affiliate: {
create: true,
update: true,
},
collaborator: {
create: true,
update: true,
},
product: {
create: true,
},
product_review_response: {
update: true,
},
balance: {
index: true,
export: true,
},
checkout_offer_code: {
create: true,
},
checkout_form: {
update: true,
},
upsell: {
create: true,
},
settings_payments_user: {
show: true,
},
settings_profile: {
manage_social_connections: false,
update: true,
update_username: false
},
settings_third_party_analytics_user: {
update: true
},
installment: {
create: true,
},
workflow: {
create: true,
},
utm_link: {
index: false,
},
community: {
index: false,
}
},
is_gumroad_admin: false,
is_impersonating: true,
lazy_load_offscreen_discover_images: false,
},
current_seller: UserPresenter.new(user: seller).as_current_seller,
csp_nonce: SecureHeaders.content_security_policy_script_nonce(stubbed_view_context.request),
locale: "en-US",
feature_flags: {
require_email_typo_acknowledgment: false
}
}
)
end
end
end
end
private
class StubbedViewContext
attr_reader :pundit_user, :request
def initialize(pundit_user)
@pundit_user = pundit_user
@request = ActionDispatch::TestRequest.create
end
def controller
OpenStruct.new(is_mobile?: true, impersonating?: true, http_accept_language: HttpAcceptLanguage::Parser.new(""))
end
def font_url(font_name)
ActionController::Base.helpers.font_url(font_name)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/generate_fees_by_creator_location_report_job_spec.rb | spec/sidekiq/generate_fees_by_creator_location_report_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GenerateFeesByCreatorLocationReportJob 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 argument 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/creator-fees-reporting-spec-#{SecureRandom.hex(18)}.zip")
end
before do
virginia_product = nil
washington_product = nil
california_product = nil
australia_product = nil
singapore_product = nil
spain_product = nil
travel_to(Time.find_zone("UTC").local(2022, 7, 1)) do
virginia_creator = create(:user).tap do |creator|
creator.fetch_or_build_user_compliance_info.dup_and_save! do |new_compliance_info|
new_compliance_info.state = "VA"
new_compliance_info.country = "United States"
end
end
virginia_product = create(:product, user: virginia_creator, price_cents: 100_00, native_type: "digital")
washington_creator = create(:user).tap do |creator|
creator.fetch_or_build_user_compliance_info.dup_and_save! do |new_compliance_info|
new_compliance_info.state = "WA"
new_compliance_info.country = "United States"
end
end
washington_product = create(:product, user: washington_creator, price_cents: 100_00, native_type: "digital")
california_creator = create(:user).tap do |creator|
creator.fetch_or_build_user_compliance_info.dup_and_save! do |new_compliance_info|
new_compliance_info.state = "CA"
new_compliance_info.country = "United States"
end
end
california_product = create(:product, user: california_creator, price_cents: 100_00, native_type: "digital")
australia_creator = create(:user).tap do |creator|
creator.fetch_or_build_user_compliance_info.dup_and_save! do |new_compliance_info|
new_compliance_info.country = "Australia"
end
end
australia_product = create(:product, user: australia_creator, price_cents: 100_00, native_type: "digital")
singapore_creator = create(:compliant_user).tap do |creator|
creator.fetch_or_build_user_compliance_info.dup_and_save! do |new_compliance_info|
new_compliance_info.country = "Singapore"
end
end
singapore_product = create(:product, :recommendable, user: singapore_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: virginia_product, country: "United States", zip_code: "22207")
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: washington_product, country: "United States", zip_code: "94016")
create(:purchase_in_progress, link: california_product, country: "United States", zip_code: "94016")
create(:purchase_in_progress, link: australia_product, country: "United States", zip_code: "94016")
create(:purchase_in_progress, link: singapore_product, was_product_recommended: true, country: "United States", zip_code: "94016")
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, 10)) do
create(:purchase_in_progress, link: california_product, country: "United States", zip_code: "94016")
create(:purchase_in_progress, link: australia_product, country: "United States", zip_code: "94016")
create(:purchase_in_progress, link: singapore_product, was_product_recommended: true, country: "United States", zip_code: "94016")
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, 20)) do
create(:purchase_in_progress, link: australia_product, country: "United States", zip_code: "94016")
create(:purchase_in_progress, link: singapore_product, was_product_recommended: true, country: "United States", zip_code: "94016")
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, 31)) do
create(:purchase_in_progress, link: singapore_product, was_product_recommended: true, country: "United States", zip_code: "94016")
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: spain_product, country: "United States", zip_code: "94016")
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 creator fees by location" 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", "Fee 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).to eq([
["Month", "Creator Country", "Creator State", "Gumroad Fees"],
["August 2022", "United States", "Washington", "1370"],
["August 2022", "United States", "California", "2740"],
["August 2022", "United States", "", "4110"],
["August 2022", "Australia", "", "4110"],
["August 2022", "Singapore", "", "12000"]
])
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_currencies_worker_spec.rb | spec/sidekiq/update_currencies_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpdateCurrenciesWorker, :vcr do
describe "#perform" do
before do
@worker_instance = described_class.new
end
it "updates currencies for current date" do
@worker_instance.currency_namespace.set("AUD", "0.1111")
expect(@worker_instance.get_rate("AUD")).to eq("0.1111")
@worker_instance.perform
# In test this is a fixed rate read from a file
expect(@worker_instance.get_rate("AUD")).to eq("0.969509")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/sync_stuck_purchases_job_spec.rb | spec/sidekiq/sync_stuck_purchases_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SyncStuckPurchasesJob, :vcr do
describe "#perform" do
let(:product) { create(:product) }
before do
stub_const("GUMROAD_ADMIN_ID", create(:admin_user).id)
end
it "does not sync any purchases if there are none in progress" do
create(:failed_purchase, link: product, created_at: 12.hours.ago)
create(:purchase, link: product, created_at: 24.hours.ago)
expect_any_instance_of(Purchase).to_not receive(:sync_status_with_charge_processor)
described_class.new.perform
end
it "does not sync any in progress purchases if they are outside of the query time range" do
create(:purchase_in_progress, link: product, created_at: 4.days.ago)
create(:purchase_in_progress, link: product, created_at: 2.hours.ago)
expect_any_instance_of(Purchase).to_not receive(:sync_status_with_charge_processor)
described_class.new.perform
end
it "does not sync an in progress purchases if it is an off session charge on an Indian card created less than 26 hours ago" do
stuck_in_progress_purchase_that_would_succeed_if_synced = travel_to(Time.current - 12.hours) do
purchase = create(:purchase, link: product, purchase_state: "in_progress", chargeable: create(:chargeable))
purchase.process!
purchase
end
allow_any_instance_of(Purchase).to receive(:is_an_off_session_charge_on_indian_card?).and_return(true)
expect_any_instance_of(Purchase).to_not receive(:sync_status_with_charge_processor)
expect(stuck_in_progress_purchase_that_would_succeed_if_synced.in_progress?).to eq(true)
described_class.new.perform
expect(stuck_in_progress_purchase_that_would_succeed_if_synced.reload.in_progress?).to eq(true)
end
it "syncs the in progress free purchase and does nothing if the new purchase state is successful and there are no subsequent successful purchases" do
stuck_in_progress_free_purchase_that_will_succeed_when_synced = travel_to(Time.current - 12.hours) do
offer_code = create(:offer_code, products: [product], amount_cents: 100)
purchase = create(:free_purchase, link: product, purchase_state: "in_progress", offer_code:)
purchase.process!
purchase
end
expect(stuck_in_progress_free_purchase_that_will_succeed_when_synced.in_progress?).to be(true)
described_class.new.perform
expect(stuck_in_progress_free_purchase_that_will_succeed_when_synced.reload.successful?).to eq(true)
expect(stuck_in_progress_free_purchase_that_will_succeed_when_synced.refunded?).to eq(false)
end
it "syncs the in progress purchase and does nothing if the new purchase state is successful and there are no subsequent successful purchases" do
stuck_in_progress_purchase_that_will_succeed_when_synced = travel_to(Time.current - 12.hours) do
purchase = create(:purchase, link: product, purchase_state: "in_progress", chargeable: create(:chargeable))
purchase.process!
purchase
end
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.in_progress?).to eq(true)
described_class.new.perform
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.reload.successful?).to eq(true)
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.refunded?).to eq(false)
end
it "syncs the in progress which is an off session charge on an Indian card created more than 26 hours ago and does nothing if the new purchase state is successful and there are no subsequent successful purchases" do
stuck_in_progress_purchase_that_will_succeed_when_synced = travel_to(Time.current - 27.hours) do
purchase = create(:purchase, link: product, purchase_state: "in_progress", chargeable: create(:chargeable))
purchase.process!
purchase
end
allow_any_instance_of(Purchase).to receive(:is_an_off_session_charge_on_indian_card?).and_return(true)
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.in_progress?).to eq(true)
described_class.new.perform
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.reload.successful?).to eq(true)
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.refunded?).to eq(false)
end
context "when there is a subsequent successful purchase" do
let!(:successful_purchase) { create(:purchase, link: product) }
it "syncs the in progress purchase and does nothing if the new purchase state is failed" do
stuck_in_progress_purchase_that_will_fail_when_synced = travel_to(Time.current - 12.hours) do
purchase = create(:purchase, link: product, email: successful_purchase.email, purchase_state: "in_progress", chargeable: create(:chargeable_success_charge_decline))
purchase.process!
purchase.stripe_transaction_id = nil
purchase.save!
purchase
end
expect(stuck_in_progress_purchase_that_will_fail_when_synced.in_progress?).to eq(true)
expect_any_instance_of(Purchase).to_not receive(:refund_and_save!)
described_class.new.perform
expect(stuck_in_progress_purchase_that_will_fail_when_synced.reload.failed?).to eq(true)
end
it "syncs the in progress purchase and then refunds it if the new purchase state is successful" do
allow_any_instance_of(User).to receive(:unpaid_balance_cents).and_return(100_00)
stuck_in_progress_purchase_that_will_succeed_when_synced = travel_to(Time.current - 12.hours) do
purchase = create(:purchase, link: product, email: successful_purchase.email, purchase_state: "in_progress", chargeable: create(:chargeable))
purchase.process!
purchase
end
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.in_progress?).to eq(true)
described_class.new.perform
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.reload.successful?).to eq(true)
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.refunded?).to eq(true)
end
it "syncs the in progress free purchase and then does not refund it because it is free if the new purchase state is successful" do
stuck_in_progress_free_purchase_that_will_succeed_when_synced = travel_to(Time.current - 12.hours) do
offer_code = create(:offer_code, products: [product], amount_cents: 100)
purchase = create(:free_purchase, link: product, email: successful_purchase.email, purchase_state: "in_progress", offer_code:)
purchase.process!
purchase
end
expect(stuck_in_progress_free_purchase_that_will_succeed_when_synced.in_progress?).to be(true)
described_class.new.perform
expect(stuck_in_progress_free_purchase_that_will_succeed_when_synced.reload.successful?).to eq(true)
expect(stuck_in_progress_free_purchase_that_will_succeed_when_synced.refunded?).to eq(false)
end
end
context "when there is a subsequent successful purchase for a variant of the product" do
let(:product_with_digital_versions) { create(:product_with_digital_versions) }
let!(:successful_purchase_of_variant) { create(:purchase, link: product_with_digital_versions, variant_attributes: [product_with_digital_versions.variants.last]) }
it "syncs the in progress purchase and does nothing if the new purchase state is failed" do
stuck_in_progress_purchase_that_will_fail_when_synced = travel_to(Time.current - 12.hours) do
purchase = create(:purchase, link: product_with_digital_versions, email: successful_purchase_of_variant.email, purchase_state: "in_progress", variant_attributes: [product_with_digital_versions.variants.last], chargeable: create(:chargeable_success_charge_decline))
purchase.process!
purchase.stripe_transaction_id = nil
purchase.save!
purchase
end
expect(stuck_in_progress_purchase_that_will_fail_when_synced.in_progress?).to eq(true)
described_class.new.perform
expect(stuck_in_progress_purchase_that_will_fail_when_synced.reload.failed?).to eq(true)
end
it "syncs the in progress purchase and then refunds it if the new purchase state is successful for the same variant of the product" do
allow_any_instance_of(User).to receive(:unpaid_balance_cents).and_return(100_00)
stuck_in_progress_purchase_that_will_succeed_when_synced = travel_to(Time.current - 12.hours) do
purchase = create(:purchase, link: product_with_digital_versions, email: successful_purchase_of_variant.email, purchase_state: "in_progress", variant_attributes: [product_with_digital_versions.variants.last], chargeable: create(:chargeable))
purchase.process!
purchase
end
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.in_progress?).to eq(true)
described_class.new.perform
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.reload.successful?).to eq(true)
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.refunded?).to eq(true)
end
it "syncs the in progress purchase and then does NOT refund it if the new purchase state is successful for a different variant of the product" do
stuck_in_progress_purchase_that_will_succeed_when_synced = travel_to(Time.current - 12.hours) do
purchase = create(:purchase, link: product_with_digital_versions, email: successful_purchase_of_variant.email, purchase_state: "in_progress", variant_attributes: [product_with_digital_versions.variants.first], chargeable: create(:chargeable))
purchase.process!
purchase
end
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.in_progress?).to eq(true)
expect_any_instance_of(Purchase).to_not receive(:refund_and_save!)
described_class.new.perform
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.reload.successful?).to eq(true)
expect(stuck_in_progress_purchase_that_will_succeed_when_synced.refunded?).to eq(false)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/order_review_reminder_job_spec.rb | spec/sidekiq/order_review_reminder_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe OrderReviewReminderJob do
let(:order) { create(:order) }
let(:eligible_purchase) { create(:purchase, order: order) }
let(:ineligible_purchase) { create(:purchase, order: order) }
before do
allow(Order).to receive(:find).with(order.id).and_return(order)
allow(eligible_purchase).to receive(:eligible_for_review_reminder?).and_return(true)
allow(ineligible_purchase).to receive(:eligible_for_review_reminder?).and_return(false)
end
context "when there are no eligible purchases" do
before do
allow(order).to receive(:purchases).and_return([ineligible_purchase])
end
it "does not enqueue any emails" do
expect do
described_class.new.perform(order.id)
end.not_to have_enqueued_mail(CustomerLowPriorityMailer)
end
end
context "when there is one eligible purchase" do
before do
allow(order).to receive(:purchases).and_return([eligible_purchase, ineligible_purchase])
end
it "enqueues a single purchase review reminder once" do
expect do
described_class.new.perform(order.id)
described_class.new.perform(order.id)
end.to have_enqueued_mail(CustomerLowPriorityMailer, :purchase_review_reminder)
.with(eligible_purchase.id)
.on_queue(:low)
.once
end
end
context "when there are multiple eligible purchases" do
let(:another_eligible_purchase) { create(:purchase, order: order) }
before do
allow(order).to receive(:purchases).and_return([eligible_purchase, another_eligible_purchase])
allow(another_eligible_purchase).to receive(:eligible_for_review_reminder?).and_return(true)
end
it "enqueues an order review reminder once" do
expect do
described_class.new.perform(order.id)
described_class.new.perform(order.id)
end.to have_enqueued_mail(CustomerLowPriorityMailer, :order_review_reminder)
.with(order.id)
.on_queue(:low)
.once
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_sendgrid_event_job_spec.rb | spec/sidekiq/handle_sendgrid_event_job_spec.rb | # frozen_string_literal: true
describe HandleSendgridEventJob do
describe ".perform" do
context "when the event type is not supported" do
let(:params) do
{
"_json" => [
{
"event" => "processed",
"type" => "CustomerMailer.receipt",
"identifier" => "[1]"
}
]
}
end
it "does nothing" do
expect(HandleEmailEventInfo::ForInstallmentEmail).not_to receive(:perform)
expect(HandleEmailEventInfo::ForReceiptEmail).not_to receive(:perform)
expect(HandleEmailEventInfo::ForAbandonedCartEmail).not_to receive(:perform)
described_class.new.perform(params)
end
end
context "when the event data is invalid" do
let(:params) do
{
"_json" => [
{
"foo" => "bar",
}
]
}
end
it "does nothing" do
expect(HandleEmailEventInfo::ForInstallmentEmail).not_to receive(:perform)
expect(HandleEmailEventInfo::ForReceiptEmail).not_to receive(:perform)
expect(HandleEmailEventInfo::ForAbandonedCartEmail).not_to receive(:perform)
described_class.new.perform(params)
end
end
it "handles events for abandoned cart emails" do
params = { "_json" => [{ "event" => "delivered", "mailer_class" => "CustomerMailer", "mailer_method" => "abandoned_cart", "mailer_args" => "[3783, {\"5296\"=>[153758, 163413], \"5644\"=>[163413]}]" }] }
expect(HandleEmailEventInfo::ForInstallmentEmail).not_to receive(:perform)
expect(HandleEmailEventInfo::ForReceiptEmail).not_to receive(:perform)
expect(HandleEmailEventInfo::ForAbandonedCartEmail).to receive(:perform).with(an_instance_of(SendgridEventInfo))
described_class.new.perform(params)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/handle_payout_reversed_worker_spec.rb | spec/sidekiq/handle_payout_reversed_worker_spec.rb | # frozen_string_literal: true
describe HandlePayoutReversedWorker do
describe "#perform" do
let(:payment) { create(:payment) }
let(:reversing_payout_id) { "reversing-payout-id" }
let(:stripe_account_id) { "stripe-account-id" }
let(:reversing_payout_status) { raise "define `reversing_payout_status`" }
let(:balance_transaction_status) { raise "define `balance_transaction_status`" }
let(:reversing_stripe_payout) do
{
object: "payout",
id: "reversal_payout_id",
failure_code: nil,
automatic: false,
status: reversing_payout_status,
balance_transaction: {
status: balance_transaction_status
}
}.deep_stringify_keys
end
before do
allow(Stripe::Payout).to receive(:retrieve).with(hash_including({ id: reversing_payout_id }), anything).and_return(reversing_stripe_payout)
end
context "reversing payout succeeds" do
let(:reversing_payout_status) { "paid" }
let(:balance_transaction_status) { "available" }
it "calls the StripePayoutProcessor#handle_stripe_event_payout_reversed" do
expect(StripePayoutProcessor).to receive(:handle_stripe_event_payout_reversed).with(payment, reversing_payout_id)
HandlePayoutReversedWorker.new.perform(payment.id, reversing_payout_id, stripe_account_id)
end
end
context "reversing payout fails" do
let(:reversing_payout_status) { "failed" }
let(:balance_transaction_status) { "available" }
it "does nothing and does not raise an error" do
expect(StripePayoutProcessor).not_to receive(:handle_stripe_event_payout_reversed)
HandlePayoutReversedWorker.new.perform(payment.id, reversing_payout_id, stripe_account_id)
end
end
context "reversing payout isn't finalized" do
let(:reversing_payout_status) { "paid" }
let(:balance_transaction_status) { "pending" }
it "raises an error", :vcr, :sidekiq_inline do
expect do
HandlePayoutReversedWorker.new.perform(payment.id, reversing_payout_id, stripe_account_id)
end.to raise_error(RuntimeError, /Timed out waiting for reversing payout to become finalized/)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/post_to_ping_endpoints_worker_spec.rb | spec/sidekiq/post_to_ping_endpoints_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PostToPingEndpointsWorker, :vcr do
before do
@user = create(:user, notification_endpoint: "http://notification.com")
@product = create(:product, user: @user, unique_permalink: "Iqw", price_cents: 500)
@default_params = lambda do |purchase|
link = purchase.link
{
seller_id: ObfuscateIds.encrypt(link.user.id),
product_id: ObfuscateIds.encrypt(link.id),
product_name: link.name,
permalink: link.unique_permalink,
product_permalink: link.long_url,
short_product_id: link.unique_permalink,
email: purchase.email,
price: purchase.price_cents,
gumroad_fee: purchase.fee_cents,
currency: purchase.link.price_currency_type,
quantity: purchase.quantity,
is_gift_receiver_purchase: false,
order_number: purchase.external_id_numeric,
sale_id: purchase.external_id,
sale_timestamp: purchase.created_at.as_json,
resource_name: ResourceSubscription::SALE_RESOURCE_NAME,
refunded: false,
disputed: false,
dispute_won: false,
discover_fee_charged: purchase.was_discover_fee_charged,
can_contact: purchase.can_contact,
referrer: purchase.referrer,
card: {
bin: nil,
expiry_month: purchase.card_expiry_month,
expiry_year: purchase.card_expiry_year,
type: purchase.card_type,
visual: purchase.card_visual
}
}
end
@http_double = double
allow(@http_double).to receive(:success?).and_return(true)
allow(@http_double).to receive(:code).and_return(200)
end
it "enqueues job PostToIndividualPingEndpointWorker with the correct parameters" do
purchase = create(:purchase, link: @product, price_cents: 500)
PostToPingEndpointsWorker.new.perform(purchase.id, "{\"first_param\":\"test\",\"second_param\":\"flkdjaf\"}")
params = @default_params.call(purchase).merge(
url_params: "{\"first_param\":\"test\",\"second_param\":\"flkdjaf\"}"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
it "includes a license key if the purchase has one" do
link = create(:product, user: @user, unique_permalink: "lic", is_licensed: true)
purchase = create(:purchase, link:, price_cents: 500)
create(:license, link:, purchase:)
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
product_name: link.name,
permalink: "lic",
product_permalink: link.long_url,
license_key: purchase.license.serial
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
it "includes gift related information if the purchase is a gift" do
gift = create(:gift, gifter_email: "gifter@gumroad.com", giftee_email: "giftee@gumroad.com", link: @product)
gifter_purchase = create(:purchase, link: @product, price_cents: 500, email: "gifter@gumroad.com", is_gift_sender_purchase: true)
giftee_purchase = create(:purchase, link: @product,
email: "giftee@gumroad.com",
price_cents: 0,
is_gift_receiver_purchase: true,
purchase_state: "gift_receiver_purchase_successful")
gift.gifter_purchase = gifter_purchase
gift.giftee_purchase = giftee_purchase
gift.mark_successful
gift.save!
PostToPingEndpointsWorker.new.perform(giftee_purchase.id, nil)
params = @default_params.call(giftee_purchase).merge(
email: "giftee@gumroad.com",
price: 0,
gift_price: 500,
is_gift_receiver_purchase: true,
gifter_email: gifter_purchase.email
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
it "includes a purchaser id if there is one for the purchase" do
purchaser = create(:user)
purchase = create(:purchase, link: @product, price_cents: 500, purchaser:)
PostToPingEndpointsWorker.new.perform(purchase.id, "{\"first_param\":\"test\",\"second_param\":\"flkdjaf\"}")
params = @default_params.call(purchase).merge(
purchaser_id: purchaser.external_id,
url_params: "{\"first_param\":\"test\",\"second_param\":\"flkdjaf\"}"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
it "includes the sku id in the post if there's a sku" do
@product.skus_enabled = true
@product.is_physical = true
@product.require_shipping = true
@product.shipping_destinations << ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0)
@product.save!
purchase = create(:physical_purchase, link: @product, price_cents: 500)
purchase.variant_attributes << create(:sku)
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
full_name: "barnabas",
street_address: "123 barnabas street",
country: "United States",
state: "CA",
zip_code: "94114",
city: "barnabasville",
shipping_information: {
full_name: "barnabas",
street_address: "123 barnabas street",
country: "United States",
state: "CA",
zip_code: "94114",
city: "barnabasville"
},
sku_id: purchase.sku.external_id,
variants: { "Version" => "Large" },
shipping_rate: 0
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
it "includes the custom sku in the post if there's a sku" do
@product.skus_enabled = true
@product.is_physical = true
@product.require_shipping = true
@product.shipping_destinations << ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0)
@product.save!
purchase = create(:physical_purchase, link: @product, price_cents: 500)
purchase.variant_attributes << create(:sku)
Sku.last.update_attribute(:custom_sku, "CUSTOMIZE")
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
full_name: "barnabas",
street_address: "123 barnabas street",
country: "United States",
state: "CA",
zip_code: "94114",
city: "barnabasville",
shipping_information: {
full_name: "barnabas",
street_address: "123 barnabas street",
country: "United States",
state: "CA",
zip_code: "94114",
city: "barnabasville"
},
sku_id: "CUSTOMIZE",
original_sku_id: Sku.last.external_id,
variants: { "Version" => "Large" },
shipping_rate: 0
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
it "includes the sku id in the post if the product is sku-enabled and doesn't have a sku" do
@product.skus_enabled = true
@product.is_physical = true
@product.require_shipping = true
@product.shipping_destinations << ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0)
@product.save!
purchase = create(:physical_purchase, link: @product, price_cents: 500)
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
full_name: "barnabas",
street_address: "123 barnabas street",
country: "United States",
state: "CA",
zip_code: "94114",
city: "barnabasville",
shipping_information: {
full_name: "barnabas",
street_address: "123 barnabas street",
country: "United States",
state: "CA",
zip_code: "94114",
city: "barnabasville"
},
sku_id: purchase.sku_custom_name_or_external_id,
shipping_rate: 0
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
describe "shipping information" do
it "makes a post with the correct body" do
link = create(:product, user: @user, unique_permalink: "Klm", require_shipping: true)
purchase = create(:purchase, link:, price_cents: 500, full_name: "Edgar Gumstein", street_address: "123 Gum Road",
city: "Montgomery", state: "Alabama", country: "United States", zip_code: "12345")
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
product_name: link.name,
product_permalink: link.long_url,
permalink: "Klm",
shipping_information: {
full_name: "Edgar Gumstein",
street_address: "123 Gum Road",
city: "Montgomery",
state: "Alabama",
country: "United States",
zip_code: "12345"
},
full_name: "Edgar Gumstein",
street_address: "123 Gum Road",
city: "Montgomery",
state: "Alabama",
country: "United States",
zip_code: "12345"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
end
describe "quantity" do
it "makes a post with the correct body" do
link = create(:physical_product, user: @user, unique_permalink: "Klm", require_shipping: true)
purchase = create(:purchase, link:, price_cents: 500, full_name: "Edgar Gumstein", street_address: "123 Gum Road",
city: "Montgomery", state: "Alabama", country: "United States", zip_code: "12345", quantity: 5)
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
product_name: link.name,
product_permalink: link.long_url,
permalink: "Klm",
quantity: 5,
shipping_information: {
full_name: "Edgar Gumstein",
street_address: "123 Gum Road",
city: "Montgomery",
state: "Alabama",
country: "United States",
zip_code: "12345"
},
full_name: "Edgar Gumstein",
street_address: "123 Gum Road",
city: "Montgomery",
state: "Alabama",
country: "United States",
zip_code: "12345",
shipping_rate: 0,
sku_id: "pid_#{link.external_id}"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
end
describe "buyer ip country" do
it "makes a post with the correct body" do
link = create(:product, user: @user, unique_permalink: "Klm")
purchase = create(:purchase, link:, price_cents: 500, ip_country: "United States")
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
product_name: link.name,
product_permalink: link.long_url,
permalink: "Klm",
ip_country: "United States"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
end
describe "custom_fields" do
it "makes the request to the endpoint with the correct paramters" do
purchase = create(
:purchase,
link: @product,
price_cents: 500,
purchase_custom_fields: [
build(:purchase_custom_field, name: "pet_name", value: "woofy"),
build(:purchase_custom_field, name: "species", value: "dog")
]
)
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
pet_name: "woofy",
species: "dog",
custom_fields: {
"pet_name" => "woofy",
"species" => "dog"
}
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
end
describe "offer_code" do
it "makes request to the endpoint with the correct parameters" do
purchase = create(:purchase, link: @product, price_cents: 500)
offer_code = create(:offer_code, products: [@product], code: "thanks9")
offer_code.purchases << purchase
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
offer_code: "thanks9"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
end
describe "recurring charge" do
it "makes request to endpoint with the correct parameters" do
purchase = create(:purchase, link: @product, price_cents: 500)
subscription = create(:subscription, link: @product)
subscription.purchases << purchase
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
is_recurring_charge: true,
recurrence: subscription.recurrence,
subscription_id: subscription.external_id
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
end
describe "refund resource" do
it "does not send a ping to the user's notification_endpoint about sale refund", :sidekiq_inline do
purchase = create(:purchase, link: @product, price_cents: 500, stripe_refunded: true)
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::REFUNDED_RESOURCE_NAME)
expect(params[:refunded]).to be(true)
expect(params[:refunded]).to be(true)
expect(HTTParty).not_to receive(:post).with(@user.notification_endpoint, timeout: 5, body: params)
PostToPingEndpointsWorker.new.perform(purchase.id, nil, ResourceSubscription::REFUNDED_RESOURCE_NAME)
end
end
describe "cancellation resource" do
it "does not send a ping to the user's notification_endpoint about subscription cancellation", :sidekiq_inline do
purchase = create(:membership_purchase, link: @product, price_cents: 500)
subscription = create(:subscription, link: @product, cancelled_at: Time.current, user_requested_cancellation_at: Time.current)
subscription.purchases << purchase
params = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:cancelled]).to be(true)
expect(HTTParty).not_to receive(:post).with(@user.notification_endpoint, timeout: 5, body: params)
PostToPingEndpointsWorker.new.perform(nil, nil, ResourceSubscription::CANCELLED_RESOURCE_NAME, subscription.id)
end
end
describe "resource subscription" do
before do
@product = create(:product, user: @user, unique_permalink: "abc")
@app = create(:oauth_application, owner: create(:user))
@token = create("doorkeeper/access_token", application: @app, resource_owner_id: @user.id, scopes: "view_sales")
@resource_subscription = create(:resource_subscription, oauth_application: @app, user: @user)
@refunded_resource_subscription = create(:resource_subscription, oauth_application: @app, user: @user,
resource_name: ResourceSubscription::REFUNDED_RESOURCE_NAME)
@cancelled_resource_subscription = create(:resource_subscription, oauth_application: @app, user: @user,
resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
@subscription_ended_resource_subscription = create(:resource_subscription, oauth_application: @app, user: @user,
resource_name: ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME)
@subscription_restarted_resource_subscription = create(:resource_subscription, oauth_application: @app, user: @user,
resource_name: ResourceSubscription::SUBSCRIPTION_RESTARTED_RESOURCE_NAME)
@subscription_updated_resource_subscription = create(:resource_subscription, oauth_application: @app, user: @user,
resource_name: ResourceSubscription::SUBSCRIPTION_UPDATED_RESOURCE_NAME)
end
it "posts to the app's post url" do
purchaser = create(:user)
purchase = create(:purchase, link: @product, price_cents: 500, email: "ibuy@gumroad.com", seller: @product.user, purchaser:)
expect(purchase.purchaser).to eq purchaser
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
product_name: @product.name,
product_permalink: @product.long_url,
purchaser_id: purchaser.external_id,
permalink: "abc",
email: "ibuy@gumroad.com"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@resource_subscription.post_url, params, @resource_subscription.content_type, @user.id)
end
it "posts affiliate_credit information to the app's post url" do
@product.update!(price_cents: 500)
@affiliate_user = create(:affiliate_user)
@direct_affiliate = create(:direct_affiliate, affiliate_user: @affiliate_user, seller: @user, affiliate_basis_points: 1500, products: [@product])
@purchase = create(:purchase_in_progress, link: @product, email: "ibuy@gumroad.com", price_cents: 500, purchase_state: "in_progress", affiliate: @direct_affiliate)
@purchase.process!
@purchase.update_balance_and_mark_successful!
PostToPingEndpointsWorker.new.perform(@purchase.id, nil)
params = @default_params.call(@purchase).merge(
product_name: @product.name,
product_permalink: @product.long_url,
permalink: "abc",
email: "ibuy@gumroad.com",
affiliate_credit_amount_cents: 53,
affiliate: @affiliate_user.form_email
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@resource_subscription.post_url, params, @resource_subscription.content_type, @user.id)
end
it "posts to all apps' post urls and to the user's notification endpoint" do
@user.update(notification_endpoint: "http://notification.com")
another_app = create(:oauth_application, owner: create(:user), name: "another app")
create("doorkeeper/access_token", application: another_app, resource_owner_id: @user.id, scopes: "view_sales")
another_resource_subscription = create(:resource_subscription, oauth_application: another_app, user: @user, post_url: "http://preposterous.com")
purchase = create(:purchase, link: @product, price_cents: 500, email: "ibuy@gumroad.com")
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
product_name: @product.name,
product_permalink: @product.long_url,
permalink: "abc",
email: "ibuy@gumroad.com"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@resource_subscription.post_url, params, @resource_subscription.content_type, @user.id)
params = @default_params.call(purchase).merge(
product_name: @product.name,
product_permalink: @product.long_url,
permalink: "abc",
email: "ibuy@gumroad.com"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(another_resource_subscription.post_url, params, another_resource_subscription.content_type, @user.id)
params = @default_params.call(purchase).merge(
product_name: @product.name,
product_permalink: @product.long_url,
permalink: "abc",
email: "ibuy@gumroad.com"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@user.notification_endpoint, params, @user.notification_content_type, @user.id)
end
it "does not post to the app's post url if the token is revoked" do
@token.revoke
purchase = create(:purchase, link: @product, price_cents: 500, email: "ibuy@gumroad.com")
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
jobs = PostToIndividualPingEndpointWorker.jobs
expect(jobs.size).to eq(1)
expect(jobs.first["args"].first).to eq("http://notification.com")
end
it "does not post to the app's post url if the post url is invalid" do
@resource_subscription.update!(post_url: "http://localhost/path")
purchase = create(:purchase, link: @product)
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
expect(PostToIndividualPingEndpointWorker).to_not have_enqueued_sidekiq_job(@resource_subscription.post_url, anything, @resource_subscription.content_type, anything)
end
it "does not post to the app's post url if the user hasn't given view_sales permissions to the app" do
another_app = create(:oauth_application, owner: create(:user), name: "another app")
create("doorkeeper/access_token", application: another_app, resource_owner_id: @user.id, scopes: "edit_products")
create(:resource_subscription, oauth_application: another_app, user: @user, post_url: "http://preposterous.com")
purchase = create(:purchase, link: @product, price_cents: 500, email: "ibuy@gumroad.com")
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
jobs = PostToIndividualPingEndpointWorker.jobs
expect(jobs.size).to eq(2)
expect(jobs.first["args"].first).to eq(@resource_subscription.post_url)
expect(jobs.second["args"].first).to eq("http://notification.com")
end
it "posts to the app's post url if the user has given multiple permissions to the app, including view_sales" do
@token.revoke
another_app = create(:oauth_application, owner: create(:user), name: "another app")
create("doorkeeper/access_token", application: another_app, resource_owner_id: @user.id, scopes: "view_sales edit_products")
another_resource_subscription = create(:resource_subscription, oauth_application: another_app, user: @user, post_url: "http://preposterous.com")
purchase = create(:purchase, link: @product, price_cents: 500, email: "ibuy@gumroad.com")
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
product_name: @product.name,
product_permalink: @product.long_url,
permalink: "abc",
email: "ibuy@gumroad.com"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(another_resource_subscription.post_url, params, another_resource_subscription.content_type, @user.id)
end
it "posts to the app's post url even if the token is expired" do
@token.update!(expires_in: -10.minutes)
expect(@token.expired?).to be(true)
purchase = create(:purchase, link: @product, price_cents: 500, email: "ibuy@gumroad.com")
PostToPingEndpointsWorker.new.perform(purchase.id, nil)
params = @default_params.call(purchase).merge(
product_name: @product.name,
product_permalink: @product.long_url,
permalink: "abc",
email: "ibuy@gumroad.com"
)
expect(PostToIndividualPingEndpointWorker).to have_enqueued_sidekiq_job(@resource_subscription.post_url, params, @resource_subscription.content_type, @user.id)
end
it "posts sale refunded ping to the 'refunded' resource's post_url", :sidekiq_inline do
purchase = create(:purchase, link: @product, price_cents: 500, stripe_refunded: true)
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::REFUNDED_RESOURCE_NAME)
expect(params[:refunded]).to be(true)
expect(HTTParty).not_to receive(:post).with(@user.notification_endpoint, timeout: 5, body: params.deep_stringify_keys)
expect(HTTParty).to receive(:post).with(@refunded_resource_subscription.post_url,
timeout: 5,
body: params.deep_stringify_keys,
headers: { "Content-Type" => @refunded_resource_subscription.content_type }).and_return(@http_double)
PostToPingEndpointsWorker.new.perform(purchase.id, nil, ResourceSubscription::REFUNDED_RESOURCE_NAME)
end
it "posts subscription cancelled ping to the 'cancellation' resource's post_url", :sidekiq_inline do
purchase = create(:membership_purchase, link: @product, price_cents: 500)
subscription = create(:subscription, link: @product, cancelled_at: Time.current, user_requested_cancellation_at: Time.current)
subscription.purchases << purchase
params = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
expect(params[:cancelled]).to be(true)
expect(HTTParty).not_to receive(:post).with(@user.notification_endpoint, timeout: 5, body: params.deep_stringify_keys)
expect(HTTParty).to receive(:post).with(@cancelled_resource_subscription.post_url,
timeout: 5,
body: params.deep_stringify_keys,
headers: { "Content-Type" => @cancelled_resource_subscription.content_type }).and_return(@http_double)
PostToPingEndpointsWorker.new.perform(nil, nil, ResourceSubscription::CANCELLED_RESOURCE_NAME, subscription.id)
end
it "posts subscription ended ping to the 'subscription_ended' resource's post_url", :sidekiq_inline do
subscription = create(:subscription, link: @product, deactivated_at: Time.current, cancelled_at: Time.current)
create(:membership_purchase, subscription:, link: @product)
params = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME)
expect(params[:ended_reason]).to be_present
expect(HTTParty).not_to receive(:post).with(@user.notification_endpoint, timeout: 5, body: params.deep_stringify_keys)
expect(HTTParty).to receive(:post).with(@subscription_ended_resource_subscription.post_url,
timeout: 5,
body: params.deep_stringify_keys,
headers: { "Content-Type" => @subscription_ended_resource_subscription.content_type }).and_return(@http_double)
PostToPingEndpointsWorker.new.perform(nil, nil, ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME, subscription.id)
end
it "does not post subscription ended ping to the 'subscription_ended' resource's post_url if the subscription has not ended", :sidekiq_inline do
subscription = create(:subscription, link: @product, cancelled_at: 1.week.from_now)
create(:membership_purchase, subscription:, link: @product)
params = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME)
expect(HTTParty).not_to receive(:post).with(@subscription_ended_resource_subscription.post_url,
timeout: 5,
body: params.deep_stringify_keys,
headers: { "Content-Type" => @subscription_ended_resource_subscription.content_type }
)
PostToPingEndpointsWorker.new.perform(nil, nil, ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME, subscription.id)
end
it "posts subscription restarted ping ot the 'subscription_restarted' resource's post_url", :sidekiq_inline do
subscription = create(:subscription, link: @product)
create(:membership_purchase, subscription:, link: @product)
params = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::SUBSCRIPTION_RESTARTED_RESOURCE_NAME)
expect(HTTParty).not_to receive(:post).with(@user.notification_endpoint, timeout: 5, body: params.deep_stringify_keys)
expect(HTTParty).to receive(:post).with(@subscription_restarted_resource_subscription.post_url,
timeout: 5,
body: params.deep_stringify_keys,
headers: { "Content-Type" => @subscription_restarted_resource_subscription.content_type }).and_return(@http_double)
PostToPingEndpointsWorker.new.perform(nil, nil, ResourceSubscription::SUBSCRIPTION_RESTARTED_RESOURCE_NAME, subscription.id)
end
it "does not post subscription restarted ping to the 'subscription_restarted' resource's post_url if the subscription has a termination date", :sidekiq_inline do
subscription = create(:subscription, link: @product, cancelled_at: Time.current)
create(:membership_purchase, subscription:, link: @product)
expect(HTTParty).not_to receive(:post)
PostToPingEndpointsWorker.new.perform(nil, nil, ResourceSubscription::SUBSCRIPTION_RESTARTED_RESOURCE_NAME, subscription.id)
end
it "posts subscription updated ping to the 'subscription_updated' resource's post_url", :sidekiq_inline do
subscription = create(:subscription, link: @product)
create(:membership_purchase, subscription:, link: @product)
params = subscription.payload_for_ping_notification(resource_name: ResourceSubscription::SUBSCRIPTION_UPDATED_RESOURCE_NAME, additional_params: { "foo" => "bar" })
expect(HTTParty).not_to receive(:post).with(@user.notification_endpoint, timeout: 5, body: params.deep_stringify_keys)
expect(HTTParty).to receive(:post).with(@subscription_updated_resource_subscription.post_url,
timeout: 5,
body: params.deep_stringify_keys,
headers: { "Content-Type" => @subscription_updated_resource_subscription.content_type }).and_return(@http_double)
PostToPingEndpointsWorker.new.perform(nil, nil, ResourceSubscription::SUBSCRIPTION_UPDATED_RESOURCE_NAME, subscription.id, { "foo" => "bar" })
end
it "posts sale disputed ping to the 'dispute' resource's post_url", :sidekiq_inline do
purchase = create(:purchase, link: @product, price_cents: 500, chargeback_date: Date.today)
params = purchase.payload_for_ping_notification(resource_name: ResourceSubscription::DISPUTE_RESOURCE_NAME)
dispute_resource_subscription = create(:resource_subscription, oauth_application: @app, user: @user,
resource_name: ResourceSubscription::DISPUTE_RESOURCE_NAME)
expect(params[:disputed]).to be(true)
expect(HTTParty).not_to receive(:post).with(@user.notification_endpoint,
timeout: 5,
body: params.deep_stringify_keys,
headers: { "Content-Type" => @user.notification_content_type })
expect(HTTParty).to receive(:post).with(dispute_resource_subscription.post_url,
timeout: 5,
body: params.deep_stringify_keys,
headers: { "Content-Type" => dispute_resource_subscription.content_type }).and_return(@http_double)
PostToPingEndpointsWorker.new.perform(purchase.id, nil, ResourceSubscription::DISPUTE_RESOURCE_NAME)
end
it "posts sale dispute won ping to the 'dispute_won' resource's post_url", :sidekiq_inline do
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/remove_deleted_files_from_s3_job_spec.rb | spec/sidekiq/remove_deleted_files_from_s3_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RemoveDeletedFilesFromS3Job do
before do
allow_any_instance_of(described_class).to receive(:delete_s3_objects!)
end
it "removes recently deleted files from S3" do
product_file = create(:product_file, deleted_at: 26.hours.ago)
product_file_archive = create(:product_files_archive, deleted_at: 26.hours.ago)
subtitle_file = create(:subtitle_file, deleted_at: 26.hours.ago)
described_class.new.perform
expect(product_file.reload.deleted_from_cdn_at).to be_present
expect(product_file_archive.reload.deleted_from_cdn_at).to be_present
expect(subtitle_file.reload.deleted_from_cdn_at).to be_present
end
it "does not remove older deleted files from S3" do
product_file = create(:product_file, deleted_at: 1.year.ago)
product_file_archive = create(:product_files_archive, deleted_at: 1.year.ago)
subtitle_file = create(:subtitle_file, deleted_at: 1.year.ago)
described_class.new.perform
expect(product_file.reload.deleted_from_cdn_at).to be_nil
expect(product_file_archive.reload.deleted_from_cdn_at).to be_nil
expect(subtitle_file.reload.deleted_from_cdn_at).to be_nil
end
it "does not attempt to delete files already marked as removed from S3" do
create(:product_file, deleted_at: 26.hours.ago, deleted_from_cdn_at: 26.hours.ago)
create(:product_files_archive, deleted_at: 26.hours.ago, deleted_from_cdn_at: 26.hours.ago)
create(:subtitle_file, deleted_at: 26.hours.ago, deleted_from_cdn_at: 26.hours.ago)
expect_any_instance_of(described_class).not_to receive(:delete_s3_object!)
described_class.new.perform
end
it "does not remove files with existing alive duplicate files from S3" do
product_file_1 = create(:product_file, deleted_at: 26.hours.ago)
product_file_2 = create(:product_file, url: product_file_1.url)
subtitle_file_1 = create(:subtitle_file, deleted_at: 26.hours.ago)
subtitle_file_2 = create(:subtitle_file, url: subtitle_file_1.url)
# product file archives can't have duplicate urls
described_class.new.perform
expect(product_file_1.reload.deleted_from_cdn_at).to be_nil
expect(product_file_2.reload.deleted_from_cdn_at).to be_nil
expect(subtitle_file_1.reload.deleted_from_cdn_at).to be_nil
expect(subtitle_file_2.reload.deleted_from_cdn_at).to be_nil
end
it "notifies Bugsnag and continues when there's an error removing a file" do
instance = described_class.new
product_file_1 = create(:product_file, deleted_at: 26.hours.ago)
product_file_2 = create(:product_file, deleted_at: 26.hours.ago)
allow(instance).to receive(:remove_record_files).and_call_original
allow(instance).to receive(:remove_record_files).with(satisfy { _1.id == product_file_1.id }).and_raise(RuntimeError.new)
expect(Bugsnag).to receive(:notify).with(an_instance_of(RuntimeError))
instance.perform
expect(product_file_1.deleted_from_cdn_at).to be_nil
expect(product_file_2.reload.deleted_from_cdn_at).to be_present
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/renew_custom_domain_ssl_certificates_spec.rb | spec/sidekiq/renew_custom_domain_ssl_certificates_spec.rb | # frozen_string_literal: true
describe RenewCustomDomainSslCertificates do
describe "#perform" do
before do
@obj_double = double("SslCertificates::Renew object")
allow(SslCertificates::Renew).to receive(:new).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
it "invokes SslCertificates::Generate service" do
expect(SslCertificates::Renew).to receive(:new)
expect(@obj_double).to receive(:process)
described_class.new.perform
end
end
context "when the environment is not production or staging" do
it "doesn't invoke SslCertificates::Generate service" do
expect(SslCertificates::Renew).not_to receive(:new)
expect(@obj_double).not_to receive(:process)
described_class.new.perform
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/google_calendar_invite_job_spec.rb | spec/sidekiq/google_calendar_invite_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GoogleCalendarInviteJob do
describe "#perform" do
let(:call) { create(:call) }
let(:link) { call.link }
let(:buyer_email) { "buyer@example.com" }
let(:google_calendar_integration) { create(:google_calendar_integration) }
let(:gcal_api) { instance_double(GoogleCalendarApi) }
before do
allow(Call).to receive(:find).with(call.id).and_return(call)
allow(call).to receive(:link).and_return(link)
allow(call.purchase).to receive(:purchaser).and_return(double(email: buyer_email))
allow(link).to receive(:get_integration).and_return(google_calendar_integration)
allow(GoogleCalendarApi).to receive(:new).and_return(gcal_api)
end
context "when the call already has a Google Calendar event ID" do
before do
allow(call).to receive(:google_calendar_event_id).and_return("existing_event_id")
end
it "does nothing" do
expect(gcal_api).not_to receive(:insert_event)
described_class.new.perform(call.id)
end
end
context "when the call does not have a Google Calendar event ID" do
before do
allow(call).to receive(:google_calendar_event_id).and_return(nil)
end
context "when the Google Calendar integration is not present" do
before do
allow(link).to receive(:get_integration).and_return(nil)
end
it "does nothing" do
expect(gcal_api).not_to receive(:insert_event)
described_class.new.perform(call.id)
end
end
context "when the Google Calendar integration is present" do
let(:event) do
{
summary: "Call with #{buyer_email}",
description: "Scheduled call for #{link.name}",
start: { dateTime: call.start_time.iso8601 },
end: { dateTime: call.end_time.iso8601 },
attendees: [{ email: buyer_email }],
reminders: { useDefault: true }
}
end
context "when the API call is successful" do
let(:api_response) { double(success?: true, parsed_response: { "id" => "new_event_id" }) }
before do
allow(gcal_api).to receive(:insert_event).and_return(api_response)
end
it "creates a Google Calendar event and updates the call" do
expect(gcal_api).to receive(:insert_event).with(google_calendar_integration.calendar_id, event, access_token: google_calendar_integration.access_token)
expect(call).to receive(:update).with(google_calendar_event_id: "new_event_id")
described_class.new.perform(call.id)
end
end
context "when the API call fails with a 401 error" do
let(:failed_response) { double(success?: false, code: 401) }
let(:refresh_response) { double(success?: true, parsed_response: { "access_token" => "new_access_token" }) }
let(:success_response) { double(success?: true, parsed_response: { "id" => "new_event_id" }) }
before do
allow(gcal_api).to receive(:insert_event).and_return(failed_response, success_response)
allow(gcal_api).to receive(:refresh_token).and_return(refresh_response)
end
it "refreshes the token and retries inserting the event" do
expect(gcal_api).to receive(:refresh_token).with(google_calendar_integration.refresh_token)
expect(google_calendar_integration).to receive(:update).with(access_token: "new_access_token")
expect(gcal_api).to receive(:insert_event).with(google_calendar_integration.calendar_id, event, access_token: "new_access_token")
expect(call).to receive(:update).with(google_calendar_event_id: "new_event_id")
described_class.new.perform(call.id)
end
end
context "when the API call fails with a non-401 error" do
let(:failed_response) { double(success?: false, code: 500, parsed_response: "Internal Server Error") }
before do
allow(gcal_api).to receive(:insert_event).and_return(failed_response)
end
it "logs the error" do
expect(Rails.logger).to receive(:error).with("Failed to insert Google Calendar event: Internal Server Error")
described_class.new.perform(call.id)
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/large_sellers_update_user_balance_stats_cache_worker_spec.rb | spec/sidekiq/large_sellers_update_user_balance_stats_cache_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe LargeSellersUpdateUserBalanceStatsCacheWorker do
describe "#perform" do
it "queues a job for each cacheable user" do
ids = create_list(:user, 2).map(&:id)
expect(UserBalanceStatsService).to receive(:cacheable_users).and_return(User.where(id: ids))
described_class.new.perform
expect(UpdateUserBalanceStatsCacheWorker).to have_enqueued_sidekiq_job(ids[0])
expect(UpdateUserBalanceStatsCacheWorker).to have_enqueued_sidekiq_job(ids[1])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/delete_product_files_archives_worker_spec.rb | spec/sidekiq/delete_product_files_archives_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DeleteProductFilesArchivesWorker do
before do
@product = create(:product, user: create(:named_seller))
product_file_1 = create(:product_file, link: @product)
product_file_2 = create(:product_file, link: @product)
product_file_3 = create(:product_file, link: @product)
product_file_4 = create(:product_file, link: @product)
folder1_id = SecureRandom.uuid
folder2_id = SecureRandom.uuid
product_page_description = [
{ "type" => "fileEmbedGroup", "attrs" => { "name" => "", "uid" => folder1_id }, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file_1.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => product_file_2.external_id, "uid" => SecureRandom.uuid } },
] },
{ "type" => "fileEmbedGroup", "attrs" => { "name" => "", "uid" => folder2_id }, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file_3.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => product_file_4.external_id, "uid" => SecureRandom.uuid } },
] }]
create(:rich_content, entity: @product, title: "Page 1", description: product_page_description)
product_archive = @product.product_files_archives.create!
product_archive.product_files = @product.product_files
product_archive.mark_in_progress!
product_archive.mark_ready!
folder_archive1 = @product.product_files_archives.create!(folder_id: folder1_id)
folder_archive1.product_files = [product_file_1, product_file_2]
folder_archive1.mark_in_progress!
folder_archive1.mark_ready!
folder_archive2 = @product.product_files_archives.create!(folder_id: folder2_id)
folder_archive2.product_files = [product_file_3, product_file_4]
folder_archive2.mark_in_progress!
folder_archive2.mark_ready!
folder3_id = SecureRandom.uuid
product_file_5 = create(:product_file)
product_file_6 = create(:product_file)
variant_category = create(:variant_category, title: "versions", link: @product)
@variant = create(:variant, variant_category:, name: "mac")
@variant.product_files = [product_file_5, product_file_6]
variant_page_description = [
{ "type" => "fileEmbedGroup", "attrs" => { "name" => "", "uid" => folder3_id }, "content" => [
{ "type" => "fileEmbed", "attrs" => { "id" => product_file_5.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "fileEmbed", "attrs" => { "id" => product_file_6.external_id, "uid" => SecureRandom.uuid } },
] }]
create(:rich_content, entity: @variant, title: "Variant Page 1", description: variant_page_description)
variant_archive = @variant.product_files_archives.create!
variant_archive.product_files = @variant.product_files
variant_archive.mark_in_progress!
variant_archive.mark_ready!
variant_folder_archive = @variant.product_files_archives.create!(folder_id: folder3_id)
variant_folder_archive.product_files = [product_file_5, product_file_6]
variant_folder_archive.mark_in_progress!
variant_folder_archive.mark_ready!
@total_product_archives = @product.product_files_archives.alive.ready.count
@total_variant_archives = @variant.product_files_archives.alive.ready.count
end
describe ".perform" do
context "when given a product_id" do
it "deletes the corresponding product and variant archives when the product is deleted" do
described_class.new.perform(@product.id, nil)
expect(ProductFilesArchive.alive.count).to eq(@total_product_archives + @total_variant_archives)
@product.mark_deleted!
described_class.new.perform(@product.id, nil)
expect(@product.product_files_archives.alive.count).to eq(0)
expect(@variant.product_files_archives.alive.count).to eq(0)
end
end
context "when given a variant_id" do
it "deletes the corresponding variant archives when the variant is deleted" do
described_class.new.perform(@variant.variant_category.link_id, @variant.id)
expect(ProductFilesArchive.alive.count).to eq(@total_product_archives + @total_variant_archives)
@variant.mark_deleted!
described_class.new.perform(@variant.variant_category.link_id, @variant.id)
expect(@product.product_files_archives.alive.count).to eq(@total_product_archives)
expect(@variant.product_files_archives.alive.count).to eq(0)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_community_chat_recap_notifications_job_spec.rb | spec/sidekiq/send_community_chat_recap_notifications_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe SendCommunityChatRecapNotificationsJob do
let(:job) { described_class.new }
describe "#perform" do
let(:recap_run) { create(:community_chat_recap_run) }
let(:seller) { create(:user) }
let(:product) { create(:product, user: seller, community_chat_enabled: true) }
let(:community) { create(:community, seller:, resource: product) }
let(:user) { create(:user) }
let!(:recap) { create(:community_chat_recap, community:, community_chat_recap_run: recap_run) }
let!(:notification_setting) { create(:community_notification_setting, user:, seller:) }
before do
Feature.activate_user(:communities, seller)
end
context "when recap run is not finished" do
it "does not send any notifications" do
expect do
job.perform(recap_run.id)
end.not_to have_enqueued_mail(CommunityChatRecapMailer, :community_chat_recap_notification)
end
end
context "when recap run is finished" do
before { recap_run.update_column(:finished_at, 1.hour.ago) } # To prevent after_save_commit callback from triggering
context "when no notification settings exist" do
before do
recap.update!(status: "finished")
notification_setting.destroy!
end
it "does not send any notifications" do
expect do
job.perform(recap_run.id)
end.not_to have_enqueued_mail(CommunityChatRecapMailer, :community_chat_recap_notification)
end
end
context "when notification setting exists and recaps are finished" do
before do
recap.update!(status: "finished")
end
context "when user has accessible communities" do
let!(:purchase) { create(:purchase, seller:, link: product, purchaser: user) }
it "sends notification to user" do
expect do
job.perform(recap_run.id)
end.to have_enqueued_mail(CommunityChatRecapMailer, :community_chat_recap_notification)
.with(user.id, seller.id, [recap.id])
end
end
context "when user has no accessible communities" do
it "does not send notification" do
expect do
job.perform(recap_run.id)
end.not_to have_enqueued_mail(CommunityChatRecapMailer, :community_chat_recap_notification)
end
end
context "when seller has no communities" do
before do
product.update!(community_chat_enabled: false)
end
it "does not send notification" do
expect do
job.perform(recap_run.id)
end.not_to have_enqueued_mail(CommunityChatRecapMailer, :community_chat_recap_notification)
end
end
context "when an error occurs" do
it "notifies Bugsnag" do
expect(Bugsnag).to receive(:notify).with(ActiveRecord::RecordNotFound)
job.perform("non-existing-id")
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/refresh_sitemap_monthly_worker_spec.rb | spec/sidekiq/refresh_sitemap_monthly_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RefreshSitemapMonthlyWorker do
describe "#perform" do
it "enqueues jobs to generate sitemaps for products updated in last month" do
product_1 = create(:product, created_at: 3.months.ago, updated_at: 1.month.ago)
product_2 = create(:product, created_at: 2.months.ago, updated_at: 1.month.ago)
described_class.new.perform
expect(RefreshSitemapDailyWorker).to have_enqueued_sidekiq_job(product_1.created_at.beginning_of_month.to_date.to_s)
expect(RefreshSitemapDailyWorker).to have_enqueued_sidekiq_job(product_2.created_at.beginning_of_month.to_date.to_s).in(30.minutes)
end
it "doesn't enqueue jobs to generate sitemaps updated in the current month" do
create(:product)
described_class.new.perform
expect(RefreshSitemapDailyWorker.jobs.size).to eq(0)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/free_trial_expiring_reminder_worker_spec.rb | spec/sidekiq/free_trial_expiring_reminder_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe FreeTrialExpiringReminderWorker, :vcr do
let(:purchase) { create(:free_trial_membership_purchase) }
let(:subscription) { purchase.subscription }
it "sends an email if the subscription is currently in a free trial" do
expect do
described_class.new.perform(subscription.id)
end.to have_enqueued_mail(CustomerLowPriorityMailer, :free_trial_expiring_soon).with(subscription.id)
end
it "doesn't send email for a test subscription" do
subscription.update!(is_test_subscription: true)
expect do
described_class.new.perform(subscription.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :free_trial_expiring_soon).with(subscription.id)
end
it "doesn't send email if the subscription is no longer in a free trial" do
subscription.update!(free_trial_ends_at: 1.day.ago)
expect do
described_class.new.perform(subscription.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :free_trial_expiring_soon).with(subscription.id)
end
it "doesn't send email if the subscription is pending cancellation" do
subscription.update!(cancelled_at: 1.day.from_now)
expect do
described_class.new.perform(subscription.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :free_trial_expiring_soon).with(subscription.id)
end
it "doesn't send email if the subscription is cancelled" do
subscription.update!(cancelled_at: 1.day.ago)
expect do
described_class.new.perform(subscription.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :free_trial_expiring_soon).with(subscription.id)
end
it "doesn't send email for a subscription without a free trial" do
purchase = create(:membership_purchase)
subscription = purchase.subscription
expect do
described_class.new.perform(subscription.id)
end.to_not have_enqueued_mail(CustomerLowPriorityMailer, :free_trial_expiring_soon).with(subscription.id)
end
it "doesn't send duplicate emails" do
expect do
described_class.new.perform(subscription.id)
described_class.new.perform(subscription.id)
end.to have_enqueued_mail(CustomerLowPriorityMailer, :free_trial_expiring_soon).with(subscription.id).once
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/generate_financial_reports_for_previous_month_job_spec.rb | spec/sidekiq/generate_financial_reports_for_previous_month_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GenerateFinancialReportsForPreviousMonthJob do
describe ".perform" do
it "does not generate any reports when the Rails environment is not production" do
described_class.new.perform
expect(CreateCanadaMonthlySalesReportJob.jobs.size).to eq(0)
expect(GenerateFeesByCreatorLocationReportJob.jobs.size).to eq(0)
expect(CreateUsStatesSalesSummaryReportJob.jobs.size).to eq(0)
expect(GenerateCanadaSalesReportJob.jobs.size).to eq(0)
end
it "generates reports when the Rails environment is production" do
allow(Rails.env).to receive(:production?).and_return(true)
described_class.new.perform
expect(CreateCanadaMonthlySalesReportJob).to have_enqueued_sidekiq_job(an_instance_of(Integer), an_instance_of(Integer))
expect(GenerateFeesByCreatorLocationReportJob).to have_enqueued_sidekiq_job(an_instance_of(Integer), an_instance_of(Integer))
expect(CreateUsStatesSalesSummaryReportJob).to have_enqueued_sidekiq_job(Compliance::Countries::TAXABLE_US_STATE_CODES, an_instance_of(Integer), an_instance_of(Integer))
expect(GenerateCanadaSalesReportJob).to have_enqueued_sidekiq_job(an_instance_of(Integer), an_instance_of(Integer))
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_states_sales_summary_report_job_spec.rb | spec/sidekiq/create_us_states_sales_summary_report_job_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CreateUsStatesSalesSummaryReportJob do
let(:subdivision_codes) { ["WA", "WI"] }
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_codes, 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_codes, 13, year) }.to raise_error(ArgumentError)
end
it "raises an argument error if any subdivision code is not valid" do
expect { described_class.new.perform(["WA", "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/us-states-sales-summary-spec-#{SecureRandom.hex(18)}.csv")
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: "53703") # Madison, Wisconsin
@purchase3 = create(:purchase_in_progress, link: product, country: "United States", zip_code: "98184") # Seattle, Washington
@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
@purchase7 = create(:purchase_in_progress, link: product, country: "United States", zip_code: "53202", gumroad_tax_cents: 850) # Milwaukee, Wisconsin
@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 a summary CSV file with correct totals for each state and submits transactions to TaxJar" do
expect(s3_bucket_double).to receive(:object).ordered.and_return(@s3_object)
expect_any_instance_of(TaxjarApi).to receive(:create_order_transaction).exactly(8).times.and_call_original
described_class.new.perform(subdivision_codes, month, year)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "US Sales Tax Summary Report", 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).to eq([
["State", "GMV", "Number of orders", "Sales tax collected"],
["Washington", "843.70", "6", "71.53"],
["Wisconsin", "212.59", "2", "12.59"]
])
expect(@purchase1.purchase_taxjar_info).to be_present
expect(@purchase2.purchase_taxjar_info).to be_present
expect(@purchase3.purchase_taxjar_info).to be_present
expect(@purchase4.purchase_taxjar_info).to be_present
expect(@purchase5.purchase_taxjar_info).to be_present
expect(@purchase6.purchase_taxjar_info).to be_present
expect(@purchase_to_refund.purchase_taxjar_info).to be_present
expect(@purchase_without_taxjar_info.purchase_taxjar_info).to be_nil
expect(@purchase2.purchase_taxjar_info).to be_present
expect(@purchase7.purchase_taxjar_info).to be_present
end
it "creates a summary CSV file with correct totals for each state without submitting transactions to TaxJar when push_to_taxjar is false" do
expect(s3_bucket_double).to receive(:object).ordered.and_return(@s3_object)
expect_any_instance_of(TaxjarApi).not_to receive(:create_order_transaction)
described_class.new.perform(subdivision_codes, month, year, push_to_taxjar: false)
expect(SlackMessageWorker).to have_enqueued_sidekiq_job("payments", "US Sales Tax Summary Report", 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).to eq([
["State", "GMV", "Number of orders", "Sales tax collected"],
["Washington", "843.70", "6", "71.53"],
["Wisconsin", "212.59", "2", "12.59"]
])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/charge_preorder_worker_spec.rb | spec/sidekiq/charge_preorder_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ChargePreorderWorker, :vcr do
describe "#perform" do
before do
@good_card = build(:chargeable)
@good_card_but_cant_charge = build(:chargeable_success_charge_decline)
product = create(:product, price_cents: 600, is_in_preorder_state: false)
preorder_product = create(:preorder_product_with_content, link: product)
preorder_product.update_attribute(:release_at, Time.current) # bypass validation
authorization_purchase = build(:purchase, link: product, chargeable: @good_card, purchase_state: "in_progress",
is_preorder_authorization: true)
@preorder = preorder_product.build_preorder(authorization_purchase)
end
it "charges the preorder and mark it as successful" do
@preorder.authorize!
@preorder.mark_authorization_successful!
described_class.new.perform(@preorder.id)
expect(@preorder.reload.state).to eq "charge_successful"
expect(@preorder.authorization_purchase.purchase_state).to eq "preorder_concluded_successfully"
expect(@preorder.purchases.count).to eq 2
expect(@preorder.purchases.last.purchase_state).to eq "successful"
end
it "raises an error if preorder product is not in chargeable state" do
@preorder.authorize!
@preorder.mark_authorization_successful!
@preorder.link.update!(is_in_preorder_state: true)
expect do
described_class.new.perform(@preorder.id)
end.to raise_error(/Unable to charge preorder #{@preorder.id}/)
end
it "retries the charge if the purchase fails with 'processing_error'",
vcr: { cassette_name: "_manual/should_retry_the_charge_if_the_purchase_fails_with_processing_error_" } do
# The vcr cassette was manually changed in order to simulate processing_error charge error. This was
# necessary because stripe doesn't allow customer creation with the processing_error test card.
@preorder.authorize!
@preorder.mark_authorization_successful!
@preorder.credit_card = CreditCard.create(@good_card_but_cant_charge)
described_class.new.perform(@preorder.id)
expect(described_class).to have_enqueued_sidekiq_job(@preorder.id, 2)
expect(@preorder.reload.state).to eq "authorization_successful"
expect(@preorder.purchases.count).to eq 2
expect(@preorder.purchases.last.purchase_state).to eq "failed"
expect(@preorder.purchases.last.stripe_error_code).to eq "processing_error"
end
it "retries the charge three times if the purchase fails with 'processing_error'",
vcr: { cassette_name: "_manual/retries_the_charge_three_times_if_the_purchase_fails_with_processing_error_" } do
# The vcr cassette was manually changed in order to simulate processing_error charge error. This was
# necessary because stripe doesn't allow customer creation with the processing_error test card.
@preorder.authorize!
@preorder.mark_authorization_successful!
@preorder.credit_card = CreditCard.create(@good_card_but_cant_charge)
described_class.new.perform(@preorder.id)
expect(described_class).to have_enqueued_sidekiq_job(@preorder.id, 2)
described_class.perform_one # Run the scheduled job
expect(described_class).to have_enqueued_sidekiq_job(@preorder.id, 3)
described_class.perform_one
allow(Rails.logger).to receive(:info)
expect(described_class).to have_enqueued_sidekiq_job(@preorder.id, 4)
described_class.perform_one
expect(Rails.logger).to(have_received(:info)
.with("ChargePreorder: Gave up charging Preorder #{@preorder.id} after 4 attempts."))
expect(described_class).to_not have_enqueued_sidekiq_job(@preorder.id, 5)
end
it "sends an email to the buyer if the purchase fails with 'card_declined'" do
@preorder.authorize!
@preorder.mark_authorization_successful!
@preorder.credit_card = CreditCard.create(@good_card_but_cant_charge)
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(CustomerLowPriorityMailer).to receive(:preorder_card_declined).with(@preorder.id).and_return(mail_double)
described_class.new.perform(@preorder.id)
expect(@preorder.reload.state).to eq "authorization_successful"
expect(@preorder.purchases.count).to eq 2
expect(@preorder.purchases.last.purchase_state).to eq "failed"
expect(@preorder.purchases.last.stripe_error_code).to eq "card_declined_generic_decline"
end
it "schedules CancelPreorderWorker job to cancel the preorder after 2 weeks if purchase fails with 'card_declined' error" do
@preorder.authorize!
@preorder.mark_authorization_successful!
@preorder.credit_card = CreditCard.create(@good_card_but_cant_charge)
travel_to(Time.current) do
described_class.new.perform(@preorder.id)
expect(@preorder.reload.state).to eq "authorization_successful"
expect(@preorder.purchases.count).to eq 2
expect(@preorder.purchases.last.purchase_state).to eq "failed"
expect(@preorder.purchases.last.stripe_error_code).to eq "card_declined_generic_decline"
job = CancelPreorderWorker.jobs.last
expect(job["args"][0]).to eq(@preorder.id)
expect(job["at"]).to eq(2.weeks.from_now.to_f)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/calculate_payout_numbers_worker_spec.rb | spec/sidekiq/calculate_payout_numbers_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CalculatePayoutNumbersWorker, :sidekiq_inline, :elasticsearch_wait_for_refresh do
describe "#perform" do
before { recreate_model_indices(Purchase) }
context "when purchases are present" do
let(:now) { Time.now.in_time_zone("America/Los_Angeles") }
let(:beginning_of_last_week) { now.prev_week }
let(:end_of_last_week) { beginning_of_last_week.end_of_week }
before do
travel_to(beginning_of_last_week + 30.minutes) do
create(:purchase, price_cents: 123_45)
create(:purchase, price_cents: 234_56)
create(:purchase, price_cents: 567_89)
create(:purchase, price_cents: 0)
create(:purchase, price_cents: 890_12)
create(:purchase, price_cents: 1890_12, chargeback_date: Date.today)
create(:refunded_purchase, price_cents: 1890_12)
create(:failed_purchase, price_cents: 111_890_12)
end
travel_to(beginning_of_last_week - 1.second) do
create_list(:purchase, 5, price_cents: 99_999_00)
end
travel_to(end_of_last_week + 1.second) do
create_list(:purchase, 5, price_cents: 99_999_00)
end
end
let(:expected_total) { (123_45 + 234_56 + 567_89 + 890_12) / 100.0 }
it "stores the expected payout data in Redis" do
described_class.new.perform
expect($redis.get(RedisKey.prev_week_payout_usd)).to eq(expected_total.to_i.to_s)
end
end
context "when there is no data" do
it "stores zero in Redis" do
described_class.new.perform
expect($redis.get(RedisKey.prev_week_payout_usd)).to eq("0")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/block_object_worker_spec.rb | spec/sidekiq/block_object_worker_spec.rb | # frozen_string_literal: true
describe BlockObjectWorker do
describe "#perform" do
let(:admin_user) { create(:admin_user) }
context "when blocking email domain" do
let(:identifier) { "example.com" }
it "blocks email domains without expiration" do
expect(BlockedObject.email_domain.count).to eq(0)
described_class.new.perform("email_domain", identifier, admin_user.id)
expect(BlockedObject.email_domain.count).to eq(1)
blocked_object = BlockedObject.active.find_by(object_value: identifier)
expect(blocked_object.object_value).to eq("example.com")
expect(blocked_object.blocked_by).to eq(admin_user.id)
expect(blocked_object.expires_at).to be_nil
end
end
context "when blocking IP address" do
let(:identifier) { "172.0.0.1" }
it "blocks IP address with expiration" do
expect(BlockedObject.ip_address.count).to eq(0)
described_class.new.perform("ip_address", identifier, admin_user.id, BlockedObject::IP_ADDRESS_BLOCKING_DURATION_IN_MONTHS.months.to_i)
expect(BlockedObject.ip_address.count).to eq(1)
blocked_object = BlockedObject.active.find_by(object_value: identifier)
expect(blocked_object.object_value).to eq("172.0.0.1")
expect(blocked_object.blocked_by).to eq(admin_user.id)
expect(blocked_object.expires_at).to be_present
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/suspend_accounts_with_payment_address_worker_spec.rb | spec/sidekiq/suspend_accounts_with_payment_address_worker_spec.rb | # frozen_string_literal: true
describe SuspendAccountsWithPaymentAddressWorker do
describe "#perform" do
before do
@user = create(:user, payment_address: "sameuser@paypal.com")
@user_2 = create(:user, payment_address: "sameuser@paypal.com")
create(:user) # admin user
end
it "suspends other accounts with the same payment address" do
described_class.new.perform(@user.id)
expect(@user_2.reload.suspended?).to be(true)
expect(@user_2.comments.first.content).to eq("Flagged for fraud automatically on #{Time.current.to_fs(:formatted_date_full_month)} because of usage of payment address #{@user.payment_address} (from User##{@user.id})")
expect(@user_2.comments.last.content).to eq("Suspended for fraud automatically on #{Time.current.to_fs(:formatted_date_full_month)} because of usage of payment address #{@user.payment_address} (from User##{@user.id})")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/log_resend_event_job_spec.rb | spec/sidekiq/log_resend_event_job_spec.rb | # frozen_string_literal: true
describe LogResendEventJob do
describe "#perform" do
let(:email) { "example@example.com" }
let(:email_digest) { Digest::SHA1.hexdigest(email).first(12) }
let(:event_timestamp) { 5.minutes.from_now }
before do
Feature.activate(:log_email_events)
EmailEvent.log_send_events(email, Time.current)
end
it "logs open event" do
params = {
"type" => "email.opened",
"created_at" => "2024-02-22T23:41:12.126Z",
"data" => {
"created_at" => event_timestamp.to_s,
"email_id" => "56761188-7520-42d8-8898-ff6fc54ce618",
"from" => "Acme <onboarding@resend.dev>",
"to" => [email],
"subject" => "Sending this example",
"headers" => [
{
"name" => MailerInfo.header_name(:mailer_class),
"value" => MailerInfo.encrypt("Mailer")
},
{
"name" => MailerInfo.header_name(:mailer_method),
"value" => MailerInfo.encrypt("method")
},
]
}
}
described_class.new.perform(params)
record = EmailEvent.find_by(email_digest:)
expect(record.open_count).to eq 1
expect(record.unopened_emails_count).to eq 0
expect(record.first_unopened_email_sent_at).to be_nil
expect(record.last_opened_at.to_i).to eq event_timestamp.to_i
end
it "logs click event" do
params = {
"type" => "email.clicked",
"created_at" => "2024-11-22T23:41:12.126Z",
"data" => {
"created_at" => event_timestamp.to_s,
"email_id" => "56761188-7520-42d8-8898-ff6fc54ce618",
"from" => "Acme <onboarding@resend.dev>",
"to" => [email],
"click" => {
"ipAddress" => "122.115.53.11",
"link" => "https://resend.com",
"timestamp" => "2024-11-24T05:00:57.163Z",
"userAgent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15"
},
"subject" => "Sending this example",
"headers" => [
{
"name" => MailerInfo.header_name(:mailer_class),
"value" => MailerInfo.encrypt("Mailer")
},
{
"name" => MailerInfo.header_name(:mailer_method),
"value" => MailerInfo.encrypt("method")
},
]
}
}
described_class.new.perform(params)
record = EmailEvent.find_by(email_digest:)
expect(record.click_count).to eq 1
expect(record.last_clicked_at.to_i).to eq event_timestamp.to_i
end
it "ignores other event types" do
params = {
"type" => "email.delivered",
"created_at" => "2024-02-22T23:41:12.126Z",
"data" => {
"created_at" => event_timestamp.to_s,
"email_id" => "56761188-7520-42d8-8898-ff6fc54ce618",
"from" => "Acme <onboarding@resend.dev>",
"to" => [email],
"subject" => "Sending this example",
"headers" => [
{
"name" => MailerInfo.header_name(:mailer_class),
"value" => MailerInfo.encrypt("Mailer")
},
{
"name" => MailerInfo.header_name(:mailer_method),
"value" => MailerInfo.encrypt("method")
},
]
}
}
described_class.new.perform(params)
record = EmailEvent.find_by(email_digest:)
expect(record.open_count).to eq 0
expect(record.click_count).to eq 0
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/score_product_worker_spec.rb | spec/sidekiq/score_product_worker_spec.rb | # frozen_string_literal: true
describe ScoreProductWorker, :vcr do
describe "#perform" do
before do
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("production"))
end
it "sends message to SQS risk queue" do
sqs_client = instance_double(Aws::SQS::Client)
queue_url = "https://sqs.us-east-1.amazonaws.com/123456789012/risk_queue"
queue_url_response = instance_double(Aws::SQS::Types::GetQueueUrlResult, queue_url:)
allow(Aws::SQS::Client).to receive(:new).and_return(sqs_client)
allow(sqs_client).to receive(:get_queue_url).with(queue_name: "risk_queue").and_return(queue_url_response)
expect(sqs_client).to receive(:send_message).with({ queue_url:, message_body: { "type" => "product", "id" => 123 }.to_s })
ScoreProductWorker.new.perform(123)
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_grmc_callback_job_spec.rb | spec/sidekiq/handle_grmc_callback_job_spec.rb | # frozen_string_literal: true
describe HandleGrmcCallbackJob do
let(:product_file) { create(:product_file) }
let(:transcoded_video) { create(:transcoded_video, job_id: "test_job_id", streamable: product_file, transcoded_video_key: "/attachments/68756f28973n28347/hls/", state: :processing) }
describe "#perform" do
context "when notification status is 'success'" do
let(:notification) { { "job_id" => transcoded_video.job_id, "status" => "success" } }
it "updates the product file and transcoded video, and marks it as completed" do
described_class.new.perform(notification)
product_file.reload
transcoded_video.reload
expect(product_file.is_transcoded_for_hls).to be true
expect(transcoded_video.transcoded_video_key).to eq("/attachments/68756f28973n28347/hls/index.m3u8")
expect(transcoded_video).to be_completed
end
it "updates all processing transcoded videos, and marks them as completed" do
transcoded_video_2 = create(:transcoded_video, original_video_key: transcoded_video.original_video_key, transcoded_video_key: transcoded_video.transcoded_video_key, state: :processing)
described_class.new.perform(notification)
product_file.reload
transcoded_video.reload
expect(product_file.is_transcoded_for_hls).to be true
expect(transcoded_video.transcoded_video_key).to eq("/attachments/68756f28973n28347/hls/index.m3u8")
expect(transcoded_video).to be_completed
product_file_2 = transcoded_video_2.reload.streamable.reload
expect(product_file_2.is_transcoded_for_hls).to be true
expect(transcoded_video_2.transcoded_video_key).to eq("/attachments/68756f28973n28347/hls/index.m3u8")
expect(transcoded_video_2).to be_completed
end
end
context "when notification status is not 'success'" do
let(:notification) { { "job_id" => transcoded_video.job_id, "status" => "failure" } }
it "enqueues TranscodeVideoForStreamingWorker" do
described_class.new.perform(notification)
expect(TranscodeVideoForStreamingWorker).to have_enqueued_sidekiq_job(product_file.id, ProductFile.name, TranscodeVideoForStreamingWorker::MEDIACONVERT, true)
end
it "marks transcoded video, marks it as errored" do
described_class.new.perform(notification)
transcoded_video.reload
expect(transcoded_video.state).to eq("error")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/sidekiq/send_payment_reminder_worker_spec.rb | spec/sidekiq/send_payment_reminder_worker_spec.rb | # frozen_string_literal: true
describe SendPaymentReminderWorker do
describe "perform" do
before do
@user = create(:user, payment_address: nil)
create(:balance, user: @user, amount_cents: 1001)
end
it "notifies users to update payment information" do
expect do
described_class.new.perform
end.to have_enqueued_mail(ContactingCreatorMailer, :remind).with(@user.id)
end
it "does not notify the user to update payment information if they have an active stripe connect account" do
create(:merchant_account_stripe_connect, user: @user)
expect do
described_class.new.perform
end.not_to have_enqueued_mail(ContactingCreatorMailer, :remind).with(@user.id)
@user.stripe_connect_account.mark_deleted!
expect do
described_class.new.perform
end.to have_enqueued_mail(ContactingCreatorMailer, :remind).with(@user.id)
end
it "does not notify the user to update payment information if they have an active paypal connect account" do
create(:merchant_account_paypal, user: @user)
expect do
described_class.new.perform
end.not_to have_enqueued_mail(ContactingCreatorMailer, :remind).with(@user.id)
@user.paypal_connect_account.mark_deleted!
expect do
described_class.new.perform
end.to have_enqueued_mail(ContactingCreatorMailer, :remind).with(@user.id)
end
it "does not notify the user to update payment information if they have an active bank account" do
create(:ach_account, user: @user)
expect do
described_class.new.perform
end.not_to have_enqueued_mail(ContactingCreatorMailer, :remind).with(@user.id)
@user.active_bank_account.mark_deleted!
expect do
described_class.new.perform
end.to have_enqueued_mail(ContactingCreatorMailer, :remind).with(@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/create_licenses_for_existing_customers_worker_spec.rb | spec/sidekiq/create_licenses_for_existing_customers_worker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CreateLicensesForExistingCustomersWorker do
describe "#perform" do
before(:each) do
@purchase1 = create(:purchase)
@product = @purchase1.link
@purchase2 = create(:purchase, link: @product)
@purchase3 = create(:purchase, link: @product)
end
it "creates licenses for past purchases" do
expect do
described_class.new.perform(@product.id)
end.to change { @product.licenses.count }.from(0).to(3)
expect(@product.licenses.map(&:purchase_id)).to match_array([@purchase1.id, @purchase2.id, @purchase3.id])
end
it "creates licenses for past purchases only if they do not already exist" do
create(:license, purchase: @purchase1, link: @product)
create(:license, purchase: @purchase3, link: @product)
expect do
described_class.new.perform(@product.id)
end.to change { @product.licenses.count }.from(2).to(3)
expect(@product.licenses.map(&:purchase_id)).to match_array([@purchase1.id, @purchase2.id, @purchase3.id])
end
it "creates licenses for giftee purchases but not gifter purchases" do
gift = create(:gift, link: @product)
gifter_purchase = create(:purchase_in_progress, link: @product, is_gift_sender_purchase: true)
gifter_purchase.process!
gifter_purchase.mark_successful!
gift.gifter_purchase = gifter_purchase
gifter_purchase.is_gift_sender_purchase = true
gift.giftee_purchase = create(:purchase, link: @product, price_cents: 0,
is_gift_receiver_purchase: true,
purchase_state: "gift_receiver_purchase_successful")
gift.mark_successful
gift.save!
expect do
described_class.new.perform(@product.id)
end.to change { @product.licenses.count }.from(0).to(4)
expect(@product.licenses.map(&:purchase_id)).to(
match_array([@purchase1.id, @purchase2.id, @purchase3.id, gift.giftee_purchase.id])
)
end
it "creates licenses for only the original purchases of subscriptions and not the recurring charges" do
user = create(:user)
subscription = create(:subscription, user:, link: @product)
original_subscription_purchase = create(:purchase, link: @product, email: user.email, is_original_subscription_purchase: true, subscription:)
create(:purchase, link: @product, email: user.email, is_original_subscription_purchase: false, subscription:)
expect do
described_class.new.perform(@product.id)
end.to change { @product.licenses.count }.from(0).to(4)
expect(@product.licenses.map(&:purchase_id)).to(match_array([@purchase1.id, @purchase2.id, @purchase3.id, original_subscription_purchase.id]))
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.