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/models/country_spec.rb
spec/models/country_spec.rb
# frozen_string_literal: true describe Country do describe "#supports_stripe_cross_border_payouts?" do it "returns true if country only supports cross-border payouts via stripe otherwise returns false" do expect(Country.new("US").supports_stripe_cross_border_payouts?).to be false expect(Country.new("GB").supports_stripe_cross_border_payouts?).to be false expect(Country.new("AU").supports_stripe_cross_border_payouts?).to be false expect(Country.new("FR").supports_stripe_cross_border_payouts?).to be false expect(Country.new("TH").supports_stripe_cross_border_payouts?).to be true expect(Country.new("KR").supports_stripe_cross_border_payouts?).to be true expect(Country.new("AE").supports_stripe_cross_border_payouts?).to be false expect(Country.new("ET").supports_stripe_cross_border_payouts?).to be true expect(Country.new("BN").supports_stripe_cross_border_payouts?).to be true expect(Country.new("GY").supports_stripe_cross_border_payouts?).to be true expect(Country.new("GT").supports_stripe_cross_border_payouts?).to be true expect(Country.new("IL").supports_stripe_cross_border_payouts?).to be true expect(Country.new("TT").supports_stripe_cross_border_payouts?).to be true expect(Country.new("PH").supports_stripe_cross_border_payouts?).to be true expect(Country.new("MX").supports_stripe_cross_border_payouts?).to be true expect(Country.new("SE").supports_stripe_cross_border_payouts?).to be false expect(Country.new("RO").supports_stripe_cross_border_payouts?).to be false expect(Country.new("NO").supports_stripe_cross_border_payouts?).to be false expect(Country.new("AR").supports_stripe_cross_border_payouts?).to be true expect(Country.new("PE").supports_stripe_cross_border_payouts?).to be true expect(Country.new("IN").supports_stripe_cross_border_payouts?).to be true expect(Country.new("TW").supports_stripe_cross_border_payouts?).to be true expect(Country.new("VN").supports_stripe_cross_border_payouts?).to be true expect(Country.new("NA").supports_stripe_cross_border_payouts?).to be true expect(Country.new("AG").supports_stripe_cross_border_payouts?).to be true expect(Country.new("TZ").supports_stripe_cross_border_payouts?).to be true expect(Country.new("ID").supports_stripe_cross_border_payouts?).to be true expect(Country.new("AL").supports_stripe_cross_border_payouts?).to be true expect(Country.new("JO").supports_stripe_cross_border_payouts?).to be true expect(Country.new("NG").supports_stripe_cross_border_payouts?).to be true expect(Country.new("AZ").supports_stripe_cross_border_payouts?).to be true expect(Country.new("BH").supports_stripe_cross_border_payouts?).to be true expect(Country.new("CR").supports_stripe_cross_border_payouts?).to be true expect(Country.new("CL").supports_stripe_cross_border_payouts?).to be true expect(Country.new("PK").supports_stripe_cross_border_payouts?).to be true expect(Country.new("BA").supports_stripe_cross_border_payouts?).to be true expect(Country.new("TR").supports_stripe_cross_border_payouts?).to be true expect(Country.new("BW").supports_stripe_cross_border_payouts?).to be true expect(Country.new("MA").supports_stripe_cross_border_payouts?).to be true expect(Country.new("RS").supports_stripe_cross_border_payouts?).to be true expect(Country.new("ZA").supports_stripe_cross_border_payouts?).to be true expect(Country.new("KE").supports_stripe_cross_border_payouts?).to be true expect(Country.new("EG").supports_stripe_cross_border_payouts?).to be true expect(Country.new("CO").supports_stripe_cross_border_payouts?).to be true expect(Country.new("AO").supports_stripe_cross_border_payouts?).to be true expect(Country.new("NE").supports_stripe_cross_border_payouts?).to be true expect(Country.new("SM").supports_stripe_cross_border_payouts?).to be true expect(Country.new("SA").supports_stripe_cross_border_payouts?).to be true expect(Country.new("KZ").supports_stripe_cross_border_payouts?).to be true expect(Country.new("EC").supports_stripe_cross_border_payouts?).to be true expect(Country.new("LI").supports_stripe_cross_border_payouts?).to be false expect(Country.new("JP").supports_stripe_cross_border_payouts?).to be false expect(Country.new("MY").supports_stripe_cross_border_payouts?).to be true expect(Country.new("GI").supports_stripe_cross_border_payouts?).to be false expect(Country.new("UY").supports_stripe_cross_border_payouts?).to be true expect(Country.new("RW").supports_stripe_cross_border_payouts?).to be true expect(Country.new("MU").supports_stripe_cross_border_payouts?).to be true expect(Country.new("JM").supports_stripe_cross_border_payouts?).to be true expect(Country.new("OM").supports_stripe_cross_border_payouts?).to be true expect(Country.new("DO").supports_stripe_cross_border_payouts?).to be true expect(Country.new("UZ").supports_stripe_cross_border_payouts?).to be true expect(Country.new("BO").supports_stripe_cross_border_payouts?).to be true expect(Country.new("TN").supports_stripe_cross_border_payouts?).to be true expect(Country.new("MD").supports_stripe_cross_border_payouts?).to be true expect(Country.new("PA").supports_stripe_cross_border_payouts?).to be true expect(Country.new("SV").supports_stripe_cross_border_payouts?).to be true expect(Country.new("BD").supports_stripe_cross_border_payouts?).to be true expect(Country.new("BT").supports_stripe_cross_border_payouts?).to be true expect(Country.new("LA").supports_stripe_cross_border_payouts?).to be true expect(Country.new("MZ").supports_stripe_cross_border_payouts?).to be true expect(Country.new("MG").supports_stripe_cross_border_payouts?).to be true expect(Country.new("PY").supports_stripe_cross_border_payouts?).to be true expect(Country.new("GH").supports_stripe_cross_border_payouts?).to be true expect(Country.new("AM").supports_stripe_cross_border_payouts?).to be true expect(Country.new("LK").supports_stripe_cross_border_payouts?).to be true expect(Country.new("KW").supports_stripe_cross_border_payouts?).to be true expect(Country.new("MK").supports_stripe_cross_border_payouts?).to be true expect(Country.new("IS").supports_stripe_cross_border_payouts?).to be true expect(Country.new("QA").supports_stripe_cross_border_payouts?).to be true expect(Country.new("BS").supports_stripe_cross_border_payouts?).to be true expect(Country.new("LC").supports_stripe_cross_border_payouts?).to be true expect(Country.new("SN").supports_stripe_cross_border_payouts?).to be true expect(Country.new("KH").supports_stripe_cross_border_payouts?).to be true expect(Country.new("MN").supports_stripe_cross_border_payouts?).to be true expect(Country.new("GA").supports_stripe_cross_border_payouts?).to be true expect(Country.new("MC").supports_stripe_cross_border_payouts?).to be true expect(Country.new("DZ").supports_stripe_cross_border_payouts?).to be true expect(Country.new("MO").supports_stripe_cross_border_payouts?).to be true expect(Country.new("BJ").supports_stripe_cross_border_payouts?).to be true expect(Country.new("CI").supports_stripe_cross_border_payouts?).to be true end end describe "#can_accept_stripe_charges?" do it "returns true if country supports payments via stripe otherwise returns false" do expect(Country.new("US").can_accept_stripe_charges?).to be true expect(Country.new("GB").can_accept_stripe_charges?).to be true expect(Country.new("AU").can_accept_stripe_charges?).to be true expect(Country.new("FR").can_accept_stripe_charges?).to be true expect(Country.new("TH").can_accept_stripe_charges?).to be false expect(Country.new("KR").can_accept_stripe_charges?).to be false expect(Country.new("AE").can_accept_stripe_charges?).to be true expect(Country.new("IL").can_accept_stripe_charges?).to be false expect(Country.new("TT").can_accept_stripe_charges?).to be false expect(Country.new("PH").can_accept_stripe_charges?).to be false expect(Country.new("MX").can_accept_stripe_charges?).to be false expect(Country.new("SE").can_accept_stripe_charges?).to be true expect(Country.new("RO").can_accept_stripe_charges?).to be true expect(Country.new("NO").can_accept_stripe_charges?).to be true expect(Country.new("AR").can_accept_stripe_charges?).to be false expect(Country.new("PE").can_accept_stripe_charges?).to be false expect(Country.new("NA").can_accept_stripe_charges?).to be false expect(Country.new("ET").can_accept_stripe_charges?).to be false expect(Country.new("BN").can_accept_stripe_charges?).to be false expect(Country.new("GY").can_accept_stripe_charges?).to be false expect(Country.new("GT").can_accept_stripe_charges?).to be false expect(Country.new("AG").can_accept_stripe_charges?).to be false expect(Country.new("TZ").can_accept_stripe_charges?).to be false expect(Country.new("IN").can_accept_stripe_charges?).to be false expect(Country.new("TW").can_accept_stripe_charges?).to be false expect(Country.new("AL").can_accept_stripe_charges?).to be false expect(Country.new("BH").can_accept_stripe_charges?).to be false expect(Country.new("RW").can_accept_stripe_charges?).to be false expect(Country.new("JO").can_accept_stripe_charges?).to be false expect(Country.new("NG").can_accept_stripe_charges?).to be false expect(Country.new("AZ").can_accept_stripe_charges?).to be false expect(Country.new("VN").can_accept_stripe_charges?).to be false expect(Country.new("ID").can_accept_stripe_charges?).to be false expect(Country.new("CR").can_accept_stripe_charges?).to be false expect(Country.new("BD").can_accept_stripe_charges?).to be false expect(Country.new("BT").can_accept_stripe_charges?).to be false expect(Country.new("LA").can_accept_stripe_charges?).to be false expect(Country.new("MZ").can_accept_stripe_charges?).to be false expect(Country.new("CL").can_accept_stripe_charges?).to be false expect(Country.new("BW").can_accept_stripe_charges?).to be false expect(Country.new("PK").can_accept_stripe_charges?).to be false expect(Country.new("TR").can_accept_stripe_charges?).to be false expect(Country.new("LI").can_accept_stripe_charges?).to be true expect(Country.new("BA").can_accept_stripe_charges?).to be false expect(Country.new("MA").can_accept_stripe_charges?).to be false expect(Country.new("RS").can_accept_stripe_charges?).to be false expect(Country.new("ZA").can_accept_stripe_charges?).to be false expect(Country.new("KE").can_accept_stripe_charges?).to be false expect(Country.new("EG").can_accept_stripe_charges?).to be false expect(Country.new("AO").can_accept_stripe_charges?).to be false expect(Country.new("NE").can_accept_stripe_charges?).to be false expect(Country.new("SM").can_accept_stripe_charges?).to be false expect(Country.new("CO").can_accept_stripe_charges?).to be false expect(Country.new("SA").can_accept_stripe_charges?).to be false expect(Country.new("KZ").can_accept_stripe_charges?).to be false expect(Country.new("EC").can_accept_stripe_charges?).to be false expect(Country.new("JP").can_accept_stripe_charges?).to be true expect(Country.new("MY").can_accept_stripe_charges?).to be false expect(Country.new("GI").can_accept_stripe_charges?).to be true expect(Country.new("UY").can_accept_stripe_charges?).to be false expect(Country.new("MU").can_accept_stripe_charges?).to be false expect(Country.new("JM").can_accept_stripe_charges?).to be false expect(Country.new("OM").can_accept_stripe_charges?).to be false expect(Country.new("DO").can_accept_stripe_charges?).to be false expect(Country.new("UZ").can_accept_stripe_charges?).to be false expect(Country.new("BO").can_accept_stripe_charges?).to be false expect(Country.new("TN").can_accept_stripe_charges?).to be false expect(Country.new("MD").can_accept_stripe_charges?).to be false expect(Country.new("PA").can_accept_stripe_charges?).to be false expect(Country.new("SV").can_accept_stripe_charges?).to be false expect(Country.new("MG").can_accept_stripe_charges?).to be false expect(Country.new("PY").can_accept_stripe_charges?).to be false expect(Country.new("GH").can_accept_stripe_charges?).to be false expect(Country.new("AM").can_accept_stripe_charges?).to be false expect(Country.new("LK").can_accept_stripe_charges?).to be false expect(Country.new("KW").can_accept_stripe_charges?).to be false expect(Country.new("MK").can_accept_stripe_charges?).to be false expect(Country.new("IS").can_accept_stripe_charges?).to be false expect(Country.new("QA").can_accept_stripe_charges?).to be false expect(Country.new("BS").can_accept_stripe_charges?).to be false expect(Country.new("LC").can_accept_stripe_charges?).to be false expect(Country.new("SN").can_accept_stripe_charges?).to be false expect(Country.new("KH").can_accept_stripe_charges?).to be false expect(Country.new("MN").can_accept_stripe_charges?).to be false expect(Country.new("GA").can_accept_stripe_charges?).to be false expect(Country.new("MC").can_accept_stripe_charges?).to be false expect(Country.new("DZ").can_accept_stripe_charges?).to be false expect(Country.new("MO").can_accept_stripe_charges?).to be false expect(Country.new("BJ").can_accept_stripe_charges?).to be false expect(Country.new("CI").can_accept_stripe_charges?).to be false end end describe "#stripe_capabilities" do it "returns country-specific stripe capabilities" do expect(Country.new("US").stripe_capabilities).to eq StripeMerchantAccountManager::REQUESTED_CAPABILITIES expect(Country.new("GB").stripe_capabilities).to eq StripeMerchantAccountManager::REQUESTED_CAPABILITIES expect(Country.new("AU").stripe_capabilities).to eq StripeMerchantAccountManager::REQUESTED_CAPABILITIES expect(Country.new("FR").stripe_capabilities).to eq StripeMerchantAccountManager::REQUESTED_CAPABILITIES expect(Country.new("TH").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("KR").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("AE").stripe_capabilities).to eq StripeMerchantAccountManager::REQUESTED_CAPABILITIES expect(Country.new("IL").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("TT").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("PH").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("MX").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("SE").stripe_capabilities).to eq StripeMerchantAccountManager::REQUESTED_CAPABILITIES expect(Country.new("RO").stripe_capabilities).to eq StripeMerchantAccountManager::REQUESTED_CAPABILITIES expect(Country.new("LI").stripe_capabilities).to eq StripeMerchantAccountManager::REQUESTED_CAPABILITIES expect(Country.new("NO").stripe_capabilities).to eq StripeMerchantAccountManager::REQUESTED_CAPABILITIES expect(Country.new("BD").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("BT").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("LA").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("MZ").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("AR").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("PE").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("AL").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("BH").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("NA").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("AG").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("TZ").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("JO").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("ET").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("BN").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("GY").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("GT").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("NG").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("AZ").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("IN").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("TW").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("BA").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("VN").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("ID").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("CR").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("CL").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("PK").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("TR").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("MA").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("RS").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("ZA").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("KE").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("EG").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("CO").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("AO").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("NE").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("SM").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("SA").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("KZ").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("EC").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("BW").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("JP").stripe_capabilities).to eq StripeMerchantAccountManager::REQUESTED_CAPABILITIES expect(Country.new("MY").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("GI").stripe_capabilities).to eq StripeMerchantAccountManager::REQUESTED_CAPABILITIES expect(Country.new("UY").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("MU").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("JM").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("OM").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("RW").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("DO").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("UZ").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("BO").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("TN").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("MD").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("PA").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("SV").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("MG").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("PY").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("GH").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("AM").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("LK").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("KW").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("MK").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("IS").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("QA").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("BS").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("LC").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("SN").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("KH").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("MN").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("GA").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("MC").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("DZ").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("MO").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("BJ").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES expect(Country.new("CI").stripe_capabilities).to eq StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES end end describe "#default_currency" do it "returns the currency which is set as default currency for all the accounts from the country" do expect(Country.new("US").default_currency).to eq Currency::USD expect(Country.new("GB").default_currency).to eq Currency::GBP expect(Country.new("AU").default_currency).to eq Currency::AUD expect(Country.new("FR").default_currency).to eq Currency::EUR expect(Country.new("TH").default_currency).to eq nil expect(Country.new("KR").default_currency).to eq nil expect(Country.new("AE").default_currency).to eq nil expect(Country.new("IL").default_currency).to eq nil expect(Country.new("TT").default_currency).to eq nil expect(Country.new("ET").default_currency).to eq nil expect(Country.new("BN").default_currency).to eq nil expect(Country.new("GY").default_currency).to eq nil expect(Country.new("GT").default_currency).to eq nil expect(Country.new("PH").default_currency).to eq nil expect(Country.new("NA").default_currency).to eq nil expect(Country.new("AG").default_currency).to eq nil expect(Country.new("TZ").default_currency).to eq nil expect(Country.new("MX").default_currency).to eq nil expect(Country.new("SE").default_currency).to eq nil expect(Country.new("RO").default_currency).to eq nil expect(Country.new("AR").default_currency).to eq nil expect(Country.new("PE").default_currency).to eq nil expect(Country.new("NO").default_currency).to eq nil expect(Country.new("IN").default_currency).to eq nil expect(Country.new("TW").default_currency).to eq nil expect(Country.new("VN").default_currency).to eq nil expect(Country.new("BD").default_currency).to eq nil expect(Country.new("BT").default_currency).to eq nil expect(Country.new("LA").default_currency).to eq nil expect(Country.new("MZ").default_currency).to eq nil expect(Country.new("LI").default_currency).to eq Currency::CHF expect(Country.new("ID").default_currency).to eq nil expect(Country.new("CR").default_currency).to eq nil expect(Country.new("CL").default_currency).to eq nil expect(Country.new("PK").default_currency).to eq nil expect(Country.new("AO").default_currency).to eq nil expect(Country.new("NE").default_currency).to eq nil expect(Country.new("SM").default_currency).to eq nil expect(Country.new("BA").default_currency).to eq nil expect(Country.new("TR").default_currency).to eq nil expect(Country.new("MA").default_currency).to eq nil expect(Country.new("RS").default_currency).to eq nil expect(Country.new("ZA").default_currency).to eq nil expect(Country.new("KE").default_currency).to eq nil expect(Country.new("EG").default_currency).to eq nil expect(Country.new("CO").default_currency).to eq nil expect(Country.new("SA").default_currency).to eq nil expect(Country.new("BW").default_currency).to eq nil expect(Country.new("KZ").default_currency).to eq nil expect(Country.new("EC").default_currency).to eq nil expect(Country.new("JP").default_currency).to eq Currency::JPY expect(Country.new("MY").default_currency).to eq nil expect(Country.new("GI").default_currency).to eq nil expect(Country.new("UY").default_currency).to eq nil expect(Country.new("MU").default_currency).to eq nil expect(Country.new("JM").default_currency).to eq nil expect(Country.new("OM").default_currency).to eq nil expect(Country.new("DO").default_currency).to eq nil expect(Country.new("UZ").default_currency).to eq nil expect(Country.new("BO").default_currency).to eq nil expect(Country.new("TN").default_currency).to eq nil expect(Country.new("RW").default_currency).to eq nil expect(Country.new("AL").default_currency).to eq nil expect(Country.new("AZ").default_currency).to eq nil expect(Country.new("BH").default_currency).to eq nil expect(Country.new("NG").default_currency).to eq nil expect(Country.new("JO").default_currency).to eq nil expect(Country.new("MD").default_currency).to eq nil expect(Country.new("PA").default_currency).to eq nil expect(Country.new("SV").default_currency).to eq nil expect(Country.new("MG").default_currency).to eq nil expect(Country.new("PY").default_currency).to eq nil expect(Country.new("GH").default_currency).to eq nil expect(Country.new("AM").default_currency).to eq nil expect(Country.new("LK").default_currency).to eq nil expect(Country.new("KW").default_currency).to eq nil expect(Country.new("MK").default_currency).to eq nil expect(Country.new("IS").default_currency).to eq nil expect(Country.new("QA").default_currency).to eq nil expect(Country.new("BS").default_currency).to eq nil expect(Country.new("LC").default_currency).to eq nil expect(Country.new("SN").default_currency).to eq nil expect(Country.new("KH").default_currency).to eq nil expect(Country.new("MN").default_currency).to eq nil expect(Country.new("GA").default_currency).to eq nil expect(Country.new("MC").default_currency).to eq nil expect(Country.new("DZ").default_currency).to eq nil expect(Country.new("MO").default_currency).to eq nil expect(Country.new("BJ").default_currency).to eq nil expect(Country.new("CI").default_currency).to eq nil expect(Country.new("BG").default_currency).to eq nil end end describe "#payout_currency" do it "returns the currency which is used for sending stripe payouts to the country" do expect(Country.new("US").payout_currency).to eq Currency::USD expect(Country.new("GB").payout_currency).to eq Currency::GBP expect(Country.new("AU").payout_currency).to eq Currency::AUD expect(Country.new("FR").payout_currency).to eq Currency::EUR expect(Country.new("TH").payout_currency).to eq Currency::THB expect(Country.new("KR").payout_currency).to eq Currency::KRW expect(Country.new("AE").payout_currency).to eq Currency::AED expect(Country.new("IL").payout_currency).to eq Currency::ILS expect(Country.new("TT").payout_currency).to eq Currency::TTD expect(Country.new("PH").payout_currency).to eq Currency::PHP expect(Country.new("AL").payout_currency).to eq Currency::ALL expect(Country.new("JO").payout_currency).to eq Currency::JOD expect(Country.new("AZ").payout_currency).to eq Currency::AZN expect(Country.new("BH").payout_currency).to eq Currency::BHD expect(Country.new("ET").payout_currency).to eq Currency::ETB expect(Country.new("BN").payout_currency).to eq Currency::BND expect(Country.new("GY").payout_currency).to eq Currency::GYD expect(Country.new("GT").payout_currency).to eq Currency::GTQ expect(Country.new("NG").payout_currency).to eq Currency::NGN expect(Country.new("MX").payout_currency).to eq Currency::MXN expect(Country.new("SE").payout_currency).to eq Currency::SEK expect(Country.new("NA").payout_currency).to eq Currency::NAD expect(Country.new("AG").payout_currency).to eq Currency::XCD expect(Country.new("TZ").payout_currency).to eq Currency::TZS
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/invite_spec.rb
spec/models/invite_spec.rb
# frozen_string_literal: true require "spec_helper" describe Invite do describe "scopes" do before do @invite_sent = create(:invite) @invite_signed_up = create(:invite, invite_state: "signed_up") end describe "#invitation_sent" do it "returns only the records with status invitation_sent" do expect(Invite.invitation_sent.to_a).to eq([@invite_sent]) end end describe "#signed_up" do it "returns only the records with status signed_up" do expect(Invite.signed_up.to_a).to eq([@invite_signed_up]) end end end describe "#mark_signed_up" do it "transitions the status correctly and sends an email in case of success" do user = create(:user) invite = create(:invite, sender_id: user.id) invited_user = create(:user, email: invite.receiver_email) invite.update!(receiver_id: invited_user.id) expect do expect do invite.mark_signed_up end.to change { invite.reload.signed_up? }.from(false).to(true) end.to have_enqueued_mail(InviteMailer, :receiver_signed_up).with(invite.id) end end describe "#invite_state_text" do it "returns the correct text depending on the status of the invite" do invite = build(:invite) expect(invite.invite_state_text).to eq("Invitation sent") invite.invite_state = "signed_up" expect(invite.invite_state_text).to eq("Signed up!") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/kazakhstan_bank_account_spec.rb
spec/models/kazakhstan_bank_account_spec.rb
# frozen_string_literal: true describe KazakhstanBankAccount do describe "#bank_account_type" do it "returns KZ" do expect(create(:kazakhstan_bank_account).bank_account_type).to eq("KZ") end end describe "#country" do it "returns KZ" do expect(create(:kazakhstan_bank_account).country).to eq("KZ") end end describe "#currency" do it "returns kzt" do expect(create(:kazakhstan_bank_account).currency).to eq("kzt") end end describe "#routing_number" do it "returns valid for 8 to 11 characters" do expect(create(:kazakhstan_bank_account, bank_code: "AAAAKZKZ")).to be_valid expect(create(:kazakhstan_bank_account, bank_code: "AAAAKZKZX")).to be_valid expect(create(:kazakhstan_bank_account, bank_code: "AAAAKZKZXX")).to be_valid expect(create(:kazakhstan_bank_account, bank_code: "AAAAKZKZXXX")).to be_valid end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:kazakhstan_bank_account, account_number_last_four: "0123").account_number_visual).to eq("KZ******0123") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/zip_tax_rate_spec.rb
spec/models/zip_tax_rate_spec.rb
# frozen_string_literal: true require "spec_helper" describe ZipTaxRate do it "requires a combined rate" do ztr = ZipTaxRate.new(zip_code: "90210", country: "US", state: "CA", is_seller_responsible: true) expect(ztr).to_not be_valid end describe "flags" do it "has `is_seller_responsible` flag" do flag_on = create(:zip_tax_rate, country: "GB", combined_rate: 0.1, is_seller_responsible: true) flag_off = create(:zip_tax_rate, country: "IT", combined_rate: 0.22, is_seller_responsible: false) expect(flag_on.is_seller_responsible).to be true expect(flag_off.is_seller_responsible).to be false end it "has `is_epublication_rate` flag" do flag_on = create(:zip_tax_rate, country: "AT", combined_rate: 0.1, is_epublication_rate: true) flag_off = create(:zip_tax_rate, country: "AT", combined_rate: 0.2, is_epublication_rate: false) expect(flag_on.is_epublication_rate).to be true expect(flag_off.is_epublication_rate).to be false end end describe "applicable years" do it "supports applicable years" do ztr = create(:zip_tax_rate, country: "SG", state: nil, zip_code: nil, combined_rate: 0.08, is_seller_responsible: false, applicable_years: [2023]) expect(ztr.applicable_years).to eq([2023]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/signup_event_spec.rb
spec/models/signup_event_spec.rb
# frozen_string_literal: true require "spec_helper" describe SignupEvent do it "is an Event" do expect(build(:signup_event).is_a?(Event)).to eq(true) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/bundle_product_spec.rb
spec/models/bundle_product_spec.rb
# frozen_string_literal: true require "spec_helper" describe BundleProduct do describe "#standalone_price_cents" do let(:bundle_product) { create(:bundle_product, quantity: 2) } it "returns the correct price" do expect(bundle_product.standalone_price_cents).to eq(200) end context "when the product has a variant" do before do bundle_product.product = create(:product_with_digital_versions, user: bundle_product.bundle.user) bundle_product.variant = bundle_product.product.alive_variants.first bundle_product.variant.price_difference_cents = 100 end it "returns the correct price" do expect(bundle_product.standalone_price_cents).to eq(400) end end end describe "#in_order" do let!(:bundle_product1) { create(:bundle_product, position: 1) } let!(:bundle_product2) { create(:bundle_product, position: 0) } let!(:bundle_product3) { create(:bundle_product, position: 2) } it "returns the bundle products in order" do expect(BundleProduct.where(id: [bundle_product1.id, bundle_product2.id, bundle_product3.id]).in_order) .to eq([bundle_product2, bundle_product1, bundle_product3]) end end describe "validations" do let(:bundle_product) { create(:bundle_product) } context "when the product doesn't belong to the bundle's user" do before do bundle_product.product = create(:product) end it "adds an error" do expect(bundle_product).to_not be_valid expect(bundle_product.errors.full_messages.first).to eq("The product must belong to the bundle's seller") end end context "when the product is versioned but no variant is set" do before do bundle_product.product = create(:product_with_digital_versions, user: bundle_product.bundle.user) end it "adds an error" do expect(bundle_product).to_not be_valid expect(bundle_product.errors.full_messages.first).to eq("Bundle product must have variant specified for versioned product") end end context "when the product is versioned and a variant is set" do before do bundle_product.product = create(:product_with_digital_versions, user: bundle_product.bundle.user) bundle_product.variant = bundle_product.product.alive_variants.first end it "doesn't add an error" do expect(bundle_product).to be_valid end end context "when the variant doesn't belong to the product" do before do bundle_product.variant = create(:variant) end it "adds an error" do expect(bundle_product).to_not be_valid expect(bundle_product.errors.full_messages.first).to eq("The bundle product's variant must belong to its product") end end context "when the product is a bundle" do before do bundle_product.product.is_bundle = true end it "adds an error" do expect(bundle_product).to_not be_valid expect(bundle_product.errors.full_messages.first).to eq("A bundle product cannot be added to a bundle") end end context "when the product is a subscription" do before do bundle_product.product.is_recurring_billing = true end it "adds an error" do expect(bundle_product).to_not be_valid expect(bundle_product.errors.full_messages.first).to eq("A subscription product cannot be added to a bundle") end end context "when the product is a call" do before do bundle_product.product = create(:call_product) end it "adds an error" do expect(bundle_product).to_not be_valid expect(bundle_product.errors.full_messages).to include("A call product cannot be added to a bundle") end end context "when a bundle product already exists for the product" do let(:duplicate_bundle_product) { build(:bundle_product, product: bundle_product.product, bundle: bundle_product.bundle) } it "adds an error" do expect(duplicate_bundle_product).to_not be_valid expect(duplicate_bundle_product.errors.full_messages.first).to eq("Product is already in bundle") end end context "when the bundle is not a bundle" do before do bundle_product.bundle.is_bundle = false end it "adds an error" do expect(bundle_product).to_not be_valid expect(bundle_product.errors.full_messages.first).to eq("Bundle products can only be added to bundles") end end context "when the bundle is a bundle" do before do bundle_product.bundle.is_bundle = true end it "doesn't add an error" do expect(bundle_product).to be_valid end end describe "installment plans" do let(:seller) { create(:user, :eligible_for_service_products) } let(:bundle) { create(:product, :bundle, user: seller, price_cents: 1000) } let(:eligible_product) { create(:product, native_type: Link::NATIVE_TYPE_DIGITAL, user: seller) } let(:ineligible_product) { create(:commission_product, user: seller) } context "when the bundle has an installment plan" do let!(:installment_plan) { create(:product_installment_plan, link: bundle) } context "when the product is eligible for installment plans" do it "doesn't add an error" do bundle_product = build(:bundle_product, bundle: bundle, product: eligible_product) expect(bundle_product).to be_valid end end context "when the product is not eligible for installment plans" do it "adds an error" do bundle_product = build(:bundle_product, bundle: bundle, product: ineligible_product) expect(bundle_product).not_to be_valid expect(bundle_product.errors.full_messages).to include("Installment plan is not available for the bundled product: #{ineligible_product.name}") end end end context "when the bundle has no installment plan" do it "doesn't validate product eligibility for installment plans" do bundle_product = build(:bundle_product, bundle: bundle, product: ineligible_product) expect(bundle_product).to be_valid 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/models/bahamas_bank_account_spec.rb
spec/models/bahamas_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe BahamasBankAccount do describe "#bank_account_type" do it "returns BS" do expect(create(:bahamas_bank_account).bank_account_type).to eq("BS") end end describe "#country" do it "returns BS" do expect(create(:bahamas_bank_account).country).to eq("BS") end end describe "#currency" do it "returns bsd" do expect(create(:bahamas_bank_account).currency).to eq("bsd") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:bahamas_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAABSNSXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:bahamas_bank_account, account_number_last_four: "1234").account_number_visual).to eq("******1234") end end describe "#validate_bank_code" do it "allows 8 to 11 characters only" do expect(build(:bahamas_bank_account, bank_code: "AAAABSNS")).to be_valid expect(build(:bahamas_bank_account, bank_code: "AAAABSNSXXX")).to be_valid expect(build(:bahamas_bank_account, bank_code: "AAAABS")).not_to be_valid expect(build(:bahamas_bank_account, bank_code: "AAAABSNSXXXX")).not_to be_valid end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/utm_link_driven_sale_spec.rb
spec/models/utm_link_driven_sale_spec.rb
# frozen_string_literal: true require "spec_helper" describe UtmLinkDrivenSale do describe "associations" do it { is_expected.to belong_to(:utm_link).optional(false) } it { is_expected.to belong_to(:utm_link_visit).optional(false) } it { is_expected.to belong_to(:purchase).optional(false) } end describe "validations" do context "purchase_id and utm_link_visit_id uniqueness" do subject(:sale) { build(:utm_link_driven_sale, utm_link: create(:utm_link)) } it { is_expected.to validate_uniqueness_of(:purchase_id).scoped_to(:utm_link_visit_id) } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/user_compliance_info_request_spec.rb
spec/models/user_compliance_info_request_spec.rb
# frozen_string_literal: true require "spec_helper" describe UserComplianceInfoRequest do describe "only_needs_field_to_be_partially_provided" do let(:request_1) { create(:user_compliance_info_request, only_needs_field_to_be_partially_provided: true) } let(:request_2) { create(:user_compliance_info_request, only_needs_field_to_be_partially_provided: false) } let(:request_3) { create(:user_compliance_info_request, only_needs_field_to_be_partially_provided: true) } let(:request_4) { create(:user_compliance_info_request, only_needs_field_to_be_partially_provided: false) } let(:request_5) { create(:user_compliance_info_request, only_needs_field_to_be_partially_provided: nil) } before do request_1 request_2 request_3 request_4 request_5 end describe "no parameter given" do it "returns the requests that only need the field to be partially provided" do expect(described_class.only_needs_field_to_be_partially_provided).to eq([request_1, request_3]) end end describe "true given" do it "returns the requests that only need the field to be partially provided" do expect(described_class.only_needs_field_to_be_partially_provided(true)).to eq([request_1, request_3]) end end describe "false given" do it "returns the requests that don't only need the field to be partially provided" do expect(described_class.only_needs_field_to_be_partially_provided(false)).to eq([request_2, request_4, request_5]) end end end describe "emails_sent_at" do let(:request) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::FIRST_NAME) } let(:request_email_sent_at) { Time.current } before do request.record_email_sent!(request_email_sent_at) end it "returns an array of times when emails had been sent at" do request_fresh = UserComplianceInfoRequest.find(request.id) expect(request_fresh.emails_sent_at).to eq([request_email_sent_at.change(usec: 0)]) expect(request_fresh.emails_sent_at[0]).to be_a(Time) end end describe "last_email_sent_at" do let(:request) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::FIRST_NAME) } describe "multiple email sent ats have been have been recorded" do let(:request_email_sent_at_1) { 2.days.ago } let(:request_email_sent_at_2) { 1.day.ago } before do request.record_email_sent!(request_email_sent_at_1) request.record_email_sent!(request_email_sent_at_2) end it "returns an array of times when emails had been sent at" do expect(request.last_email_sent_at).to be_within(1.second).of(request_email_sent_at_2) end end end describe "record_email_sent!" do let(:request) { create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::Individual::FIRST_NAME) } describe "with no parameters" do let(:time_now) { Time.current } before do request.record_email_sent! travel_to(time_now) do request.record_email_sent! end end it "appends the time now to the list of email sent at times" do expect(request.emails_sent_at[1]).to be_within(1.second).of(time_now) end end describe "with a time" do let(:time_provided) { Time.current } before do request.record_email_sent! request.record_email_sent!(time_provided) end it "appends the time provided to the list of email sent at times" do expect(request.emails_sent_at[1]).to be_within(1.second).of(time_provided) end end end describe "handle_new_user_compliance_info" do let(:user) { create(:user) } let(:request_1) { create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Individual::FIRST_NAME) } let(:request_2) { create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Individual::LAST_NAME) } let(:request_3) { create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Business::NAME) } let(:request_4) { create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Individual::TAX_ID) } let(:request_5) do create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Individual::TAX_ID, only_needs_field_to_be_partially_provided: true) end let(:request_6) { create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Business::TAX_ID) } let(:request_7) { create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::BANK_ACCOUNT) } let(:user_compliance_info) do create(:user_compliance_info_empty, user:, first_name: "Maxwell", last_name: "Dudeswell", individual_tax_id: "1234", business_tax_id: "") end before do request_1 request_2 request_3 request_4 request_5 request_6 request_7 user_compliance_info end it "marks provided any outstanding request for a field not blank" do expect(request_1.reload.state).to eq("provided") expect(request_2.reload.state).to eq("provided") end it "sets the provided at for requests that are closed" do expect(request_1.reload.provided_at).not_to be_nil expect(request_1.reload.provided_at).to be_a(Time) expect(request_2.reload.provided_at).not_to be_nil expect(request_2.reload.provided_at).to be_a(Time) end it "does not change any outstanding request for fields not provided" do expect(request_3.reload.state).to eq("requested") end it "marks provided any outstanding request for an encrypted field" do expect(request_6.reload.state).to eq("requested") expect(request_7.reload.state).to eq("requested") end it "marks provided any outstanding request for a field not blank partially provided" do expect(request_4.reload.state).to eq("provided") expect(request_5.reload.state).to eq("provided") end describe "field has an expected length and can be partially provided" do let(:user_compliance_info) do create(:user_compliance_info_empty, user:, country: "United States", first_name: "Maxwell", last_name: "Dudeswell", individual_tax_id: "1234", business_tax_id: "") end it "marks provided any outstanding request for a field not blank partially provided" do expect(request_4.reload.state).to eq("requested") expect(request_5.reload.state).to eq("provided") end end describe "field has an expected length and can be partially provided, but is provided in full" do let(:user_compliance_info) do create(:user_compliance_info_empty, user:, country: "United States", first_name: "Maxwell", last_name: "Dudeswell", individual_tax_id: "123456789", business_tax_id: "") end it "marks provided any outstanding request for a field not blank partially provided" do expect(request_4.reload.state).to eq("provided") expect(request_5.reload.state).to eq("provided") end end describe "field has an expected length and can be partially provided and has separators in it" do let(:user_compliance_info) do create(:user_compliance_info_empty, user:, country: "United States", first_name: "Maxwell", last_name: "Dudeswell", individual_tax_id: "12-34", business_tax_id: "") end it "marks provided any outstanding request for a field not blank partially provided" do expect(request_4.reload.state).to eq("requested") expect(request_5.reload.state).to eq("provided") end end end describe "handle_new_bank_account" do let(:user) { create(:user) } let(:request_1) { create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::BANK_ACCOUNT) } let(:bank_account) { create(:ach_account, user:) } before do request_1 bank_account end it "marks provided any outstanding request for a bank account" do expect(request_1.reload.state).to eq("provided") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/upsell_variant_spec.rb
spec/models/upsell_variant_spec.rb
# frozen_string_literal: true require "spec_helper" describe UpsellVariant do describe "validations" do context "when the variants don't belong to the upsell's offered product" do before do @upsell_variant = build(:upsell_variant, selected_variant: create(:variant), offered_variant: create(:variant)) end it "adds an error" do expect(@upsell_variant.valid?).to eq(false) expect(@upsell_variant.errors.full_messages.first).to eq("The selected variant and the offered variant must belong to the upsell's offered product.") end end end context "when the variants belong to the upsell's offered product" do before do @seller = create(:user) @product = create(:product, user: @seller) @upsell = create(:upsell, product: @product, seller: @seller) @upsell_variant = build(:upsell_variant, upsell: @upsell, selected_variant: create(:variant, variant_category: create(:variant_category, link: @product)), offered_variant: create(:variant, variant_category: create(:variant_category, link: @product))) end it "doesn't add an error" do expect(@upsell_variant.valid?).to eq(true) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/azerbaijan_bank_account_spec.rb
spec/models/azerbaijan_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe AzerbaijanBankAccount do describe "#bank_account_type" do it "returns AZ" do expect(create(:azerbaijan_bank_account).bank_account_type).to eq("AZ") end end describe "#country" do it "returns AZ" do expect(create(:azerbaijan_bank_account).country).to eq("AZ") end end describe "#currency" do it "returns azn" do expect(create(:azerbaijan_bank_account).currency).to eq("azn") end end describe "#routing_number" do it "returns valid for 6 digits with hyphen after 3" do ba = create(:azerbaijan_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("123456-123456") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:azerbaijan_bank_account, account_number_last_four: "7890").account_number_visual).to eq("AZ******7890") end end describe "#validate_bank_code" do it "allows 6 digits only" do expect(build(:azerbaijan_bank_account, bank_code: "123456")).to be_valid expect(build(:azerbaijan_bank_account, bank_code: "12345")).not_to be_valid expect(build(:azerbaijan_bank_account, bank_code: "1234567")).not_to be_valid expect(build(:azerbaijan_bank_account, bank_code: "ABCDEF")).not_to be_valid end end describe "#validate_branch_code" do it "allows 6 digits only" do expect(build(:azerbaijan_bank_account, branch_code: "123456")).to be_valid expect(build(:azerbaijan_bank_account, branch_code: "12345")).not_to be_valid expect(build(:azerbaijan_bank_account, branch_code: "1234567")).not_to be_valid expect(build(:azerbaijan_bank_account, branch_code: "ABCDEF")).not_to be_valid end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/kuwait_bank_account_spec.rb
spec/models/kuwait_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe KuwaitBankAccount do describe "#bank_account_type" do it "returns KW" do expect(create(:kuwait_bank_account).bank_account_type).to eq("KW") end end describe "#country" do it "returns KW" do expect(create(:kuwait_bank_account).country).to eq("KW") end end describe "#currency" do it "returns kwd" do expect(create(:kuwait_bank_account).currency).to eq("kwd") end end describe "#routing_number" do it "returns valid for 10 characters" do ba = create(:kuwait_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAAKWKWXYZ") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:kuwait_bank_account, account_number_last_four: "0101").account_number_visual).to eq("******0101") end end describe "#validate_bank_code" do it "allows only 8 to 11 characters" do expect(build(:kuwait_bank_account, bank_code: "AAAAKWKWXYZ")).to be_valid expect(build(:kuwait_bank_account, bank_code: "AAA0000X")).to be_valid expect(build(:kuwait_bank_account, bank_code: "AAAA0000XXXX")).not_to be_valid expect(build(:kuwait_bank_account, bank_code: "AAAA000")).not_to be_valid end end describe "#validate_account_number" do it "allows only 30 characters in the correct format" do expect(build(:kuwait_bank_account, account_number: "KW81CBKU0000000000001234560101")).to be_valid expect(build(:kuwait_bank_account, account_number: "KW81CBKU00000000000012345601012")).not_to be_valid expect(build(:kuwait_bank_account, account_number: "KW81CBKU000000000000123456")).not_to be_valid expect(build(:kuwait_bank_account, account_number: "KW81CBKU0000000000001234560101234")).not_to be_valid end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/rwanda_bank_account_spec.rb
spec/models/rwanda_bank_account_spec.rb
# frozen_string_literal: true describe RwandaBankAccount do describe "#bank_account_type" do it "returns RW" do expect(create(:rwanda_bank_account).bank_account_type).to eq("RW") end end describe "#country" do it "returns RW" do expect(create(:rwanda_bank_account).country).to eq("RW") end end describe "#currency" do it "returns rwf" do expect(create(:rwanda_bank_account).currency).to eq("rwf") end end describe "#routing_number" do it "returns valid for 8 to 11 characters" do expect(build(:rwanda_bank_account, bank_code: "AAAARWRWXXX")).to be_valid expect(build(:rwanda_bank_account, bank_code: "AAAARWRW")).to be_valid expect(build(:rwanda_bank_account, bank_code: "AAAARWRWXXXX")).not_to be_valid expect(build(:rwanda_bank_account, bank_code: "AAAARWR")).not_to be_valid end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:rwanda_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:rwanda_bank_account)).to be_valid expect(build(:rwanda_bank_account, account_number: "1")).to be_valid expect(build(:rwanda_bank_account, account_number: "12345")).to be_valid expect(build(:rwanda_bank_account, account_number: "0001234567")).to be_valid expect(build(:rwanda_bank_account, account_number: "123456789012345")).to be_valid end it "rejects records that do not match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) rw_bank_account = build(:rwanda_bank_account, account_number: "ABCDEF") expect(rw_bank_account).not_to be_valid expect(rw_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") rw_bank_account = build(:rwanda_bank_account, account_number: "1234567890123456") expect(rw_bank_account).not_to be_valid expect(rw_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") rw_bank_account = build(:rwanda_bank_account, account_number: "ABC000123456789") expect(rw_bank_account).not_to be_valid expect(rw_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/purchase_integration_spec.rb
spec/models/purchase_integration_spec.rb
# frozen_string_literal: true require "spec_helper" describe PurchaseIntegration do describe "validations" do it "raises error if purchase_id is not present" do purchase_integration = build(:purchase_integration, purchase_id: nil, integration_id: create(:discord_integration).id) expect(purchase_integration.valid?).to eq(false) expect(purchase_integration.errors.full_messages).to include("Purchase can't be blank") end it "raises error if integration_id is not present" do purchase_integration = build(:purchase_integration, purchase_id: create(:purchase).id, integration_id: nil) expect(purchase_integration.valid?).to eq(false) expect(purchase_integration.errors.full_messages).to include("Integration can't be blank") end it "raises error if (purchase_id, integration_id) is not unique" do purchase_integration_1 = create(:discord_purchase_integration) purchase_integration_2 = build(:purchase_integration, purchase: purchase_integration_1.purchase, integration: purchase_integration_1.integration) expect(purchase_integration_2.valid?).to eq(false) expect(purchase_integration_2.errors.full_messages).to include("Integration has already been taken") end it "is successful if (purchase_id, integration_id) is not unique but all clashing entries have been deleted" do purchase_integration_1 = create(:discord_purchase_integration, deleted_at: 1.day.ago) purchase_integration_2 = create(:purchase_integration, purchase: purchase_integration_1.purchase, integration: purchase_integration_1.integration, discord_user_id: "user-1") expect(purchase_integration_2).to be_valid expect(purchase_integration_2).to be_persisted end it "raises error if same purchase has different integrations of same type" do purchase_integration_1 = create(:discord_purchase_integration) purchase_integration_2 = build(:purchase_integration, purchase: purchase_integration_1.purchase, integration: create(:discord_integration), discord_user_id: "user-1") expect(purchase_integration_2.valid?).to eq(false) expect(purchase_integration_2.errors.full_messages).to include("Purchase cannot have multiple integrations of the same type.") end it "is successful if same purchase has integrations of different type" do purchase_integration = create(:discord_purchase_integration) integration = create(:circle_integration) purchase_integration.purchase.link.active_integrations << integration purchase_integration_2 = create(:purchase_integration, purchase: purchase_integration.purchase, integration:) expect(purchase_integration_2).to be_valid expect(purchase_integration_2).to be_persisted end it "raises error if discord_user_id is not present for a discord integration" do purchase_integration = build(:purchase_integration, integration: create(:discord_integration)) expect(purchase_integration.valid?).to eq(false) expect(purchase_integration.errors.full_messages).to include("Discord user can't be blank") end it "raises error if purchase and the associated standalone product have different integrations" do product = create(:product, active_integrations: [create(:discord_integration)]) purchase_integration = build(:purchase_integration, integration: create(:discord_integration), purchase: create(:purchase, link: product)) expect(purchase_integration.valid?).to eq(false) expect(purchase_integration.errors.full_messages).to include("Integration does not match the one available for the associated product.") end it "raises error if purchase and the associated variant have different integrations" do product = create(:product_with_digital_versions, active_integrations: [create(:discord_integration)]) purchase_integration = build(:purchase_integration, integration: create(:discord_integration), purchase: create(:purchase, link: product, variant_attributes: [product.alive_variants.first])) expect(purchase_integration.valid?).to eq(false) expect(purchase_integration.errors.full_messages).to include("Integration does not match the one available for the associated product.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/yearly_stat_spec.rb
spec/models/yearly_stat_spec.rb
# frozen_string_literal: true require "spec_helper" describe YearlyStat do describe "associations" do it { is_expected.to belong_to(:user) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/charge_spec.rb
spec/models/charge_spec.rb
# frozen_string_literal: true require "spec_helper" describe Charge, :vcr do include StripeChargesHelper describe "validations" do it "validates presence of required attributes" do charge = described_class.new expect(charge).to be_invalid expect(charge.errors.messages).to eq( order: ["must exist"], seller: ["must exist"], ) end end describe "#statement_description" do it "returns the name of the seller" do seller = create(:user, name: "US Seller") expect(create(:charge, seller:).statement_description).to eq("US Seller") end it "returns the username of the seller if name is not present" do seller = create(:user, username: "seller1") expect(create(:charge, seller:).statement_description).to eq("seller1") seller = create(:user, username: nil) expect(create(:charge, seller:).statement_description).to eq(seller.external_id) end end describe "#shipping_cents" do let(:charge) { create(:charge) } before do charge.purchases << create(:purchase, shipping_cents: 499) charge.purchases << create(:purchase, shipping_cents: 1099) end it "sums shipping_cents from all purchases" do expect(charge.shipping_cents).to eq(1598) end end describe "#has_invoice?" do let(:charge) { create(:charge) } before do charge.purchases << create(:free_purchase) charge.purchases << create(:free_trial_membership_purchase) end it "returns false when nothing is charged" do expect(charge.has_invoice?).to be(false) end context "when there is at least one purchase with a cost" do before do charge.purchases << create(:purchase) end it "returns true" do expect(charge.has_invoice?).to be(true) end end end describe "#taxable?" do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase]) } context "when the purchase is not taxable" do it "returns false" do expect(charge.taxable?).to be(false) end end context "when a purchase is taxable" do let(:taxable_purchase) { create(:purchase, was_purchase_taxable: true) } before do charge.purchases << taxable_purchase end it "returns true" do expect(charge.taxable?).to be(true) end end end describe "#multi_item_charge?" do context "with a single purchase" do let(:charge) { create(:charge, purchases: [create(:purchase)]) } it "returns false" do expect(charge.multi_item_charge?).to be(false) end end context "with multiple purchases" do let(:charge) { create(:charge, purchases: [create(:purchase), create(:purchase)]) } it "returns true" do expect(charge.multi_item_charge?).to be(true) end end end describe "#require_shipping?" do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase]) } context "when the product is not physical" do it "returns false" do expect(charge.require_shipping?).to be(false) end end context "when a second purchase is for a physical product" do let(:physical_product) { create(:product, :is_physical) } let(:physical_purchase) { create(:physical_purchase, link: physical_product) } before do charge.purchases << physical_purchase end it "returns true" do expect(charge.require_shipping?).to be(true) end end end describe "is_direct_to_australian_customer?" do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase]) } context "when the product is not physical" do it "returns false" do expect(charge.is_direct_to_australian_customer?).to be(false) end end context "when a second purchase is for a physical product" do let(:physical_product) { create(:product, :is_physical) } let(:physical_purchase) { create(:physical_purchase, link: physical_product) } before do charge.purchases << physical_purchase end context "when the country is not Australia" do it "returns true" do expect(charge.is_direct_to_australian_customer?).to be(false) end end context "when country is Australia" do before do physical_purchase.update!(country: Compliance::Countries::AUS.common_name) end it "returns true" do expect(charge.is_direct_to_australian_customer?).to be(true) end end end end describe "#taxed_by_gumroad?" do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase]) } context "when the purchase doesn't have tax" do it "returns false" do expect(charge.taxed_by_gumroad?).to be(false) end end context "when the purchase has tax" do before do purchase.update!(gumroad_tax_cents: 100, was_purchase_taxable: true) end it "returns true" do expect(charge.taxed_by_gumroad?).to be(true) end end end describe "#external_id_for_invoice" do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase]) } it "returns the external_id of the purchase" do expect(charge.external_id_for_invoice).to eq(purchase.external_id) end end describe "#external_id_numeric_for_invoice" do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase]) } it "returns the external_id_numeric of the purchase" do expect(charge.external_id_numeric_for_invoice).to eq(purchase.external_id_numeric.to_s) end end describe "#refund_gumroad_taxes!" do let(:user) { create(:user) } let(:note) { "sample note" } let(:business_vat_id) { "VAT12345" } let(:free_purchase) { create(:free_purchase) } let(:purchase_without_tax) { create(:purchase) } let(:purchase_with_tax) { create(:purchase, gumroad_tax_cents: 100, was_purchase_taxable: true) } let(:charge) { create(:charge, purchases: [free_purchase, purchase_without_tax, purchase_with_tax]) } it "calls refund_gumroad_taxes! on eligible purchases" do expect_any_instance_of(Purchase).to receive(:refund_gumroad_taxes!).once charge.refund_gumroad_taxes!(refunding_user_id: user.id, note: note, business_vat_id: business_vat_id) end end describe "Purchase attributes" do let(:failed_purchase) { create(:failed_purchase) } let(:free_purchase) { create(:free_purchase, country: "France") } let(:paid_purchase) { create(:purchase, country: "France") } let(:taxable_purchase) { create(:purchase, was_purchase_taxable: true, country: "France") } let(:business_purchase) do purchase = create(:purchase, country: "France") purchase.update!(purchase_sales_tax_info: PurchaseSalesTaxInfo.new(business_vat_id: "VAT12345")) purchase end let(:charge) { create(:charge, purchases: [free_purchase, paid_purchase, taxable_purchase, business_purchase]) } it "returns the correct purchase attributes" do expect(charge.send(:purchase_as_chargeable)).to eq(free_purchase) expect(charge.full_name).to eq(free_purchase.full_name) expect(charge.purchaser).to eq(free_purchase.purchaser) expect(charge.send(:purchase_with_tax_as_chargeable)).to eq(taxable_purchase) expect(charge.tax_label_with_creator_tax_info).to eq(taxable_purchase.tax_label_with_creator_tax_info) expect(charge.purchase_sales_tax_info).to eq(business_purchase.purchase_sales_tax_info) expect(charge.send(:purchase_with_shipping_as_chargeable)).to eq(nil) expect(charge.send(:purchase_with_address_as_chargeable)).to eq(free_purchase) expect(charge.street_address).to eq(nil) expect(charge.city).to eq(nil) expect(charge.state).to eq(nil) expect(charge.zip_code).to eq(nil) expect(charge.country).to eq("France") expect(charge.state_or_from_ip_address).to eq(free_purchase.state_or_from_ip_address) expect(charge.country_or_ip_country).to eq(free_purchase.country_or_ip_country) end context "with physical purchase" do let(:physical_product) { create(:product, :is_physical) } let(:physical_purchase) { create(:physical_purchase, link: physical_product) } let(:charge) { create(:charge, purchases: [free_purchase, paid_purchase, taxable_purchase, physical_purchase]) } it "returns the correct purchase attributes" do expect(charge.send(:purchase_as_chargeable)).to eq(free_purchase) expect(charge.full_name).to eq(free_purchase.full_name) expect(charge.purchaser).to eq(free_purchase.purchaser) expect(charge.send(:purchase_with_tax_as_chargeable)).to eq(taxable_purchase) expect(charge.tax_label_with_creator_tax_info).to eq(taxable_purchase.tax_label_with_creator_tax_info) expect(charge.purchase_sales_tax_info).to eq(taxable_purchase.purchase_sales_tax_info) expect(charge.send(:purchase_with_shipping_as_chargeable)).to eq(physical_purchase) expect(charge.send(:purchase_with_address_as_chargeable)).to eq(physical_purchase) expect(charge.street_address).to eq(physical_purchase.street_address) expect(charge.city).to eq(physical_purchase.city) expect(charge.state).to eq(physical_purchase.state) expect(charge.zip_code).to eq(physical_purchase.zip_code) expect(charge.country).to eq(physical_purchase.country) expect(charge.state_or_from_ip_address).to eq(physical_purchase.state_or_from_ip_address) expect(charge.country_or_ip_country).to eq(physical_purchase.country_or_ip_country) end end end describe "#upload_invoice_pdf" do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase, create(:purchase)]) } before(:each) do @s3_object = Aws::S3::Resource.new.bucket("gumroad-specs").object("specs/purchase-invoice-spec-#{SecureRandom.hex(18)}") s3_bucket_double = double allow(Aws::S3::Resource).to receive_message_chain(:new, :bucket).with(INVOICES_S3_BUCKET).and_return(s3_bucket_double) expect(s3_bucket_double).to receive_message_chain(:object).and_return(@s3_object) end it "writes the passed file to S3 and returns the S3 object" do file = File.open(Rails.root.join("spec", "support", "fixtures", "smaller.png")) result = charge.upload_invoice_pdf(file) expect(result).to be(@s3_object) expect(result.content_length).to eq(file.size) end end describe "#purchase_as_chargeable" do let(:purchase) { create(:failed_purchase) } let(:test_purchase) { create(:test_purchase) } let(:paid_purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase, test_purchase, paid_purchase]) } it "returns the first successful purchase" do expect(charge.send(:purchase_as_chargeable)).to eq(test_purchase) end end describe "#purchase_with_shipping_as_chargeable" do let(:purchase) { create(:failed_purchase) } let(:free_purchase) { create(:free_purchase) } let(:charge) { create(:charge, purchases: [purchase, free_purchase]) } context "without a successful physical purchase" do it "returns nil" do expect(charge.send(:purchase_with_shipping_as_chargeable)).to be_nil end end context "with a successful physical purchase" do let(:physical_product) { create(:product, :is_physical) } let(:physical_purchase) { create(:physical_purchase, link: physical_product) } before do charge.purchases << physical_purchase end it "returns the physical purchase" do expect(charge.send(:purchase_with_shipping_as_chargeable)).to eq(physical_purchase) end end end describe "#update_charge_details_from_processor!" do let(:charge) { create(:charge) } let(:stripe_charge) do stripe_payment_intent = create_stripe_payment_intent( StripePaymentMethodHelper.success_charge_disputed.to_stripejs_payment_method_id, currency: "usd", amount: 10_00 ) stripe_payment_intent.confirm stripe_charge = Stripe::Charge.retrieve(id: stripe_payment_intent.latest_charge, expand: %w[balance_transaction]) StripeCharge.new(stripe_charge, stripe_charge.balance_transaction, nil, nil, nil) end it "saves the charge details from processor charge" do charge.update_charge_details_from_processor!(stripe_charge) expect(charge.reload.processor).to eq(StripeChargeProcessor.charge_processor_id) expect(charge.processor_transaction_id).to eq(stripe_charge.id) expect(charge.payment_method_fingerprint).to eq(stripe_charge.card_fingerprint) expect(charge.processor_fee_cents).to eq(stripe_charge.fee) expect(charge.processor_fee_currency).to eq(stripe_charge.fee_currency) end end describe "#purchases_requiring_stamping" do let(:seller) { create(:named_seller) } let(:product_one) { create(:product, user: seller, name: "Product One") } let(:purchase_one) { create(:purchase, link: product_one, seller: seller) } let(:product_two) { create(:product, user: seller, name: "Product Two") } let(:purchase_two) { create(:purchase, link: product_two, seller: seller) } let(:charge) { create(:charge, purchases: [purchase_one, purchase_two], seller: seller) } let(:order) { charge.order } before do charge.order.purchases << purchase_one charge.order.purchases << purchase_two end context "without stampable PDFs" do it "returns an empty array" do expect(charge.purchases_requiring_stamping).to eq([]) end end context "when a product has stampable PDF" do before do product_one.product_files << create(:readable_document, pdf_stamp_enabled: true) end context "without a URL redirect for purchase" do it "returns an empty array" do expect(charge.purchases_requiring_stamping).to eq([]) end end context "with a URL redirect for purchase" do before do purchase_one.create_url_redirect! end it "returns the purchase" do expect(charge.purchases_requiring_stamping).to eq([purchase_one]) end end end end describe "#charged_using_stripe_connect_account?" do let(:charge) { create(:charge) } context "when the merchant account is using a stripe connect account" do before do allow_any_instance_of(MerchantAccount).to receive(:is_a_stripe_connect_account?).and_return(true) end it "returns true" do expect(charge.charged_using_stripe_connect_account?).to be(true) end end context "when the merchant account is not using a stripe connect account" do before do allow_any_instance_of(MerchantAccount).to receive(:is_a_stripe_connect_account?).and_return(false) end it "returns false" do expect(charge.charged_using_stripe_connect_account?).to be(false) end end end describe "#buyer_blocked?" do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase]) } before do allow_any_instance_of(Purchase).to receive(:buyer_blocked?).and_return("buyer_blocked!") end it "returns true" do expect(charge.buyer_blocked?).to eq("buyer_blocked!") end end describe "#block_buyer!" do let(:admin) { create(:admin_user) } let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase]) } it "calls block_buyer! on the purchase" do expect_any_instance_of(Purchase).to receive(:block_buyer!).with(blocking_user_id: admin.id, comment_content: "Comment") charge.block_buyer!(blocking_user_id: admin.id, comment_content: "Comment") end end describe "#refund_for_fraud_and_block_buyer!" do let(:admin) { create(:admin_user) } let(:purchase_one) { create(:purchase) } let(:purchase_two) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase_one, purchase_two]) } it "calls refund_for_fraud for each purchase and block_buyer! once" do refund_count = 0 allow_any_instance_of(Purchase).to receive(:refund_for_fraud!) { refund_count += 1 } expect_any_instance_of(Purchase).to receive(:block_buyer!).once.with(blocking_user_id: admin.id, comment_content: nil) charge.refund_for_fraud_and_block_buyer!(admin.id) expect(refund_count).to eq(2) end end describe "#first_purchase_for_subscription" do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase]) } context "without a subscription purchase" do it "returns nil" do expect(charge.first_purchase_for_subscription).to be_nil end end context "with a subscription purchase" do let(:subscription_purchase) { create(:membership_purchase) } before do charge.purchases << subscription_purchase end it "returns the subscription purchase" do expect(charge.first_purchase_for_subscription).to eq(subscription_purchase) end end end describe "#receipt_email_info" do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase, create(:purchase)]) } context "without email info records" do it "returns nil" do expect(charge.receipt_email_info).to be_nil end end context "with email info records" do let!(:email_info) do create( :customer_email_info, purchase_id: nil, email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD, email_info_charge_attributes: { charge_id: charge.id } ) end it "returns email_info from charge" do expect(charge.receipt_email_info).to eq(email_info) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/balance_spec.rb
spec/models/balance_spec.rb
# frozen_string_literal: true require "spec_helper" describe Balance do let(:user) { create(:user) } let(:merchant_account) { create(:merchant_account, user:) } describe "validate_amounts_are_only_changed_when_unpaid" do let(:balance) { create(:balance, user:, merchant_account:, date: Date.today) } describe "new balance" do it "allows the balance creation without error" do balance end end describe "updating balance's amounts and is unpaid" do it "allows the balance's amounts to be updated" do balance.increment(:amount_cents, 1000) balance.save! end end describe "updating balance's amounts and is processing" do before do balance.mark_processing! balance.increment(:amount_cents, 1000) end it "raises an error if save! is called with the amount changed" do expect { balance.save! }.to raise_error(ActiveRecord::RecordInvalid, /Amount cents may not be changed in processing state/) end end describe "updating balance's amounts and is paid" do before do balance.mark_processing! balance.mark_paid! balance.increment(:amount_cents, 1000) end it "does not allow the balance's amounts to be updated" do expect { balance.save! }.to raise_error(ActiveRecord::RecordInvalid, /Amount cents may not be changed in paid state/) end end describe "updating balance's amounts and was paid then marked unpaid again" do before do balance.mark_processing! balance.mark_paid! balance.mark_unpaid! balance.increment(:amount_cents, 1000) end it "allows the balance's amounts to be updated" do balance.save! end end end describe "forfeited balances" do let(:balance) { create(:balance) } it "allows the balance to be forfeited" do balance.mark_forfeited! end end describe "#state" do it "has an initial state of unpaid" do expect(Balance.new.state).to eq("unpaid") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/indian_bank_account_spec.rb
spec/models/indian_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe IndianBankAccount do describe "#bank_account_type" do it "returns Indian" do expect(create(:indian_bank_account).bank_account_type).to eq("IN") end end describe "#country" do it "returns IN" do expect(create(:indian_bank_account).country).to eq("IN") end end describe "#currency" do it "returns inr" do expect(create(:indian_bank_account).currency).to eq("inr") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:indian_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("HDFC0004051") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:indian_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789") end end describe "#validate_ifsc" do it "allows 11 characters only" do expect(build(:indian_bank_account, ifsc: "HDFC0004051")).to be_valid expect(build(:indian_bank_account, ifsc: "ICIC0123456")).to be_valid expect(build(:indian_bank_account, ifsc: "HDFC00040511")).not_to be_valid expect(build(:indian_bank_account, ifsc: "HDFC000405")).not_to be_valid end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/preorder_spec.rb
spec/models/preorder_spec.rb
# frozen_string_literal: true require "spec_helper" describe Preorder, :vcr do before do $currency_namespace = Redis::Namespace.new(:currencies, redis: $redis) end describe "mobile_json_data" do it "returns proper json for a preorder without a url redirect" do good_card = build(:chargeable) link = create(:product, price_cents: 600, is_in_preorder_state: true) preorder_product = create(:preorder_link, link:) authorization_purchase = build(:purchase, link:, chargeable: good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = preorder_product.build_preorder(authorization_purchase) preorder.authorize! json_hash = preorder.mobile_json_data %w[name description unique_permalink created_at updated_at].each do |attr| attr = attr.to_sym unless %w[name description unique_permalink].include?(attr) expect(json_hash[attr]).to eq link.send(attr) end expect(json_hash[:preview_url]).to eq "" expect(json_hash[:creator_name]).to eq link.user.username expect(json_hash[:preview_oembed_url]).to eq "" expect(json_hash[:preview_height]).to eq 0 expect(json_hash[:preview_width]).to eq 0 expect(json_hash[:url_redirect_external_id]).to eq nil expect(json_hash[:file_data]).to eq nil expect(json_hash[:purchased_at]).to eq authorization_purchase.created_at preorder_data = { external_id: preorder.external_id, release_at: preorder_product.release_at } expect(json_hash[:preorder_data]).to eq preorder_data end it "returns proper json for a preorder with a url redirect post charge" do travel_to(Time.current) do good_card = build(:chargeable) link = create(:product, price_cents: 600, is_in_preorder_state: true) link.product_files << create( :product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/6996320f4de6424990904fcda5808cef/original/Don&amp;#39;t Stop.mp3" ) link.product_files << create( :product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/a1a5b8c8c38749e2b3cb27099a817517/original/Alice&#39;s Adventures in Wonderland.pdf" ) preorder_link = create(:preorder_link, link:, release_at: 2.days.from_now) authorization_purchase = build(:purchase, link:, chargeable: good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = preorder_link.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" preorder.mark_authorization_successful expect(preorder.state).to eq "authorization_successful" link.is_in_preorder_state = false link.save! purchase = preorder.charge! json_hash = preorder.mobile_json_data %w[name description unique_permalink created_at updated_at].each do |attr| attr = attr.to_sym unless %w[name description unique_permalink].include?(attr) expect(json_hash[attr]).to eq link.send(attr) end expect(json_hash[:preview_url]).to eq "" expect(json_hash[:creator_name]).to eq link.user.username expect(json_hash[:preview_oembed_url]).to eq "" expect(json_hash[:preview_height]).to eq 0 expect(json_hash[:preview_width]).to eq 0 expect(json_hash[:url_redirect_external_id]).to eq purchase.url_redirect.external_id expect(json_hash[:file_data].map { |product_file| product_file[:name] }).to eq ["Don&amp;#39;t Stop.mp3", "Alice&#39;s Adventures in Wonderland.pdf"] expect(json_hash[:purchased_at].to_i).to eq authorization_purchase.created_at.to_i expect(json_hash[:preorder_data]).to eq nil end end end describe "authorize! and charge!" do before do @product = create(:product, price_cents: 600, is_in_preorder_state: false) @preorder_product = create(:preorder_product_with_content, link: @product) @preorder_product.update(release_at: Time.current) # bypassed the creation validation @good_card = build(:chargeable) @bad_card = build(:chargeable_decline) @incorrect_cvc_card = build(:chargeable_decline_cvc_check_fails) @good_card_but_cant_charge = build(:chargeable, card: StripePaymentMethodHelper.success_charge_decline) end after do # delete this entry so that the subsequent specs don't read the value set by these specs. $currency_namespace.set("JPY", nil) end it "marks the authorization purchase and preorder as invalid because of incorrect cvc" do authorization_purchase = build(:purchase, link: @product, chargeable: @incorrect_cvc_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.errors).to be_present expect(preorder.authorization_purchase.errors).to be_present expect(preorder.authorization_purchase.stripe_error_code).to eq "incorrect_cvc" preorder.mark_authorization_failed expect(preorder.state).to eq "authorization_failed" end it "creates both the authorization purchase and the main purchase and their states is properly set" do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" preorder.mark_authorization_successful expect(preorder.state).to eq "authorization_successful" preorder.charge! purchase = preorder.purchases.last expect(purchase.purchase_state).to eq "successful" expect(purchase.card_visual).to eq "**** **** **** 4242" preorder.mark_charge_successful expect(preorder.state).to eq "charge_successful" expect(preorder.authorization_purchase.purchase_state).to eq "preorder_concluded_successfully" expect(preorder.reload.credit_card).to be_present end it "creates both the authorization purchase and the main purchase and their states is properly set - for PayPal as a chargeable" do authorization_purchase = build(:purchase, link: @product, chargeable: build(:paypal_chargeable), purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" preorder.mark_authorization_successful expect(preorder.state).to eq "authorization_successful" preorder.charge! purchase = preorder.purchases.last expect(purchase.purchase_state).to eq "successful" expect(purchase.card_visual).to eq "jane.doe@example.com" preorder.mark_charge_successful expect(preorder.state).to eq "charge_successful" expect(preorder.authorization_purchase.purchase_state).to eq "preorder_concluded_successfully" expect(preorder.reload.credit_card).to be_present end describe "handling of unexpected errors", :vcr do context "when a rate limit error occurs" do it "does not leave the purchase in in_progress state" do expect do expect do expect do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful expect(Stripe::PaymentIntent).to receive(:create).and_raise(Stripe::RateLimitError) preorder.charge! end.to raise_error(ChargeProcessorError) end.to change { Purchase.failed.count }.by(1) end.not_to change { Purchase.in_progress.count } end end context "when a generic Stripe error occurs" do it "does not leave the purchase in in_progress state" do expect do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful expect(Stripe::PaymentIntent).to receive(:create).and_raise(Stripe::IdempotencyError) purchase = preorder.charge! expect(purchase.purchase_state).to eq("failed") end.not_to change { Purchase.in_progress.count } end end context "when a generic Braintree error occurs" do it "does not leave the purchase in in_progress state" do expect do authorization_purchase = build(:purchase, link: @product, chargeable: build(:paypal_chargeable), purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful expect(Braintree::Transaction).to receive(:sale).and_raise(Braintree::BraintreeError) purchase = preorder.charge! expect(purchase.purchase_state).to eq("failed") end.not_to change { Purchase.in_progress.count } end end context "when a PayPal connection error occurs" do it "does not leave the purchase in in_progress state" do create(:merchant_account_paypal, user: @product.user, charge_processor_merchant_id: "CJS32DZ7NDN5L", currency: "gbp") expect do authorization_purchase = build(:purchase, link: @product, chargeable: build(:native_paypal_chargeable), purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful expect_any_instance_of(PayPal::PayPalHttpClient).to receive(:execute).and_raise(PayPalHttp::HttpError.new(418, OpenStruct.new(details: [OpenStruct.new(description: "IO Error")]), nil)) purchase = preorder.charge! expect(purchase.purchase_state).to eq("failed") end.not_to change { Purchase.in_progress.count } end end context "when unexpected runtime error occurs mid purchase" do it "does not leave the purchase in in_progress state" do expect do expect do expect do authorization_purchase = build(:purchase, link: @product, chargeable: build(:paypal_chargeable), purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful expect_any_instance_of(Purchase).to receive(:charge!).and_raise(RuntimeError) preorder.charge! end.to raise_error(RuntimeError) end.to change { Purchase.failed.count }.by(1) end.not_to change { Purchase.in_progress.count } end end end it "sends the proper preorder emails" do mail_double = double allow(mail_double).to receive(:deliver_later) expect(ContactingCreatorMailer).to receive(:notify).and_return(mail_double) expect(CustomerMailer).to receive(:preorder_receipt).and_return(mail_double) authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful end it "sends the proper preorder emails for test preorders" do mail_double = double allow(mail_double).to receive(:deliver_later) expect(ContactingCreatorMailer).to receive(:notify).and_return(mail_double) expect(CustomerMailer).to receive(:preorder_receipt).and_return(mail_double) expect(CustomerMailer).to_not receive(:receipt) authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", purchaser: @product.user, seller: @product.user, is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_test_authorization_successful! end it "does not create a url redirect on successful authorization" do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful expect(preorder.url_redirect).to_not be_present end it "creates both the authorization purchase (successful) and the main purchase (failed)" do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card_but_cant_charge, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" preorder.mark_authorization_successful expect(preorder.state).to eq "authorization_successful" preorder.charge! expect(preorder.purchases.last.purchase_state).to eq "failed" expect(preorder.purchases.last.stripe_error_code).to eq "card_declined_generic_decline" preorder.mark_cancelled expect(preorder.state).to eq "cancelled" expect(preorder.authorization_purchase.purchase_state).to eq "preorder_concluded_unsuccessfully" end it "enqueues activate integrations worker on successful charge" do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful preorder.charge! purchase = preorder.purchases.last expect(purchase.reload.purchase_state).to eq "successful" expect(ActivateIntegrationsWorker).to have_enqueued_sidekiq_job(preorder.purchases.last.id) end it "does not enqueue activate integrations worker if charge fails" do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card_but_cant_charge, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful preorder.charge! expect(preorder.purchases.last.purchase_state).to eq "failed" expect(ActivateIntegrationsWorker.jobs.size).to eq(0) end it "does not charge the preorder if a purchase is in progress" do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" preorder.mark_authorization_successful expect(preorder.state).to eq "authorization_successful" create(:purchase, link: @product, preorder:, chargeable: @good_card, purchase_state: "in_progress") expect do preorder.charge! end.not_to change(Purchase, :count) end it "does not charge the same preorder twice" do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" preorder.mark_authorization_successful expect(preorder.state).to eq "authorization_successful" preorder.charge! purchase = preorder.purchases.last expect(purchase.purchase_state).to eq "successful" expect(purchase.card_visual).to eq "**** **** **** 4242" travel 1.hour # skipping the double charge protection expect do preorder.charge! end.not_to change(Purchase, :count) end it "properly cancels the preorder and mark its auth purchase as concluded" do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" preorder.mark_authorization_successful expect(preorder.state).to eq "authorization_successful" mail_double = double allow(mail_double).to receive(:deliver_later) expect(ContactingCreatorMailer).to receive(:preorder_cancelled).and_return(mail_double) expect(CustomerLowPriorityMailer).to receive(:preorder_cancelled).and_return(mail_double) preorder.mark_cancelled expect(preorder.state).to eq "cancelled" expect(preorder.authorization_purchase.purchase_state).to eq "preorder_concluded_unsuccessfully" expect(preorder.reload.credit_card).to be_present end it "applies the offer code that was used at the time of the preorder" do offer_code = create(:offer_code, products: [@product], code: "sxsw", amount_cents: 200) authorization_purchase = build(:purchase, link: @product, offer_code:, discount_code: offer_code.code, chargeable: @good_card, purchase_state: "in_progress", referrer: "thefacebook.com", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" expect(preorder.authorization_purchase.price_cents).to eq 400 mail_double = double allow(mail_double).to receive(:deliver_later) expect(ContactingCreatorMailer).to receive(:notify).and_return(mail_double) preorder.mark_authorization_successful expect(ContactingCreatorMailer).to_not receive(:notify) preorder.charge! charge_purchase = preorder.purchases.last expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.offer_code).to eq offer_code expect(charge_purchase.price_cents).to eq 400 expect(charge_purchase.referrer).to eq "thefacebook.com" end it "applies the variants that were used at the time of the preorder" do category = create(:variant_category, title: "sizes", link: @product) variant = create(:variant, name: "small", price_difference_cents: 300, variant_category: category) authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) authorization_purchase.variant_attributes << variant preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" expect(preorder.authorization_purchase.price_cents).to eq 900 preorder.mark_authorization_successful preorder.charge! charge_purchase = preorder.purchases.last expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.variant_attributes).to include variant expect(charge_purchase.price_cents).to eq 900 end it "applies the quantity that was used at the time of the preorder" do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true, quantity: 3) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" expect(preorder.authorization_purchase.price_cents).to eq 1800 preorder.mark_authorization_successful preorder.charge! charge_purchase = preorder.purchases.last expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.quantity).to eq 3 expect(charge_purchase.price_cents).to eq 1800 end it "applies the name, address, shipping_cents, etc. that were used at the time of the preorder" do @product.update!(require_shipping: true, is_physical: true) @product.shipping_destinations << create(:shipping_destination, country_code: Compliance::Countries::USA.alpha2) authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true, zip_code: "94102", city: "sf", full_name: "gum stein", street_address: "here", country: "United States", state: "ca") authorization_purchase.purchase_custom_fields << [ build(:purchase_custom_field, name: "height", value: "tall"), build(:purchase_custom_field, name: "waist", value: "fat") ] preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful! # Set a new non-zero shipping price @product.shipping_destinations.first.update!(one_item_rate_cents: 500, multiple_items_rate_cents: 500) preorder.charge! charge_purchase = preorder.purchases.last expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.purchase_custom_fields.pluck(:name, :value, :field_type)).to eq authorization_purchase.purchase_custom_fields.pluck(:name, :value, :field_type) expect(charge_purchase.custom_fields).to eq authorization_purchase.custom_fields expect(charge_purchase.full_name).to eq authorization_purchase.full_name expect(charge_purchase.street_address).to eq authorization_purchase.street_address expect(charge_purchase.country).to eq authorization_purchase.country expect(charge_purchase.state).to eq authorization_purchase.state expect(charge_purchase.zip_code).to eq authorization_purchase.zip_code expect(charge_purchase.city).to eq authorization_purchase.city expect(charge_purchase.shipping_cents).to eq(0) end it "charges the preorder when the product requires shipping but the auth purchase doesn't have shipping info \ (the product did not require shipping at the time of auth)" do authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true, full_name: "gum stein") preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful @product.update(require_shipping: true) preorder.charge! charge_purchase = preorder.purchases.last expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.full_name).to eq authorization_purchase.full_name expect(charge_purchase.street_address).to eq authorization_purchase.street_address expect(charge_purchase.country).to eq authorization_purchase.country expect(charge_purchase.state).to eq authorization_purchase.state expect(charge_purchase.zip_code).to eq authorization_purchase.zip_code expect(charge_purchase.city).to eq authorization_purchase.city end it "transfers VAT ID and elected tax country from the authorization to the actual charge" do create(:zip_tax_rate, country: "IT", zip_code: nil, state: nil, combined_rate: 0.22, is_seller_responsible: false) authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true, full_name: "gum stein", ip_address: "2.47.255.255", country: "Italy") authorization_purchase.business_vat_id = "IE6388047V" authorization_purchase.sales_tax_country_code_election = "IT" authorization_purchase.process! preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful preorder.charge! charge_purchase = preorder.purchases.last expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.purchase_sales_tax_info.business_vat_id).to eq "IE6388047V" expect(charge_purchase.purchase_sales_tax_info.elected_country_code).to eq "IT" expect(charge_purchase.total_transaction_cents).to eq 600 expect(charge_purchase.gumroad_tax_cents).to eq 0 end it "does not charge the card if the preorder is free" do expect(Stripe::PaymentIntent).to_not receive(:create) @product.update_attribute(:price_cents, 0) authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" expect(preorder.authorization_purchase.price_cents).to eq 0 preorder.mark_authorization_successful preorder.charge! charge_purchase = preorder.purchases.last expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.price_cents).to eq 0 end it "charges the card if the preorder is free but has a variant with a price" do @product.update_attribute(:price_cents, 0) category = create(:variant_category, title: "sizes", link: @product) variant = create(:variant, name: "small", price_difference_cents: 300, variant_category: category) authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) authorization_purchase.variant_attributes << variant preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" expect(preorder.authorization_purchase.price_cents).to eq 300 preorder.mark_authorization_successful preorder.charge! charge_purchase = preorder.purchases.last.reload expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.variant_attributes).to include variant expect(charge_purchase.price_cents).to eq 300 end it "charges the card the right amount based on the exchange rate at the time of the charge" do @product.update!(price_currency_type: "jpy", price_cents: 600) $currency_namespace.set("JPY", 95) authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" expect(preorder.authorization_purchase.price_cents).to eq 632 # 600 yens in cents preorder.mark_authorization_successful $currency_namespace.set("JPY", 100) preorder.charge! charge_purchase = preorder.purchases.last.reload expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.price_cents).to eq 600 # 600 yens in cents based on the new rate end it "charges the card the right amount based on the custom price the buyer entered at preorder time" do @product.update_attribute(:customizable_price, true) authorization_purchase = build(:purchase, link: @product, perceived_price_cents: 7_00, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" expect(preorder.authorization_purchase.price_cents).to eq 700 preorder.mark_authorization_successful preorder.charge! charge_purchase = preorder.purchases.last.reload expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.price_cents).to eq 700 end it "charges the card the right amount based on the custom price the buyer entered at preorder time - non USD" do @product.update!( price_currency_type: "jpy", price_cents: 600, customizable_price: true ) $currency_namespace.set("JPY", 90) authorization_purchase = build(:purchase, link: @product, perceived_price_cents: 700, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" expect(preorder.authorization_purchase.price_cents).to eq 778 preorder.mark_authorization_successful $currency_namespace.set("JPY", 100) preorder.charge! charge_purchase = preorder.purchases.last.reload expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.price_cents).to eq 700 end it "does not count the charge purchase towards the offer code limit" do offer_code = create(:offer_code, products: [@product], code: "sxsw", amount_cents: 200, max_purchase_count: 1) authorization_purchase = build(:purchase, link: @product, offer_code:, discount_code: offer_code.code, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.authorization_purchase.purchase_state).to eq "preorder_authorization_successful" expect(preorder.authorization_purchase.price_cents).to eq 400 preorder.mark_authorization_successful preorder.charge! charge_purchase = preorder.purchases.last expect(charge_purchase.purchase_state).to eq "successful" expect(charge_purchase.offer_code).to eq offer_code expect(charge_purchase.price_cents).to eq 400 authorization_purchase = build(:purchase, link: @product, offer_code:, discount_code: offer_code.code, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! expect(preorder.errors).to be_present expect(preorder.authorization_purchase.error_code).to eq("offer_code_sold_out") end it "does not count the charge purchase towards the variant quantity limit" do category = create(:variant_category, title: "sizes", link: @product) variant = create(:variant, name: "small", price_difference_cents: 300, variant_category: category, max_purchase_count: 1)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/credit_card_spec.rb
spec/models/credit_card_spec.rb
# frozen_string_literal: true require "spec_helper" describe CreditCard do describe "after creating a credit card", :vcr do let(:chargeable) { build(:chargeable) } it "is valid" do credit_card = CreditCard.create(chargeable) expect(credit_card.valid?).to be(true) end it "has charge processor id matching the chargeable it wrapped" do credit_card = CreditCard.create(chargeable) expect(credit_card.charge_processor_id).to eq chargeable.charge_processor_id end it "has correct charge processor token" do expect(chargeable).to receive(:reusable_token_for!).with(StripeChargeProcessor.charge_processor_id, anything).once.ordered.and_return("reusable-token-stripe") expect(chargeable).to receive(:reusable_token_for!).with(BraintreeChargeProcessor.charge_processor_id, anything).once.ordered.and_return("reusable-token-braintree") expect(chargeable).to receive(:reusable_token_for!).with(PaypalChargeProcessor.charge_processor_id, anything).once.ordered.and_return("reusable-token-paypal") credit_card = CreditCard.create(chargeable) expect(credit_card.stripe_customer_id).to eq "reusable-token-stripe" expect(credit_card.braintree_customer_id).to eq "reusable-token-braintree" expect(credit_card.paypal_billing_agreement_id).to eq "reusable-token-paypal" end describe "errors" do describe "card declined" do let(:chargeable_decline) { build(:chargeable, card: StripePaymentMethodHelper.decline) } it "does not throw an exception" do expect { CreditCard.create(chargeable_decline) }.to_not raise_error end it "stores errors in 'errors'" do credit_card = CreditCard.create(chargeable_decline) expect(credit_card.errors).to be_present expect(credit_card.stripe_error_code).to be_present end end describe "chard processor unavailable" do before do allow(chargeable).to receive(:reusable_token_for!).and_raise(ChargeProcessorUnavailableError) end it "does not throw an exception" do expect { CreditCard.create(chargeable) }.to_not raise_error end it "stores errors in 'errors'" do credit_card = CreditCard.create(chargeable) expect(credit_card.errors).to be_present expect(credit_card.error_code).to be_present end end describe "chard processor invalid request" do before do allow(chargeable).to receive(:reusable_token_for!).and_raise(ChargeProcessorInvalidRequestError) end it "does not throw an exception" do expect { CreditCard.create(chargeable) }.to_not raise_error end it "stores errors in 'errors'" do credit_card = CreditCard.create(chargeable) expect(credit_card.errors).to be_present expect(credit_card.error_code).to be_present end end end describe "#charge_processor_unavailable_error" do it "returns STRIPE_UNAVAILABLE error if charge_processor_id is nil" do credit_card = build(:credit_card, charge_processor_id: nil) expect(credit_card.send(:charge_processor_unavailable_error)).to eq PurchaseErrorCode::STRIPE_UNAVAILABLE end it "returns STRIPE_UNAVAILABLE error if charge_processor_id is Stripe" do credit_card = create(:credit_card, charge_processor_id: StripeChargeProcessor.charge_processor_id) expect(credit_card.send(:charge_processor_unavailable_error)).to eq PurchaseErrorCode::STRIPE_UNAVAILABLE end it "returns PAYPAL_UNAVAILABLE error if charge_processor_id is Paypal" do credit_card = build(:credit_card, charge_processor_id: PaypalChargeProcessor.charge_processor_id) expect(credit_card.send(:charge_processor_unavailable_error)).to eq PurchaseErrorCode::PAYPAL_UNAVAILABLE end it "returns PAYPAL_UNAVAILABLE error if charge_processor_id is Braintree" do credit_card = build(:credit_card, charge_processor_id: BraintreeChargeProcessor.charge_processor_id) expect(credit_card.send(:charge_processor_unavailable_error)).to eq PurchaseErrorCode::PAYPAL_UNAVAILABLE end end end describe "#create", :vcr do before do allow_any_instance_of(StripeChargeablePaymentMethod).to receive(:stripe_setup_intent_id).and_return("seti_1234567890") allow_any_instance_of(StripeChargeablePaymentMethod).to receive(:stripe_payment_intent_id).and_return("pi_1234567890") end context "when card country is India and processor is Stripe" do let!(:chargeable) { create(:chargeable, card: StripePaymentMethodHelper.success_indian_card_mandate) } it "saves stripe_setup_intent_id if it present on the chargeable" do credit_card = CreditCard.create(chargeable) expect(credit_card.stripe_setup_intent_id).to eq "seti_1234567890" end it "saves stripe_payment_intent_id if it present on the chargeable" do credit_card = CreditCard.create(chargeable) expect(credit_card.stripe_payment_intent_id).to eq "pi_1234567890" end end context "when card country is not India and processor is Stripe" do let!(:chargeable) { create(:chargeable, card: StripePaymentMethodHelper.success) } it "does not save stripe_setup_intent_id even if it present on the chargeable" do credit_card = CreditCard.create(chargeable) expect(credit_card.stripe_setup_intent_id).to be nil end it "does not save stripe_payment_intent_id even if it present on the chargeable" do credit_card = CreditCard.create(chargeable) expect(credit_card.stripe_payment_intent_id).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/models/device_spec.rb
spec/models/device_spec.rb
# frozen_string_literal: true require "spec_helper" describe Device do describe "creating" do it "deletes existing token if already linked with other account" do device = create(:device, token: "x" * 64, device_type: "ios") create(:device, token: "x" * 64, device_type: "ios") expect(Device.where(id: device.id)).to be_empty end end describe "validation" do describe "token" do it "is present" do expect(build(:device, token: "x" * 64)).to be_valid end it "is not present" do expect(build(:device, token: nil)).to be_invalid end end describe "device_type" do it "is present" do expect(build(:device, device_type: Device::DEVICE_TYPES.values.first)).to be_valid end it "is not present" do expect(build(:device, device_type: nil)).to be_invalid end it "is invalid type" do expect(build(:device, device_type: "windows")).to be_invalid end end describe "device_type" do it "is present" do expect(build(:device, app_type: Device::APP_TYPES.values.first)).to be_valid end it "is not present" do expect(build(:device, app_type: nil)).to be_invalid end it "is invalid type" do expect(build(:device, app_type: "windows")).to be_invalid end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/indonesia_bank_account_spec.rb
spec/models/indonesia_bank_account_spec.rb
# frozen_string_literal: true describe IndonesiaBankAccount do describe "#bank_account_type" do it "returns Indonesia" do expect(create(:indonesia_bank_account).bank_account_type).to eq("ID") end end describe "#country" do it "returns ID" do expect(create(:indonesia_bank_account).country).to eq("ID") end end describe "#currency" do it "returns idr" do expect(create(:indonesia_bank_account).currency).to eq("idr") end end describe "#routing_number" do it "returns valid for 4 characters" do ba = create(:indonesia_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("000") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:indonesia_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789") end end describe "#validate_bank_code" do it "allows 3 to 4 alphanumeric characters only" do expect(build(:indonesia_bank_account, bank_code: "123")).to be_valid expect(build(:indonesia_bank_account, bank_code: "1234")).to be_valid expect(build(:indonesia_bank_account, bank_code: "12AB")).to be_valid expect(build(:indonesia_bank_account, bank_code: "12")).not_to be_valid expect(build(:indonesia_bank_account, bank_code: "12345")).not_to be_valid expect(build(:indonesia_bank_account, bank_code: "12@#")).not_to be_valid end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/product_refund_policy_spec.rb
spec/models/product_refund_policy_spec.rb
# frozen_string_literal: true require "spec_helper" describe ProductRefundPolicy do let(:refund_policy) { create(:product_refund_policy) } describe "validations" do it "validates presence" do refund_policy = ProductRefundPolicy.new expect(refund_policy.valid?).to be false expect(refund_policy.errors.details[:seller].first[:error]).to eq :blank expect(refund_policy.errors.details[:product].first[:error]).to eq :blank end context "when refund policy for product exists" do it "validates product uniqueness" do new_refund_policy = refund_policy.dup expect(new_refund_policy.valid?).to be false expect(new_refund_policy.errors.details[:product].first[:error]).to eq :taken end end it "validates fine_print length" do refund_policy.fine_print = "a" * 3001 expect(refund_policy.valid?).to be false expect(refund_policy.errors.details[:fine_print].first[:error]).to eq :too_long end it "strips tags" do refund_policy.fine_print = "<p>This is a product-level refund policy</p>" refund_policy.save! expect(refund_policy.fine_print).to eq "This is a product-level refund policy" end it "is invalid when the product belongs to the seller" do refund_policy = create(:product_refund_policy) refund_policy.product = create(:product) expect(refund_policy.valid?).to be false expect(refund_policy.errors.details[:product].first[:error]).to eq :invalid end context "max_refund_period_in_days validation" do it "is valid with allowed refund period values" do RefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS.keys.each do |days| refund_policy.max_refund_period_in_days = days expect(refund_policy.valid?).to be true end end it "is invalid with nil value" do refund_policy.max_refund_period_in_days = nil expect(refund_policy.valid?).to be false expect(refund_policy.errors.details[:max_refund_period_in_days].first[:error]).to eq :inclusion end it "is invalid with a refund period not in the allowed list" do [1, 15, 60, 200].each do |days| refund_policy.max_refund_period_in_days = days expect(refund_policy.valid?).to be false expect(refund_policy.errors.details[:max_refund_period_in_days].first[:error]).to eq :inclusion end end end end describe "stripped_fields" do it "strips leading and trailing spaces for fine_print" do refund_policy = create(:product_refund_policy, fine_print: " This is a product-level refund policy ") expect(refund_policy.fine_print).to eq "This is a product-level refund policy" end it "nullifies fine_print" do refund_policy = create(:product_refund_policy, fine_print: "") expect(refund_policy.fine_print).to be_nil end end describe "#as_json" do let(:refund_policy) { create(:product_refund_policy) } it "returns a hash with refund details" do expect(refund_policy.as_json).to eq( { fine_print: refund_policy.fine_print, id: refund_policy.external_id, max_refund_period_in_days: refund_policy.max_refund_period_in_days, product_name: refund_policy.product.name, title: refund_policy.title, } ) end end describe "scopes" do describe "for_visible_and_not_archived_products" do let!(:refund_policy_archived_product) { create(:product_refund_policy, product: create(:product, archived: true)) } let!(:refund_policy_deleted_product) { create(:product_refund_policy, product: create(:product, deleted_at: Time.current)) } let!(:refund_policy_product) { create(:product_refund_policy, product: create(:product)) } it "returns the correct record" do expect(ProductRefundPolicy.for_visible_and_not_archived_products).to eq [refund_policy_product] end end end describe "#no_refunds?" do let(:refund_policy) { create(:product_refund_policy) } it "returns true when max_refund_period_in_days is 0" do refund_policy.max_refund_period_in_days = 0 expect(refund_policy.no_refunds?).to be true end it "returns false when max_refund_period_in_days is not 0" do [7, 14, 30, 183].each do |days| refund_policy.max_refund_period_in_days = days expect(refund_policy.no_refunds?).to be false end end end describe "#published_and_no_refunds?" do let(:refund_policy) { create(:product_refund_policy) } it "returns true when product is published and has no refunds" do allow(refund_policy.product).to receive(:published?).and_return(true) allow(refund_policy).to receive(:no_refunds?).and_return(true) expect(refund_policy.published_and_no_refunds?).to be true end it "returns false when product is not published" do allow(refund_policy.product).to receive(:published?).and_return(false) allow(refund_policy).to receive(:no_refunds?).and_return(true) expect(refund_policy.published_and_no_refunds?).to be false end it "returns false when refunds are allowed" do allow(refund_policy.product).to receive(:published?).and_return(true) allow(refund_policy).to receive(:no_refunds?).and_return(false) expect(refund_policy.published_and_no_refunds?).to be false end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/user_tax_form_spec.rb
spec/models/user_tax_form_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe UserTaxForm do subject(:user_tax_form) { build(:user_tax_form) } describe "associations" do it { is_expected.to belong_to(:user) } end describe "validations" do it { is_expected.to validate_presence_of(:tax_year) } it { is_expected.to validate_numericality_of(:tax_year).only_integer.is_greater_than_or_equal_to(UserTaxForm::MIN_TAX_YEAR) } it { is_expected.to validate_presence_of(:tax_form_type) } it { is_expected.to validate_inclusion_of(:tax_form_type).in_array(UserTaxForm::TAX_FORM_TYPES) } describe "uniqueness" do subject(:user_tax_form) { create(:user_tax_form) } it { is_expected.to validate_uniqueness_of(:user_id).scoped_to(:tax_year, :tax_form_type) } end end describe "scopes" do describe ".for_year" do it "returns tax forms for the specified year" do user = create(:user) create(:user_tax_form, user:, tax_year: 2022) tax_form_2023 = create(:user_tax_form, user:, tax_year: 2023) expect(described_class.for_year(2023)).to contain_exactly(tax_form_2023) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/peru_bank_account_spec.rb
spec/models/peru_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe PeruBankAccount do describe "#bank_account_type" do it "returns peru" do expect(create(:peru_bank_account).bank_account_type).to eq("PE") end end describe "#country" do it "returns PE" do expect(create(:peru_bank_account).country).to eq("PE") end end describe "#currency" do it "returns pen" do expect(create(:peru_bank_account).currency).to eq("pen") end end describe "#routing_number" do it "returns nil" do expect(create(:peru_bank_account).routing_number).to be nil end end describe "#account_number_visual" do it "returns the visual account number with country code prefixed" do expect(create(:peru_bank_account, account_number_last_four: "2874").account_number_visual).to eq("******2874") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:peru_bank_account)).to be_valid expect(build(:peru_bank_account, account_number: "01234567898765432101")).to be_valid pe_bank_account = build(:peru_bank_account, account_number: "012345678") expect(pe_bank_account).to_not be_valid expect(pe_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") pe_bank_account = build(:peru_bank_account, account_number: "ABCDEFGHIJKLMNOPQRSTUV") expect(pe_bank_account).to_not be_valid expect(pe_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") pe_bank_account = build(:peru_bank_account, account_number: "01234567898765432123456") expect(pe_bank_account).to_not be_valid expect(pe_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") pe_bank_account = build(:peru_bank_account, account_number: "012345678987654321234") expect(pe_bank_account).to_not be_valid expect(pe_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/stripe_apple_pay_domain_spec.rb
spec/models/stripe_apple_pay_domain_spec.rb
# frozen_string_literal: true require "spec_helper" describe StripeApplePayDomain do it "validates presence of attributes" do record = StripeApplePayDomain.create() expect(record.errors.messages).to eq( user: ["can't be blank"], domain: ["can't be blank"], stripe_id: ["can't be blank"], ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/israel_bank_account_spec.rb
spec/models/israel_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe IsraelBankAccount do describe "#bank_account_type" do it "returns IL" do expect(create(:israel_bank_account).bank_account_type).to eq("IL") end end describe "#country" do it "returns IL" do expect(create(:israel_bank_account).country).to eq("IL") end end describe "#currency" do it "returns ils" do expect(create(:israel_bank_account).currency).to eq("ils") end end describe "#routing_number" do it "returns nil" do expect(create(:israel_bank_account).routing_number).to be nil end end describe "#account_number_visual" do it "returns the visual account number with country code prefixed" do expect(create(:israel_bank_account, account_number_last_four: "9999").account_number_visual).to eq("IL******9999") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:israel_bank_account)).to be_valid expect(build(:israel_bank_account, account_number: "IL62 0108 0000 0009 9999 999")).to be_valid il_bank_account = build(:israel_bank_account, account_number: "IL12345") expect(il_bank_account).to_not be_valid expect(il_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") il_bank_account = build(:israel_bank_account, account_number: "DE6508000000192000145399") expect(il_bank_account).to_not be_valid expect(il_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") il_bank_account = build(:israel_bank_account, account_number: "8937040044053201300000") expect(il_bank_account).to_not be_valid expect(il_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") il_bank_account = build(:israel_bank_account, account_number: "ILABCDE") expect(il_bank_account).to_not be_valid expect(il_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/sendgrid_event_info_spec.rb
spec/models/sendgrid_event_info_spec.rb
# frozen_string_literal: true require "spec_helper" describe SendgridEventInfo do describe "#for_abandoned_cart_email?" do it "returns true when the mailer class is CustomerMailer and the mailer method is abandoned_cart" do event_json = { "mailer_class" => "CustomerMailer", "mailer_method" => "abandoned_cart" } sendgrid_event_info = SendgridEventInfo.new(event_json) expect(sendgrid_event_info.for_abandoned_cart_email?).to be(true) end it "returns false when the mailer class is not CustomerMailer" do event_json = { "mailer_class" => "CreatorContactingCustomersMailer", "mailer_method" => "abandoned_cart" } sendgrid_event_info = SendgridEventInfo.new(event_json) expect(sendgrid_event_info.for_abandoned_cart_email?).to be(false) end it "returns false when the mailer method is not abandoned_cart" do event_json = { "mailer_class" => "CustomerMailer", "mailer_method" => "purchase_installment" } sendgrid_event_info = SendgridEventInfo.new(event_json) expect(sendgrid_event_info.for_abandoned_cart_email?).to be(false) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/affiliate_credit_spec.rb
spec/models/affiliate_credit_spec.rb
# frozen_string_literal: true require "spec_helper" describe AffiliateCredit do describe "associations" do it { is_expected.to belong_to(:seller).class_name("User").optional(false) } it { is_expected.to belong_to(:affiliate_user).class_name("User").optional(false) } it { is_expected.to belong_to(:purchase).optional(false) } it { is_expected.to belong_to(:link).optional(true) } it { is_expected.to belong_to(:affiliate).optional(true) } it { is_expected.to belong_to(:oauth_application).optional(true) } end describe "validations" do it { is_expected.to validate_presence_of(:basis_points) } it { is_expected.to validate_numericality_of(:basis_points).is_greater_than_or_equal_to(0).is_less_than_or_equal_to(100_00) } it "requires an affiliate or oauth application to be present" do expect(build(:affiliate_credit, oauth_application: nil, affiliate: nil)).to_not be_valid expect(build(:affiliate_credit, oauth_application: build(:oauth_application), affiliate: nil)).to be_valid expect(build(:affiliate_credit, oauth_application: nil)).to be_valid end end describe "#amount_partially_refunded_cents" do it "returns the sum of amount_cents of affiliate_partial_refunds" do affiliate_credit = create(:affiliate_credit) expect(affiliate_credit.amount_partially_refunded_cents).to eq(0) create(:affiliate_partial_refund, affiliate_credit:, amount_cents: 12) create(:affiliate_partial_refund, affiliate_credit:, amount_cents: 34) expect(affiliate_credit.reload.amount_partially_refunded_cents).to eq(46) end end describe "#fee_partially_refunded_cents" do it "returns the sum of fee_cents of affiliate_partial_refunds" do affiliate_credit = create(:affiliate_credit) expect(affiliate_credit.fee_partially_refunded_cents).to eq(0) create(:affiliate_partial_refund, affiliate_credit:, fee_cents: 12) create(:affiliate_partial_refund, affiliate_credit:, fee_cents: 34) expect(affiliate_credit.reload.fee_partially_refunded_cents).to eq(46) end end describe "#create!" do let(:seller) { create(:user) } let(:product) { create(:product, user: seller) } let(:affiliate) { create(:direct_affiliate, seller:, affiliate_basis_points: 10_00, apply_to_all_products:) } let!(:product_affiliate) { create(:product_affiliate, product:, affiliate:, affiliate_basis_points: product_basis_points) } context "when a product commission is set" do let(:product_basis_points) { 20_00 } context "when affiliate does not apply to all products" do let(:apply_to_all_products) { false } let(:purchase) do create(:purchase, seller:, link: product, purchase_state: "successful", price_cents: product.price_cents, affiliate_credit_cents: 20) end it "creates an affiliate credit with the correct amount and product commission" do affiliate_credit = AffiliateCredit.create!(purchase:, affiliate:, affiliate_amount_cents: 20, affiliate_fee_cents: 5, affiliate_balance: create(:balance)) expect(affiliate_credit.amount_cents).to eq(20) expect(affiliate_credit.fee_cents).to eq(5) expect(affiliate_credit.basis_points).to eq(product_basis_points) end end context "when affiliate applies to all products" do let(:apply_to_all_products) { true } let(:purchase) do create(:purchase, seller:, link: product, purchase_state: "successful", price_cents: product.price_cents, affiliate_credit_cents: 10) end it "creates an affiliate credit with the correct amount and affiliate commission" do affiliate_credit = AffiliateCredit.create!(purchase:, affiliate:, affiliate_amount_cents: 10, affiliate_fee_cents: 5, affiliate_balance: create(:balance)) expect(affiliate_credit.amount_cents).to eq(10) expect(affiliate_credit.fee_cents).to eq(5) expect(affiliate_credit.basis_points).to eq(affiliate.affiliate_basis_points) end end end context "when a product commission is not set" do let(:apply_to_all_products) { false } let(:product_basis_points) { nil } let(:purchase) do create(:purchase, seller:, link: product, purchase_state: "successful", price_cents: product.price_cents, affiliate_credit_cents: 10) end it "creates an affiliate credit with the correct amount and commission" do affiliate_credit = AffiliateCredit.create!(purchase:, affiliate:, affiliate_amount_cents: 10, affiliate_fee_cents: 5, affiliate_balance: create(:balance)) expect(affiliate_credit.amount_cents).to eq(10) expect(affiliate_credit.fee_cents).to eq(5) expect(affiliate_credit.basis_points).to eq(affiliate.affiliate_basis_points) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/black_recurring_service_spec.rb
spec/models/black_recurring_service_spec.rb
# frozen_string_literal: true require "spec_helper" describe BlackRecurringService do describe "state transitions" do before do @black_recurring_service = create(:black_recurring_service, state: "inactive") allow_any_instance_of(User).to receive(:tier_pricing_enabled?).and_return(false) @mail_double = double allow(@mail_double).to receive(:deliver_later) end it "transitions to active" do @black_recurring_service.mark_active! expect(@black_recurring_service.reload.state).to eq("active") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/bolivia_bank_account_spec.rb
spec/models/bolivia_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe BoliviaBankAccount do describe "#bank_account_type" do it "returns BO" do expect(create(:bolivia_bank_account).bank_account_type).to eq("BO") end end describe "#country" do it "returns BO" do expect(create(:bolivia_bank_account).country).to eq("BO") end end describe "#currency" do it "returns bob" do expect(create(:bolivia_bank_account).currency).to eq("bob") end end describe "#routing_number" do it "returns valid for 3 digits" do ba = create(:bolivia_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("040") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:bolivia_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789") end end describe "#validate_bank_code" do it "allows 1 to 3 digits only" do expect(build(:bolivia_bank_account, bank_code: "1")).to be_valid expect(build(:bolivia_bank_account, bank_code: "12")).to be_valid expect(build(:bolivia_bank_account, bank_code: "123")).to be_valid expect(build(:bolivia_bank_account, bank_code: "1234")).not_to be_valid expect(build(:bolivia_bank_account, bank_code: "a12")).not_to be_valid end end describe "#validate_account_number" do it "allows 10 to 15 digits only" do expect(build(:bolivia_bank_account, account_number: "1234567890")).to be_valid expect(build(:bolivia_bank_account, account_number: "123456789012345")).to be_valid expect(build(:bolivia_bank_account, account_number: "123456789")).not_to be_valid expect(build(:bolivia_bank_account, account_number: "1234567890123456")).not_to be_valid expect(build(:bolivia_bank_account, account_number: "12345a7890")).not_to be_valid end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/gift_spec.rb
spec/models/gift_spec.rb
# frozen_string_literal: true require "spec_helper" describe Gift do describe "saving" do it "removes leading/trailing spaces in emails" do gift = create(:gift, gifter_email: " abc@def.com ", giftee_email: " foo@bar.com ") expect(gift.gifter_email).to eq("abc@def.com") expect(gift.giftee_email).to eq("foo@bar.com") end it "errors if an email is invalid" do gift = build(:gift, gifter_email: "gifter@gumroad.com", giftee_email: "foo") expect(gift).not_to be_valid expect(gift.errors.full_messages).to include "Giftee email is invalid" gift = build(:gift, gifter_email: "foo", giftee_email: "giftee@gumroad.com") expect(gift).not_to be_valid expect(gift.errors.full_messages).to include "Gifter email is invalid" end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/uk_bank_account_spec.rb
spec/models/uk_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe UkBankAccount do describe "sort_code" do describe "is 6 digits with hyphens" do let(:uk_bank_account) { build(:uk_bank_account, sort_code: "06-21-11") } it "is valid" do expect(uk_bank_account).to be_valid end end describe "nil" do let(:uk_bank_account) { build(:uk_bank_account, sort_code: nil) } it "is not valid" do expect(uk_bank_account).not_to be_valid end end describe "is 6 digits without hyphens" do let(:uk_bank_account) { build(:uk_bank_account, sort_code: "123456") } it "is not valid" do expect(uk_bank_account).not_to be_valid end end describe "is 5 digits" do let(:uk_bank_account) { build(:uk_bank_account, sort_code: "12345") } it "is not valid" do expect(uk_bank_account).not_to be_valid end end describe "is 7 digits with hyphens" do let(:uk_bank_account) { build(:uk_bank_account, sort_code: "12-34-56-7") } it "is not valid" do expect(uk_bank_account).not_to be_valid end end describe "contains alpha characters with hyphens" do let(:uk_bank_account) { build(:uk_bank_account, sort_code: "12-34-5a") } it "is not valid" do expect(uk_bank_account).not_to be_valid end end end describe "routing_number" do let(:uk_bank_account) { build(:uk_bank_account, sort_code: "45-37-80") } it "is the sort_code" do expect(uk_bank_account.routing_number).to eq("45-37-80") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/hong_kong_bank_account_spec.rb
spec/models/hong_kong_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe HongKongBankAccount do describe "#bank_account_type" do it "returns hong kong" do expect(create(:hong_kong_bank_account).bank_account_type).to eq("HK") end end describe "#country" do it "returns HK" do expect(create(:hong_kong_bank_account).country).to eq("HK") end end describe "#currency" do it "returns hkd" do expect(create(:hong_kong_bank_account).currency).to eq("hkd") end end describe "#routing_number" do it "returns valid for 6 digits with hyphen after 3" do ba = create(:hong_kong_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("110-000") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:hong_kong_bank_account, account_number_last_four: "3456").account_number_visual).to eq("******3456") end end describe "#validate_clearing_code" do it "allows 3 digits only" do expect(build(:hong_kong_bank_account, clearing_code: "110")).to be_valid expect(build(:hong_kong_bank_account, clearing_code: "123")).to be_valid expect(build(:hong_kong_bank_account, clearing_code: "1100")).not_to be_valid expect(build(:hong_kong_bank_account, clearing_code: "ABC")).not_to be_valid end end describe "#validate_branch_code" do it "allows 3 digits only" do expect(build(:hong_kong_bank_account, branch_code: "110")).to be_valid expect(build(:hong_kong_bank_account, branch_code: "123")).to be_valid expect(build(:hong_kong_bank_account, branch_code: "1100")).not_to be_valid expect(build(:hong_kong_bank_account, branch_code: "ABC")).not_to be_valid end end describe "#validate_account_number" do it "allows records that match the required account number regex" do expect(build(:hong_kong_bank_account, account_number: "000123456")).to be_valid expect(build(:hong_kong_bank_account, account_number: "123456789")).to be_valid expect(build(:hong_kong_bank_account, account_number: "012345678910")).to be_valid hk_bank_account = build(:hong_kong_bank_account, account_number: "ABCDEFGHI") expect(hk_bank_account).to_not be_valid expect(hk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") hk_bank_account = build(:hong_kong_bank_account, account_number: "8937040044053201300000") expect(hk_bank_account).to_not be_valid expect(hk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") hk_bank_account = build(:hong_kong_bank_account, account_number: "CHABCDE") expect(hk_bank_account).to_not be_valid expect(hk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/monaco_bank_account_spec.rb
spec/models/monaco_bank_account_spec.rb
# frozen_string_literal: true describe MonacoBankAccount do describe "#bank_account_type" do it "returns MC" do expect(create(:monaco_bank_account).bank_account_type).to eq("MC") end end describe "#country" do it "returns MC" do expect(create(:monaco_bank_account).country).to eq("MC") end end describe "#currency" do it "returns eur" do expect(create(:monaco_bank_account).currency).to eq("eur") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:monaco_bank_account, account_number_last_four: "6789").account_number_visual).to eq("MC******6789") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/japan_bank_account_spec.rb
spec/models/japan_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe JapanBankAccount do describe "#bank_account_type" do it "returns Japan" do expect(create(:japan_bank_account).bank_account_type).to eq("JP") end end describe "#country" do it "returns JP" do expect(create(:japan_bank_account).country).to eq("JP") end end describe "#currency" do it "returns jpy" do expect(create(:japan_bank_account).currency).to eq("jpy") end end describe "#routing_number" do it "returns valid for 7 digits" do ba = create(:japan_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("1100000") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:japan_bank_account, account_number_last_four: "8912").account_number_visual).to eq("******8912") end end describe "#validate_bank_code" do it "allows 4 digits only" do expect(build(:japan_bank_account, bank_code: "1100", branch_code: "000")).to be_valid expect(build(:japan_bank_account, bank_code: "BANK", branch_code: "000")).not_to be_valid expect(build(:japan_bank_account, bank_code: "ABC", branch_code: "000")).not_to be_valid expect(build(:japan_bank_account, bank_code: "123", branch_code: "000")).not_to be_valid expect(build(:japan_bank_account, bank_code: "TESTK", branch_code: "000")).not_to be_valid expect(build(:japan_bank_account, bank_code: "12345", branch_code: "000")).not_to be_valid end end describe "#validate_branch_code" do it "allows 3 digits only" do expect(build(:japan_bank_account, bank_code: "1100", branch_code: "000")).to be_valid expect(build(:japan_bank_account, bank_code: "1100", branch_code: "ABC")).not_to be_valid expect(build(:japan_bank_account, bank_code: "1100", branch_code: "AB")).not_to be_valid expect(build(:japan_bank_account, bank_code: "1100", branch_code: "12")).not_to be_valid expect(build(:japan_bank_account, bank_code: "1100", branch_code: "TEST")).not_to be_valid expect(build(:japan_bank_account, bank_code: "1100", branch_code: "1234")).not_to be_valid end end describe "#validate_account_number" do it "allows records that match the required account number regex" do expect(build(:japan_bank_account, account_number: "0001234")).to be_valid expect(build(:japan_bank_account, account_number: "1234")).to be_valid expect(build(:japan_bank_account, account_number: "12345678")).to be_valid jp_bank_account = build(:japan_bank_account, account_number: "ABCDEFG") expect(jp_bank_account).to_not be_valid expect(jp_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") jp_bank_account = build(:japan_bank_account, account_number: "123456789") expect(jp_bank_account).to_not be_valid expect(jp_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") jp_bank_account = build(:japan_bank_account, account_number: "123") expect(jp_bank_account).to_not be_valid expect(jp_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/romania_bank_account_spec.rb
spec/models/romania_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe RomaniaBankAccount do describe "#bank_account_type" do it "returns romania" do expect(create(:romania_bank_account).bank_account_type).to eq("RO") end end describe "#country" do it "returns RO" do expect(create(:romania_bank_account).country).to eq("RO") end end describe "#currency" do it "returns ron" do expect(create(:romania_bank_account).currency).to eq("ron") end end describe "#routing_number" do it "returns nil" do expect(create(:romania_bank_account).routing_number).to be nil end end describe "#account_number_visual" do it "returns the visual account number with country code prefixed" do expect(create(:romania_bank_account, account_number_last_four: "0000").account_number_visual).to eq("RO******0000") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:romania_bank_account)).to be_valid expect(build(:romania_bank_account, account_number: "RO49 AAAA 1B31 0075 9384 0000")).to be_valid ro_bank_account = build(:romania_bank_account, account_number: "RO12345") expect(ro_bank_account).to_not be_valid expect(ro_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ro_bank_account = build(:romania_bank_account, account_number: "DE61109010140000071219812874") expect(ro_bank_account).to_not be_valid expect(ro_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ro_bank_account = build(:romania_bank_account, account_number: "8937040044053201300000") expect(ro_bank_account).to_not be_valid expect(ro_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ro_bank_account = build(:romania_bank_account, account_number: "ROABCDE") expect(ro_bank_account).to_not be_valid expect(ro_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/jordan_bank_account_spec.rb
spec/models/jordan_bank_account_spec.rb
# frozen_string_literal: true describe JordanBankAccount do describe "#bank_account_type" do it "returns JO" do expect(create(:jordan_bank_account).bank_account_type).to eq("JO") end end describe "#country" do it "returns JO" do expect(create(:jordan_bank_account).country).to eq("JO") end end describe "#currency" do it "returns jod" do expect(create(:jordan_bank_account).currency).to eq("jod") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:jordan_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAAJOJOXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:jordan_bank_account, account_number_last_four: "5678").account_number_visual).to eq("JO******5678") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/discover_search_spec.rb
spec/models/discover_search_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe DiscoverSearch do it "can be created" do create(:discover_search) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/tip_spec.rb
spec/models/tip_spec.rb
# frozen_string_literal: true describe Tip do describe "validations" do context "when value_cents is greater than 0" do it "doesn't add an error" do tip = build(:tip, value_cents: 100) expect(tip).to be_valid end end context "when value_cents is zero" do it "adds an error" do tip = build(:tip, value_cents: 0) expect(tip).not_to be_valid expect(tip.errors[:value_cents]).to include("must be greater than 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/models/uzbekistan_bank_account_spec.rb
spec/models/uzbekistan_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe UzbekistanBankAccount do describe "#bank_account_type" do it "returns UZ" do expect(create(:uzbekistan_bank_account).bank_account_type).to eq("UZ") end end describe "#country" do it "returns UZ" do expect(create(:uzbekistan_bank_account).country).to eq("UZ") end end describe "#currency" do it "returns uzs" do expect(create(:uzbekistan_bank_account).currency).to eq("uzs") end end describe "#routing_number" do it "returns valid bank code and branch code" do ba = create(:uzbekistan_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAAUZUZXXX-00000") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:uzbekistan_bank_account, account_number_last_four: "0024").account_number_visual).to eq("******0024") end end describe "#validate_bank_code" do it "allows valid bank code format" do expect(build(:uzbekistan_bank_account, bank_code: "AAAAUZUZXXX")).to be_valid expect(build(:uzbekistan_bank_account, bank_code: "BBBBUZUZYYY")).to be_valid expect(build(:uzbekistan_bank_account, bank_code: "AAAAUZU")).not_to be_valid expect(build(:uzbekistan_bank_account, bank_code: "AAAAUZUZXXXX")).not_to be_valid end end describe "#validate_account_number" do it "allows valid account number format" do expect(build(:uzbekistan_bank_account, account_number: "99934500012345670024")).to be_valid expect(build(:uzbekistan_bank_account, account_number: "12345")).to be_valid expect(build(:uzbekistan_bank_account, account_number: "12345678901234567890")).to be_valid expect(build(:uzbekistan_bank_account, account_number: "1234")).not_to be_valid expect(build(:uzbekistan_bank_account, account_number: "123456789012345678901")).not_to be_valid end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/dominican_republic_bank_account_spec.rb
spec/models/dominican_republic_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe DominicanRepublicBankAccount do let(:bank_account) { build(:dominican_republic_bank_account) } describe "#bank_account_type" do it "returns DO" do expect(bank_account.bank_account_type).to eq("DO") end end describe "#country" do it "returns DO" do expect(bank_account.country).to eq("DO") end end describe "#currency" do it "returns dop" do expect(bank_account.currency).to eq("dop") end end describe "#routing_number" do it "returns the bank code" do expect(bank_account.routing_number).to eq(bank_account.bank_code) end end describe "#account_number_visual" do it "returns the visual account number" do expect(bank_account.account_number_visual).to eq("******6789") end end describe "#validate_bank_code" do it "allows 1 to 3 digits only" do expect(build(:dominican_republic_bank_account, bank_code: "1")).to be_valid expect(build(:dominican_republic_bank_account, bank_code: "12")).to be_valid expect(build(:dominican_republic_bank_account, bank_code: "123")).to be_valid expect(build(:dominican_republic_bank_account, bank_code: "1234")).not_to be_valid expect(build(:dominican_republic_bank_account, bank_code: "a12")).not_to be_valid end end describe "#validate_account_number" do it "validates the account number format" do expect(bank_account).to be_valid bank_account.account_number = "invalid123" expect(bank_account).not_to be_valid expect(bank_account.errors[:base]).to include("The account number is invalid.") bank_account.account_number = "12345678901234567890123456789" # 29 digits expect(bank_account).not_to be_valid expect(bank_account.errors[:base]).to include("The account number is invalid.") bank_account.account_number = "1234567890123456789012345678" # 28 digits expect(bank_account).to be_valid end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/affiliate_spec.rb
spec/models/affiliate_spec.rb
# frozen_string_literal: true require "spec_helper" describe Affiliate do describe "scopes" do describe "affiliate types" do let!(:direct_affiliate) { create(:direct_affiliate) } let!(:confirmed_collaborator) { create(:collaborator) } let!(:pending_collaborator) { create(:collaborator, :with_pending_invitation) } it "returns all collaborators" do expect(Affiliate.direct_affiliates).to contain_exactly(direct_affiliate) expect(Affiliate.global_affiliates).to match_array GlobalAffiliate.all expect(Affiliate.direct_or_global_affiliates).to match_array([direct_affiliate] + GlobalAffiliate.all) expect(Affiliate.pending_collaborators).to contain_exactly(pending_collaborator) expect(Affiliate.confirmed_collaborators).to contain_exactly(confirmed_collaborator) expect(Affiliate.pending_or_confirmed_collaborators).to contain_exactly(confirmed_collaborator, pending_collaborator) end end describe ".for_product" do let(:product) { create(:product) } let(:seller) { product.user } let!(:direct_affiliate) { create(:direct_affiliate, seller:, products: [product]) } before do create(:direct_affiliate, seller:, products: [create(:product, user: seller)]) create(:direct_affiliate) end it "includes only direct affiliates for the product if the seller does not participate in discover" do allow(product).to receive(:recommendable?).and_return(false) affiliates = Affiliate.for_product(product) expect(affiliates).to match_array [direct_affiliate] end it "includes global affiliates if the seller participates in discover" do allow(product).to receive(:recommendable?).and_return(true) affiliates = Affiliate.for_product(product) expect(affiliates).to match_array GlobalAffiliate.all + [direct_affiliate] end it "includes only direct affiliates if the product is not recommendable" do allow(product).to receive(:recommendable?).and_return(false) affiliates = Affiliate.for_product(product) expect(affiliates).to match_array [direct_affiliate] end end describe ".valid_for_product" do let(:product) { create(:product) } let(:seller) { product.user } let!(:direct_affiliate) { create(:direct_affiliate, seller:, products: [product]) } let(:suspended_user) { create(:tos_user) } before do create(:direct_affiliate) create(:direct_affiliate, seller:, products: [create(:product, user: seller)]) create(:direct_affiliate, seller:, products: [product], deleted_at: 1.day.ago) create(:direct_affiliate, seller:, products: [product], affiliate_user: suspended_user) end it "includes only live direct affiliates for the product if the seller does not participate in discover" do allow(product).to receive(:recommendable?).and_return(false) affiliates = Affiliate.valid_for_product(product) expect(affiliates).to match_array [direct_affiliate] end it "includes only live direct and global affiliates if the seller participates in discover" do allow(product).to receive(:recommendable?).and_return(true) affiliates = Affiliate.valid_for_product(product) expect(affiliates).to match_array GlobalAffiliate.where.not(affiliate_user: suspended_user) + [direct_affiliate] end end end describe "validations" do context "uniqueness of affiliate user scoped to seller" do it "invalidates another alive affiliate with the same scope" do existing = create(:direct_affiliate) affiliate = build(:direct_affiliate, affiliate_user: existing.affiliate_user, seller: existing.seller) expect(affiliate).not_to be_valid end it "validates the affiliate for the same user with a different seller" do existing = create(:direct_affiliate) affiliate = build(:direct_affiliate, affiliate_user: existing.affiliate_user) expect(affiliate).to be_valid end it "validates the affiliate with the same scope when the existing affiliate is deleted" do existing = create(:direct_affiliate, deleted_at: 1.day.ago) affiliate = build(:direct_affiliate, affiliate_user: existing.affiliate_user, seller: existing.seller) expect(affiliate).to be_valid end it "validates the affiliate with the same scope when the existing affiliate is deleted" do existing = create(:direct_affiliate, deleted_at: 1.day.ago) affiliate = build(:direct_affiliate, affiliate_user: existing.affiliate_user, seller: existing.seller) expect(affiliate).to be_valid end end end describe "#affiliate_info" do let(:affiliate_user) { create(:affiliate_user, username: "creator") } let(:affiliate) { create(:direct_affiliate, affiliate_user:, apply_to_all_products: true) } it "returns info about the affiliate" do expect(affiliate.affiliate_info).to eq( { email: affiliate_user.email, destination_url: affiliate.destination_url, affiliate_user_name: "creator", fee_percent: 3, id: affiliate.external_id, } ) end end describe "#global?" do it "returns true for a global affiliate, false for other affiliate types" do expect(GlobalAffiliate.new.global?).to eq true expect(build(:direct_affiliate).global?).to eq false expect(build(:collaborator).global?).to eq false end end describe "#collaborator?" do it "returns true for a collaborator, false for other affiliate types" do expect(build(:collaborator).collaborator?).to eq true expect(GlobalAffiliate.new.collaborator?).to eq false expect(build(:direct_affiliate).collaborator?).to eq false end end describe "#total_cents_earned" do let(:affiliate) { create(:direct_affiliate, affiliate_basis_points: 1000) } it "sums the affiliate credits earned for all successful, paid purchases" do create(:purchase, affiliate:, purchase_state: "successful", price_cents: 100) create(:purchase, affiliate:, purchase_state: "failed", price_cents: 150) create(:purchase, affiliate:, purchase_state: "successful", price_cents: 0).update!(affiliate_credit_cents: 8) # should not have affiliate credits > 0 - just for testing purposes create(:purchase, affiliate:, purchase_state: "successful", price_cents: 1399) expect(affiliate.total_cents_earned).to eq 113 end it "excludes refunded or chargedback purchases" do create(:purchase, affiliate:, purchase_state: "successful", price_cents: 100, chargeback_date: 1.day.ago) create(:purchase, affiliate:, purchase_state: "successful", price_cents: 150, stripe_refunded: true) expect(affiliate.total_cents_earned).to eq 0 end end describe "#total_cents_earned_formatted" do it "returns the formatted amount earned" do affiliate = create(:direct_affiliate, affiliate_basis_points: 1000) create(:purchase, affiliate:, purchase_state: "successful", price_cents: 100) create(:purchase, affiliate:, purchase_state: "successful", price_cents: 1399) expect(affiliate.total_cents_earned_formatted).to eq "$1.13" end end describe "#enabled_products" do let(:affiliate_user) { create(:affiliate_user, username: "creator") } let(:affiliate) { create(:direct_affiliate, affiliate_user:, apply_to_all_products: true) } let!(:product1) { create(:product, name: "Gumbot bits", user: affiliate.seller) } let(:product2) { create(:product, name: "ChatGPT4 prompts", user: affiliate.seller) } let(:product3) { create(:product, name: "Beautiful banner", user: affiliate.seller) } before do create(:product_affiliate, affiliate:, product: product1, affiliate_basis_points: affiliate.affiliate_basis_points) create(:product_affiliate, affiliate:, product: product2, affiliate_basis_points: 45_00) create(:product_affiliate, affiliate:, product: product3, affiliate_basis_points: 23_00) create(:product, name: "Unaffiliated product we ignore", user: affiliate.seller) create(:product, name: "Unaffiliated product we ignore 2", user: affiliate.seller) end it "only returns affiliated products for an affiliate" do expect(affiliate.enabled_products).to eq( [ { id: product1.external_id_numeric, name: "Gumbot bits", fee_percent: 3, referral_url: affiliate.referral_url_for_product(product1), destination_url: nil, }, { id: product2.external_id_numeric, name: "ChatGPT4 prompts", fee_percent: 45, referral_url: affiliate.referral_url_for_product(product2), destination_url: nil, }, { id: product3.external_id_numeric, name: "Beautiful banner", fee_percent: 23, referral_url: affiliate.referral_url_for_product(product3), destination_url: nil, } ] ) end end describe "#basis_points" do let(:affiliate) { create(:user).global_affiliate } it "returns the global affiliate's basis points" do expect(affiliate.basis_points).to eq 10_00 end end describe "#affiliate_percentage" do it "returns the affiliate_basis_points as a percentage" do affiliate = build(:direct_affiliate, affiliate_basis_points: 25_00) expect(affiliate.affiliate_percentage).to eq 25 end it "returns nil if affiliate_basis_points is nil" do affiliate = build(:collaborator, affiliate_basis_points: nil) # currently only collaborators can have nil affiliate_basis_points expect(affiliate.affiliate_percentage).to be_nil end end describe "#eligible_for_credit?" do let(:affiliate_user) { create(:affiliate_user, username: "creator") } let(:affiliate) { create(:direct_affiliate, affiliate_user:, apply_to_all_products: true) } it "returns false if affiliate is deleted" do expect(affiliate.eligible_for_credit?).to be true affiliate.update!(deleted_at: Time.current) expect(affiliate.eligible_for_credit?).to be false end it "returns false if affiliated user account is suspended" do expect(affiliate.eligible_for_credit?).to be true affiliate_user.flag_for_tos_violation!(author_id: User.last.id, bulk: true) affiliate_user.suspend_for_tos_violation!(author_id: User.last.id, bulk: true) expect(affiliate.eligible_for_credit?).to be false end it "returns false if affiliated user is using a Brazilian Stripe Connect account" do expect(affiliate.eligible_for_credit?).to be true brazilian_stripe_account = create(:merchant_account_stripe_connect, user: affiliate_user, country: "BR") affiliate_user.update!(check_merchant_account_is_linked: true) expect(affiliate_user.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq brazilian_stripe_account expect(affiliate.eligible_for_credit?).to be false end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/cart_spec.rb
spec/models/cart_spec.rb
# frozen_string_literal: true require "spec_helper" describe Cart do describe "associations" do describe "#alive_cart_products" do it "returns only alive cart products" do cart = create(:cart) alive_cart_product = create(:cart_product, cart:) create(:cart_product, cart:, deleted_at: Time.current) expect(cart.alive_cart_products).to eq([alive_cart_product]) end end end describe "callbacks" do it "assigns default discount codes after initialization" do cart = build(:cart) expect(cart.discount_codes).to eq([]) end end describe "validations" do describe "discount codes" do context "when discount codes are not provided" do it "marks the cart as valid" do cart = build(:cart, discount_codes: []) expect(cart).to be_valid end end context "when discount codes are not an array" do it "marks the cart as invalid" do cart = build(:cart, discount_codes: {}) expect(cart).to be_invalid expect(cart.errors.full_messages.join).to include("The property '#/' of type object did not match the following type: array") end end context "when required fields are missing from discount codes" do it "marks the cart as invalid" do cart = build(:cart, discount_codes: [{}]) expect(cart).to be_invalid errors = cart.errors.full_messages.join("\n") expect(errors).to include("The property '#/0' did not contain a required property of 'code'") expect(errors).to include("The property '#/0' did not contain a required property of 'fromUrl'") end end context "when discount codes are valid" do it "marks the cart as valid" do cart = build(:cart, discount_codes: [{ code: "ABC123", fromUrl: false }, { code: "DEF456", fromUrl: true }]) expect(cart).to be_valid end end end describe "alive carts per user" do context "when user is present" do it "validates the user only has one alive cart" do user = create(:user) first_cart = create(:cart, user:) second_cart = build(:cart, user:) expect(second_cart).to be_invalid expect(second_cart.errors.full_messages).to include("An alive cart already exists") first_cart.mark_deleted! expect(second_cart).to be_valid end end context "when browser_guid is present and user is not present" do it "validates that there is only one alive cart per browser_guid for a non-logged-in user" do browser_guid = "123" create(:cart, :guest, browser_guid:) create(:cart, browser_guid:) cart = build(:cart, :guest, browser_guid:) expect(cart).to be_invalid expect(cart.errors.full_messages).to include("An alive cart already exists") end end end end describe "scopes" do describe "abandoned" do it "does not return deleted carts" do cart = create(:cart) cart.mark_deleted! expect(Cart.abandoned).not_to include(cart) end it "does not return carts that have been last updated more than a month ago" do cart = create(:cart, updated_at: 32.days.ago) expect(Cart.abandoned).not_to include(cart) end it "does not return carts that have been last updated less than 24 hours ago" do cart = create(:cart, updated_at: 23.hours.ago) expect(Cart.abandoned).not_to include(cart) end it "does not return carts that have been sent an abandoned cart email" do cart = create(:cart) create(:cart_product, cart:) create(:sent_abandoned_cart_email, cart:) cart.update!(updated_at: 25.hours.ago) expect(Cart.abandoned).not_to include(cart) end it "does not return carts that have no alive cart products" do cart = create(:cart) create(:cart_product, cart:, deleted_at: Time.current) cart.update!(updated_at: 25.hours.ago) expect(Cart.abandoned).not_to include(cart) end it "returns abandoned carts" do cart = create(:cart) create(:cart_product, cart:) cart.update!(updated_at: 25.hours.ago) expect(Cart.abandoned).to include(cart) end end end describe "#abandoned?" do it "returns false for a deleted cart" do cart = create(:cart) cart.mark_deleted! expect(cart.abandoned?).to be(false) end it "returns false if the cart was last updated more than a month ago" do cart = create(:cart, updated_at: 32.days.ago) expect(cart.abandoned?).to be(false) end it "returns false if the cart was last updated less than 24 hours ago" do cart = create(:cart, updated_at: 23.hours.ago) expect(cart.abandoned?).to be(false) end it "returns false if the cart has been sent an abandoned cart email" do cart = create(:cart) create(:cart_product, cart:) create(:sent_abandoned_cart_email, cart:) cart.update!(updated_at: 25.hours.ago) expect(cart.abandoned?).to be(false) end it "returns false if the cart has no alive cart products" do cart = create(:cart) create(:cart_product, cart:, deleted_at: Time.current) cart.update!(updated_at: 25.hours.ago) expect(cart.abandoned?).to be(false) end it "returns true" do cart = create(:cart) create(:cart_product, cart:) cart.update!(updated_at: 25.hours.ago) expect(cart.abandoned?).to be(true) end end describe ".fetch_by" do let(:browser_guid) { SecureRandom.uuid } context "when user is present" do it "returns the alive cart for that user" do user = create(:user) create(:cart, user:, deleted_at: 1.hour.ago) create(:cart, :guest, browser_guid:) user_cart = create(:cart, user:, browser_guid:) expect(Cart.fetch_by(user:, browser_guid:)).to eq(user_cart) expect(Cart.fetch_by(user:, browser_guid: nil)).to eq(user_cart) end end context "when user is not present and browser_guid is present" do let!(:user_cart) { create(:cart, browser_guid:) } let!(:deleted_guest_cart) { create(:cart, :guest, browser_guid:, deleted_at: 1.hour.ago) } let!(:guest_cart) { create(:cart, :guest, browser_guid:) } it "returns the alive cart with the given browser_guid" do expect(Cart.fetch_by(user: nil, browser_guid:)).to eq(guest_cart) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/workflow_spec.rb
spec/models/workflow_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/with_filtering_support" describe Workflow do before do @product = create(:product) @workflow = create(:workflow, seller: @product.user, link: @product) @post = create(:installment, link: @product, workflow: @workflow, published_at: 1.day.ago) @post_rule = create(:installment_rule, installment: @post, delayed_delivery_time: 1.day) @purchase = create(:purchase, link: @product, created_at: 1.minute.ago, price_cents: 100) end describe "scopes" do describe "published" do it "returns only published workflows" do published_workflow = create(:workflow, published_at: 1.day.ago) expect(Workflow.count).to eq(2) expect(Workflow.published).to eq([published_workflow]) end end end describe "#applies_to_purchase?" do context "for a product workflow" do let(:workflow) { create(:workflow) } it "returns true for a purchase of the workflow product" do purchase = create(:purchase, link: workflow.link) expect(workflow.applies_to_purchase?(purchase)).to eq true end it "returns false for a purchase of the workflow product that fails filters" do purchase = create(:purchase, link: workflow.link) allow(workflow).to receive(:purchase_passes_filters).with(purchase).and_return(false) expect(workflow.applies_to_purchase?(purchase)).to eq false end it "returns false for a purchase of a different product" do purchase = create(:purchase) expect(workflow.applies_to_purchase?(purchase)).to eq false end end context "for a variant workflow" do let(:workflow) { create(:variant_workflow) } it "returns true for a purchase of the workflow variant" do purchase = create(:purchase, variant_attributes: [workflow.base_variant]) expect(workflow.applies_to_purchase?(purchase)).to eq true end it "returns false for a purchase of the workflow variant that fails filters" do purchase = create(:purchase, variant_attributes: [workflow.base_variant]) allow(workflow).to receive(:purchase_passes_filters).with(purchase).and_return(false) expect(workflow.applies_to_purchase?(purchase)).to eq false end it "returns false for a purchase of a different variant" do purchase = create(:purchase, variant_attributes: [create(:variant)]) expect(workflow.applies_to_purchase?(purchase)).to eq false end end context "for a seller workflow" do let(:workflow) { create(:seller_workflow) } let(:purchase) { create(:purchase) } it "returns true for a purchase that passes the workflow filters" do allow(workflow).to receive(:purchase_passes_filters).with(purchase).and_return(true) expect(workflow.applies_to_purchase?(purchase)).to eq true end it "returns false for apurchase that fails the workflow filters" do allow(workflow).to receive(:purchase_passes_filters).with(purchase).and_return(false) expect(workflow.applies_to_purchase?(purchase)).to eq false end end end describe "#targets_variant?" do context "for a variant workflow" do let(:workflow) { create(:variant_workflow) } it "returns true if it targets the given variant" do expect(workflow.targets_variant?(workflow.base_variant)).to eq true end it "returns false if it targets a different variant" do expect(workflow.targets_variant?(create(:variant))).to eq false end end context "for a workflow with bought_variants set" do let(:variant) { create(:variant) } let(:workflow) { create(:seller_workflow, bought_variants: [variant.external_id]) } it "returns true if it targets the given variant" do expect(workflow.targets_variant?(variant)).to eq true end it "returns false if it does not target the given variant" do expect(workflow.targets_variant?(create(:variant))).to eq false end end context "for a non-variant workflow without bought_variants set" do it "returns false" do workflow = create(:workflow) expect(workflow.targets_variant?(create(:variant))).to eq false end end end describe "mark_deleted" do it "marks workflow and installments as deleted" do seller = create(:user) link = create(:product, user: seller) product_workflow = create(:workflow, seller:, link:) seller_workflow = create(:workflow, seller:, link: nil) installment1 = create(:installment, workflow: seller_workflow) create(:installment_rule, installment: installment1, delayed_delivery_time: 3.days) installment2 = create(:installment, workflow: product_workflow) create(:installment_rule, installment: installment2, delayed_delivery_time: 3.days) installment3 = create(:installment, workflow: product_workflow) create(:installment_rule, installment: installment3, delayed_delivery_time: 1.day) product_workflow.mark_deleted! expect(product_workflow.reload.deleted_at.present?).to be(true) expect(installment2.reload.deleted_at.present?).to be(true) expect(installment3.reload.deleted_at.present?).to be(true) expect(installment1.reload.deleted_at.present?).to be(false) seller_workflow.mark_deleted! expect(seller_workflow.reload.deleted_at.present?).to be(true) expect(installment1.reload.deleted_at.present?).to be(true) end end describe "#schedule_installment", :freeze_time do it "does nothing when the workflow is not published" do @workflow.mark_deleted! @workflow.schedule_installment(@post) expect(SendWorkflowPostEmailsJob.jobs).to be_empty end it "does nothing when the post is not published" do @post.unpublish! @workflow.schedule_installment(@post) expect(SendWorkflowPostEmailsJob.jobs).to be_empty end it "does nothing when workflow has a trigger" do @workflow.update!(workflow_trigger: Workflow::MEMBER_CANCELLATION_WORKFLOW_TRIGGER) @workflow.schedule_installment(@post) expect(SendWorkflowPostEmailsJob.jobs).to be_empty end it "does nothing if the post is only for new recipients and it hasn't been scheduled before" do @post.update!(is_for_new_customers_of_workflow: true) @workflow.schedule_installment(@post) expect(SendWorkflowPostEmailsJob.jobs).to be_empty end it "does nothing for an abandoned cart installment" do workflow = create(:abandoned_cart_workflow, seller: @workflow.seller, published_at: 1.day.ago) installment = workflow.installments.sole workflow.schedule_installment(installment) expect(SendWorkflowPostEmailsJob.jobs).to be_empty end context "workflow wasn't previously scheduled" do it "enqueues job with earliest_valid_time = nil" do @workflow.schedule_installment(@post) expect(SendWorkflowPostEmailsJob).to have_enqueued_sidekiq_job(@post.id, nil) end end context "workflow was previously scheduled (old_delayed_delivery_time != nil)" do let(:old_delayed_delivery_time) { 6.hours.to_i } context "post is for new recipients" do before { @post.update!(is_for_new_customers_of_workflow: true) } it "enqueues job with earliest_valid_time = post.published_at if the post was published after the old delay" do @post.update!(published_at: 1.hour.ago) @workflow.schedule_installment(@post, old_delayed_delivery_time:) expect(SendWorkflowPostEmailsJob).to have_enqueued_sidekiq_job(@post.id, @post.published_at.iso8601) end it "enqueues job with earliest_valid_time = old_delayed_delivery_time.seconds.ago if the post was published before the old delay" do @post.update!(published_at: 9.hours.ago) @workflow.schedule_installment(@post, old_delayed_delivery_time:) expect(SendWorkflowPostEmailsJob).to have_enqueued_sidekiq_job(@post.id, old_delayed_delivery_time.seconds.ago.iso8601) end end context "post is not for new recipients" do before { @post.update!(is_for_new_customers_of_workflow: false) } it "enqueues job with earliest_valid_time = old_delayed_delivery_time.seconds.ago" do @workflow.schedule_installment(@post, old_delayed_delivery_time:) expect(SendWorkflowPostEmailsJob).to have_enqueued_sidekiq_job(@post.id, old_delayed_delivery_time.seconds.ago.iso8601) end end end end describe "#add_and_validate_filters" do let(:user) { create(:user) } let!(:product) { create(:product, user:) } subject(:add_and_validate_filters) { filterable_object.add_and_validate_filters(params, user) } it_behaves_like "common customer recipient filter validation behavior", audience_type: "product" do let(:filterable_object) { create(:product_workflow, seller: user, link: product) } end it_behaves_like "common customer recipient filter validation behavior", audience_type: "variant" do let(:filterable_object) { create(:variant_workflow, seller: user, link: product) } end it_behaves_like "common customer recipient filter validation behavior", audience_type: "seller" do let(:filterable_object) { create(:seller_workflow, seller: user, link: product) } end it_behaves_like "common non-customer recipient filter validation behavior", audience_type: "audience" do let(:filterable_object) { create(:audience_workflow, seller: user, link: product) } end it_behaves_like "common non-customer recipient filter validation behavior", audience_type: "follower" do let(:filterable_object) { create(:follower_workflow, seller: user, link: product) } end it_behaves_like "common non-customer recipient filter validation behavior", audience_type: "affiliate" do let(:filterable_object) { create(:affiliate_workflow, seller: user, link: product) } end end describe "#publish!" do before do allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE) create(:merchant_account_stripe_connect, user: @workflow.seller) create(:payment_completed, user: @workflow.seller) end it "does nothing if the workflow is already published" do @workflow.update!(published_at: 1.day.ago, first_published_at: 2.days.ago) expect { @workflow.publish! }.not_to change { @workflow.reload } end it "sets 'published_at' and 'first_published_at'" do expect do @workflow.publish! end.to change { @workflow.reload.published_at }.from(nil).to(be_within(1.second).of(Time.current)) .and change { @workflow.reload.first_published_at }.from(nil).to(be_within(1.second).of(Time.current)) end it "does not update 'first_published_at' if it is already set" do @workflow.update!(first_published_at: 2.days.ago) expect do expect do @workflow.publish! end.to change { @workflow.reload.published_at }.from(nil).to(be_within(1.second).of(Time.current)) end.not_to change { @workflow.reload.first_published_at } end it "publishes and schedules all alive installments" do installment1 = create(:installment, workflow: @workflow) installment2 = create(:installment, workflow: @workflow, deleted_at: 1.day.ago) expect(@workflow).to receive(:schedule_installment).with(an_instance_of(Installment)).twice expect do expect do @workflow.publish! end.to change { @post.reload.published_at }.from(kind_of(Time)).to(be_within(1.second).of(Time.current)) .and change { installment1.reload.published_at }.from(nil).to(be_within(1.second).of(Time.current)) end.not_to change { installment2.reload.published_at } end it "raises an error if the seller is not eligible to send emails" do allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE - 1) installment1 = create(:installment, workflow: @workflow) installment2 = create(:installment, workflow: @workflow) expect { @workflow.publish! }.to raise_error(ActiveRecord::RecordInvalid, "Validation failed: You cannot publish a workflow until you have made at least $100 in total earnings and received a payout") expect(@workflow.reload.published_at).to be_nil expect(installment1.reload.published_at).to be_nil expect(installment2.reload.published_at).to be_nil end end describe "#unpublish!" do it "does nothing if the workflow is already unpublished" do expect { @workflow.unpublish! }.not_to change { @workflow.reload } end it "sets 'published_at' to nil and does not change 'first_published_at'" do @workflow.update!(published_at: 1.day.ago, first_published_at: 2.days.ago) expect do expect do @workflow.unpublish! end.to change { @workflow.reload.published_at }.from(kind_of(Time)).to(nil) end.not_to change { @workflow.reload.first_published_at } end it "unpublishes all alive installments" do @workflow.update!(published_at: 1.day.ago) @post.update!(published_at: 1.day.ago) installment1 = create(:installment, workflow: @workflow, published_at: 1.day.ago) installment2 = create(:installment, workflow: @workflow, published_at: 1.day.ago, deleted_at: 1.hour.ago) expect do expect do @workflow.unpublish! end.to change { @post.reload.published_at }.from(kind_of(Time)).to(nil) .and change { installment1.reload.published_at }.from(kind_of(Time)).to(nil) end.not_to change { installment2.reload.published_at } end end describe "#has_never_been_published?" do it "returns true if the workflow has never been published" do expect(@workflow.has_never_been_published?).to be(true) end it "returns false if the workflow has been published before" do @workflow.update!(first_published_at: 1.day.ago) expect(@workflow.has_never_been_published?).to be(false) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/product_affiliate_spec.rb
spec/models/product_affiliate_spec.rb
# frozen_string_literal: true require "spec_helper" describe ProductAffiliate do describe "associations" do it { is_expected.to belong_to(:affiliate) } it { is_expected.to belong_to(:product).class_name("Link") } end describe "validations" do context "when another record exists" do it "validates uniqueness of affiliate scoped to product" do existing = create(:product_affiliate) product_affiliate = build(:product_affiliate, affiliate: existing.affiliate, product: existing.product) expect(product_affiliate).not_to be_valid end end context "for a collaborator" do let(:collaborator) { create(:collaborator, apply_to_all_products: false) } it "validates presence of `affiliate_basis_points` if `apply_to_all_products` is not set" do product_affiliate = build(:product_affiliate, affiliate: collaborator, affiliate_basis_points: nil) expect(product_affiliate).not_to be_valid collaborator.update!(apply_to_all_products: true) product_affiliate = build(:product_affiliate, affiliate: collaborator, affiliate_basis_points: nil) expect(product_affiliate).to be_valid end it "validates `affiliate_basis_points` is in the correct range if present" do product_affiliate = build(:product_affiliate, affiliate: collaborator, affiliate_basis_points: 51_00) expect(product_affiliate).not_to be_valid product_affiliate.affiliate_basis_points = 50_00 expect(product_affiliate).to be_valid product_affiliate.affiliate_basis_points = 0 expect(product_affiliate).not_to be_valid end it "validates that the product has no other live collaborators" do product = create(:product) # ignores affiliates create(:product_affiliate, product:, affiliate: create(:user).global_affiliate) create(:direct_affiliate, products: [product]) product_affiliate = create(:product_affiliate, affiliate: collaborator, product:) expect(product_affiliate).to be_valid new_collaborator = create(:collaborator) product_affiliate = build(:product_affiliate, affiliate: new_collaborator, product:) expect(product_affiliate).not_to be_valid collaborator.mark_deleted! expect(product_affiliate).to be_valid end end context "for a direct affiliate" do it "validates that the product is not a collab" do affiliate = create(:direct_affiliate) product = create(:product, :is_collab) product_affiliate = build(:product_affiliate, affiliate:, product:) expect(product_affiliate).not_to be_valid expect(product_affiliate.errors.full_messages).to eq ["Collab products cannot have affiliates"] end end end describe "lifecycle hooks" do describe "toggling product is_collab flag" do context "for a collaborator" do let!(:affiliate) { create(:collaborator) } it "enables the is_collab flag when a product affiiate is created, and disables any self service affiliate products and direct affiliates" do product = create(:product, is_collab: false) self_service_affiliate_product = create(:self_service_affiliate_product, seller: product.user, product: product, enabled: true) direct_affiliate = create(:direct_affiliate, seller: product.user, products: [product]) expect do create(:product_affiliate, affiliate:, product:) end.to change { product.reload.is_collab }.from(false).to(true) .and change { self_service_affiliate_product.reload.enabled }.from(true).to(false) .and change { direct_affiliate.product_affiliates.count }.from(1).to(0) end it "disables the is_collab flag when a product affiliate is deleted" do product = create(:product, is_collab: true) product_affiliate = create(:product_affiliate, affiliate:, product:) expect do product_affiliate.destroy end.to change { product.reload.is_collab }.from(true).to(false) end end context "for another type of affiliate" do let!(:affiliate) { create(:direct_affiliate) } it "does not change the is_collab flag when a product affiiate is created" do product = create(:product, is_collab: false) expect do create(:product_affiliate, affiliate:, product:) end.not_to change { product.reload.is_collab } end it "does not change the is_collab flag when a product affiliate is deleted" do product = create(:product, is_collab: true) product_affiliate = build(:product_affiliate, affiliate:, product:) product_affiliate.save(validate: false) # bypass `product_is_not_a_collab` validation expect do product_affiliate.destroy end.not_to change { product.reload.is_collab } end end end end describe "#affiliate_percentage" do let(:product_affiliate) { create(:product_affiliate, affiliate_basis_points:) } context "when affiliate_basis_point is nil" do let(:affiliate_basis_points) { nil } it "returns nil" do expect(product_affiliate.affiliate_percentage).to be_nil end end context "when affiliate_basis_point is set" do let(:affiliate_basis_points) { 500 } it "returns the correct affiliate percentage value" do expect(product_affiliate.affiliate_percentage).to eq(5) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/uae_bank_account_spec.rb
spec/models/uae_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe UaeBankAccount do describe "#bank_account_type" do it "returns AE" do expect(create(:uae_bank_account).bank_account_type).to eq("AE") end end describe "#country" do it "returns AE" do expect(create(:uae_bank_account).country).to eq("AE") end end describe "#currency" do it "returns aed" do expect(create(:uae_bank_account).currency).to eq("aed") end end describe "#routing_number" do it "returns nil" do expect(create(:uae_bank_account).routing_number).to be nil end end describe "#account_number_visual" do it "returns the visual account number with country code prefixed" do expect(create(:uae_bank_account, account_number_last_four: "3456").account_number_visual).to eq("AE******3456") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:uae_bank_account)).to be_valid expect(build(:uae_bank_account, account_number: "AE 0703 3123 4567 8901 2345 6")).to be_valid hu_bank_account = build(:uae_bank_account, account_number: "AE12345") expect(hu_bank_account).to_not be_valid expect(hu_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") hu_bank_account = build(:uae_bank_account, account_number: "DE61109010140000071219812874") expect(hu_bank_account).to_not be_valid expect(hu_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") hu_bank_account = build(:uae_bank_account, account_number: "8937040044053201300000") expect(hu_bank_account).to_not be_valid expect(hu_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") hu_bank_account = build(:uae_bank_account, account_number: "AEABCDE") expect(hu_bank_account).to_not be_valid expect(hu_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/costa_rica_bank_account_spec.rb
spec/models/costa_rica_bank_account_spec.rb
# frozen_string_literal: true describe CostaRicaBankAccount do describe "#bank_account_type" do it "returns Costa Rica" do expect(create(:costa_rica_bank_account).bank_account_type).to eq("CR") end end describe "#country" do it "returns CR" do expect(create(:costa_rica_bank_account).country).to eq("CR") end end describe "#currency" do it "returns crc" do expect(create(:costa_rica_bank_account).currency).to eq("crc") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:costa_rica_bank_account, account_number_last_four: "9123").account_number_visual).to eq("CR******9123") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:costa_rica_bank_account)).to be_valid expect(build(:costa_rica_bank_account, account_number: "CR 0401 0212 3678 5670 9123")).to be_valid cr_bank_account = build(:costa_rica_bank_account, account_number: "CR12345") expect(cr_bank_account).to_not be_valid expect(cr_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") cr_bank_account = build(:costa_rica_bank_account, account_number: "DE61109010140000071219812874") expect(cr_bank_account).to_not be_valid expect(cr_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") cr_bank_account = build(:costa_rica_bank_account, account_number: "8937040044053201300000") expect(cr_bank_account).to_not be_valid expect(cr_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") cr_bank_account = build(:costa_rica_bank_account, account_number: "CRABCDE") expect(cr_bank_account).to_not be_valid expect(cr_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/utm_link_visit_spec.rb
spec/models/utm_link_visit_spec.rb
# frozen_string_literal: true require "spec_helper" describe UtmLinkVisit do describe "associations" do it { is_expected.to belong_to(:utm_link) } it { is_expected.to belong_to(:user).optional } it { is_expected.to have_many(:utm_link_driven_sales).dependent(:destroy) } it { is_expected.to have_many(:purchases).through(:utm_link_driven_sales) } end describe "validations" do it { is_expected.to be_versioned } it { is_expected.to validate_presence_of(:ip_address) } it { is_expected.to validate_presence_of(:browser_guid) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/confirmed_follower_event_spec.rb
spec/models/confirmed_follower_event_spec.rb
# frozen_string_literal: true require "spec_helper" describe ConfirmedFollowerEvent do it "can have documents added to its index" do document_id = SecureRandom.uuid EsClient.index( index: described_class.index_name, id: document_id, body: { "followed_user_id" => 123, "name" => "added", "timestamp" => Time.utc(2021, 7, 20, 1, 2, 3) }.to_json ) document = EsClient.get(index: described_class.index_name, id: document_id).fetch("_source") expect(document).to eq( "followed_user_id" => 123, "name" => "added", "timestamp" => "2021-07-20T01:02:03Z" ) end describe "Follower Callbacks" do before do allow(SecureRandom).to receive(:uuid).and_return("fake-random-uuid") @follower = create(:follower, follower_user_id: build(:user)) ElasticsearchIndexerWorker.jobs.clear end it "queues job when confirmation state changes" do # confirming queues a "added" event travel_to Time.utc(2021, 7, 1, 2, 3, 4) do @follower.confirm! end expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("index", { class_name: described_class.name, id: "fake-random-uuid", body: { name: "added", timestamp: "2021-07-01T02:03:04Z", follower_id: @follower.id, followed_user_id: @follower.followed_id, follower_user_id: @follower.follower_user_id, email: @follower.email } }) ElasticsearchIndexerWorker.jobs.clear # Sanity check: changing the value of confirmed_at from a datetime to another datetime should not queue a job @follower.update!(confirmed_at: Time.utc(2020, 1, 1), deleted_at: nil) expect(ElasticsearchIndexerWorker.jobs.size).to eq(0) # unfollowing (= deleting) queues a "removed" event travel_to Time.utc(2021, 7, 2, 3, 4, 5) do @follower.mark_deleted! end expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("index", { class_name: described_class.name, id: "fake-random-uuid", body: { name: "removed", timestamp: "2021-07-02T03:04:05Z", follower_id: @follower.id, followed_user_id: @follower.followed_id, follower_user_id: @follower.follower_user_id, email: @follower.email } }) ElasticsearchIndexerWorker.jobs.clear end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/video_file_spec.rb
spec/models/video_file_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe VideoFile, type: :model do it "schedules a job to analyze the file after creation" do video_file = create(:video_file) expect(AnalyzeFileWorker).to have_enqueued_sidekiq_job(video_file.id, VideoFile.name) end describe "#url" do it "must startwith S3_BASE_URL" do video_file = build(:video_file) video_file.url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/video.mp4" video_file.validate expect(video_file.errors[:url]).to be_empty video_file.url = "https://example.com/video.mp4" video_file.validate expect(video_file.errors[:url]).to include("must be an S3 URL") end end describe "#smil_xml" do it "returns properly formatted SMIL XML with signed cloudfront URL" do s3_key = "attachments/1234567890abcdef1234567890abcdef/original/myvideo.mp4" s3_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/1234567890abcdef1234567890abcdef/original/myvideo.mp4" signed_url = "https://cdn.example.com/signed-url-for-video.mp4" video_file = create(:video_file, url: s3_url) allow(video_file).to receive(:signed_cloudfront_url).with(s3_key, is_video: true).and_return(signed_url) expected_xml = <<~XML.strip <smil><body><switch><video src="#{signed_url}"/></switch></body></smil> XML expect(video_file.smil_xml).to eq(expected_xml) end end describe "#set_filetype" do it "sets filetype based on the file extension" do video_file = create(:video_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/video.mp4", filetype: nil) expect(video_file.filetype).to eq("mp4") video_file.update!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/video.mov") expect(video_file.filetype).to eq("mov") video_file.update!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/video.webm") expect(video_file.filetype).to eq("webm") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/benin_bank_account_spec.rb
spec/models/benin_bank_account_spec.rb
# frozen_string_literal: true describe BeninBankAccount do describe "#bank_account_type" do it "returns BJ" do expect(create(:benin_bank_account).bank_account_type).to eq("BJ") end end describe "#country" do it "returns BJ" do expect(create(:benin_bank_account).country).to eq("BJ") end end describe "#currency" do it "returns xof" do expect(create(:benin_bank_account).currency).to eq("xof") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:benin_bank_account, account_number_last_four: "0769").account_number_visual).to eq("BJ******0769") end end describe "#routing_number" do it "returns nil" do expect(create(:benin_bank_account).routing_number).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/models/pakistan_bank_account_spec.rb
spec/models/pakistan_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe PakistanBankAccount do describe "#bank_account_type" do it "returns Pakistan" do expect(create(:pakistan_bank_account).bank_account_type).to eq("PK") end end describe "#country" do it "returns PK" do expect(create(:pakistan_bank_account).country).to eq("PK") end end describe "#currency" do it "returns pkr" do expect(create(:pakistan_bank_account).currency).to eq("pkr") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:pakistan_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAAPKKAXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:pakistan_bank_account, account_number_last_four: "6702").account_number_visual).to eq("******6702") end end describe "#validate_bank_code" do it "allows 8 to 11 characters only" do expect(build(:pakistan_bank_account, bank_code: "AAAAPKKAXXX")).to be_valid expect(build(:pakistan_bank_account, bank_code: "AAAAPKKA")).to be_valid expect(build(:pakistan_bank_account, bank_code: "AAAAPKK")).not_to be_valid expect(build(:pakistan_bank_account, bank_code: "AAAAPKKAXXXX")).not_to be_valid end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:pakistan_bank_account)).to be_valid expect(build(:pakistan_bank_account, account_number: "PK36SCBL0000001123456702")).to be_valid pk_bank_account = build(:pakistan_bank_account, account_number: "PK12345") expect(pk_bank_account).to_not be_valid expect(pk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") pk_bank_account = build(:pakistan_bank_account, account_number: "PK36SCBL00000011234567021") expect(pk_bank_account).to_not be_valid expect(pk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") pk_bank_account = build(:pakistan_bank_account, account_number: "PK36SCBL000000112345670") expect(pk_bank_account).to_not be_valid expect(pk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") pk_bank_account = build(:pakistan_bank_account, account_number: "PKABCDE") expect(pk_bank_account).to_not be_valid expect(pk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/url_redirect_spec.rb
spec/models/url_redirect_spec.rb
# frozen_string_literal: true require "spec_helper" describe UrlRedirect do before do allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000) @good_kindle_email = "maxwell_1234@kindle.com" end it "has a token that is unique" do url_redirect = create(:url_redirect) expect(url_redirect.token).to_not be(nil) expect(url_redirect.token.size).to be > 10 end describe "product_files_hash" do let(:product) { create(:product) } let!(:readable_document) { create(:readable_document, link: product) } let!(:video) { create(:streamable_video, link: product) } let!(:stream_only_video) { create(:streamable_video, stream_only: true, link: product, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/43a5363194e74e9ee75b6203eaea6705/original/episode2.mp4") } let!(:deleted_file) { create(:listenable_audio, deleted_at: Time.current) } let(:purchase) { create(:purchase, link: product) } let(:url_redirect) { create(:url_redirect, purchase:) } before do allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000) end it "only contains alive, non-stream only product files" do travel_to(Time.current) do product_files_hash = JSON.parse(url_redirect.product_files_hash) expect(product_files_hash.length).to eq 2 expect(product_files_hash).to include("url" => purchase.url_redirect.signed_location_for_file(readable_document), "filename" => readable_document.s3_filename) expect(product_files_hash).to include("url" => purchase.url_redirect.signed_location_for_file(video), "filename" => video.s3_filename) expect(product_files_hash).to_not include("url" => purchase.url_redirect.signed_location_for_file(stream_only_video), "filename" => stream_only_video.s3_filename) expect(product_files_hash).to_not include("url" => purchase.url_redirect.signed_location_for_file(deleted_file), "filename" => deleted_file.s3_filename) end end end describe "referenced_link" do describe "test purchase" do before do @product = create(:product) @url_redirect = create(:url_redirect, link: @product, purchase: nil) end it "returns the correct link" do expect(@url_redirect.referenced_link).to eq @product end end describe "imported_customer" do before do @product = create(:product) @imported_customer = create(:imported_customer, link: @product, importing_user: @product.user) @url_redirect = create(:url_redirect, link: @product, imported_customer: @imported_customer, purchase: nil) end it "returns the correct link for an imported_customer without a url_redirect" do expect(@url_redirect.referenced_link).to eq @product end end describe "normal purchase" do before do @product = create(:product) @purchase = create(:purchase, link: @product) @url_redirect = create(:url_redirect, purchase: @purchase) end it "returns the correct link" do expect(@url_redirect.referenced_link).to eq @product end end end describe "url" do before do @url_redirect = create(:url_redirect) end it "returns the correct url" do expect(@url_redirect.url).to eq "http://#{DOMAIN}/r/#{@url_redirect.token}" end end describe "redirect_or_s3_location" do describe "imported_customer" do before do @product = create(:product) @imported_customer = create(:imported_customer, link: @product, importing_user: @product.user) travel_to(Time.current) end it "returns the right url when there is no provided url redirect for and installment" do @url_redirect = create(:url_redirect, link: @product, imported_customer: @imported_customer, purchase: nil) @installment = create(:installment, link: @product, installment_type: "product") @product.product_files << create( :product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/43a5363194e74e9ee75b6203eaea6705/original/manual.pdf" ) expect(@url_redirect.redirect_or_s3_location).to eq @url_redirect.signed_location_for_file(@product.alive_product_files.first) end it "returns the file url for an external link file" do @url_redirect = create(:url_redirect, link: @product, purchase: nil) @product.product_files << create(:product_file, url: "http://gumroad.com", filetype: "link") expect(@url_redirect.redirect_or_s3_location).to eq @url_redirect.signed_location_for_file(@product.alive_product_files.first) end it "returns the right url when there is no provided url redirect for an installment and there are multiple files" do @url_redirect = create(:url_redirect, link: @product, imported_customer: @imported_customer, purchase: nil) @installment = create(:installment, link: @product, installment_type: "product") 3.times do @product.product_files << create( :product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/43a5363194e74e9ee75b6203eaea6705/original/manual.pdf" ) end expect(@url_redirect.redirect_or_s3_location).to eq @url_redirect.download_page_url end it "returns the right url when there is a provided url redirect for an installment" do @installment = create(:installment, link: @product, installment_type: "product") url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/43a5363194e74e9ee75b6203eaea6705/original/chapter1.mp4" @installment.product_files << create(:product_file, url:) @installment_url_redirect = create(:url_redirect, installment: @installment, imported_customer: @imported_customer, link: @product) @product.product_files << create(:product_file, url:) url = "https://d3t5lixau6dhwk.cloudfront.net/attachments/43a5363194e74e9ee75b6203eaea6705/original/chapter1.mp4?response-content-disposition=" url += "attachment&Expires=1414098718&Signature=gidpQSe4zFcVs5K9fTzno4wb3RTJrDlwX3s4I4zC1FVaNNSDmMlUj2Vqkaa8S7X7mE4Ep4BHtn+" url += "ZZa8aEJ4WM4JC4fXQJLElrR4XNNOq8UfXsVX6CwNGLeZQue1rCpq9Gj3anqml5zj1jrSGr3qGk6P4eeKJy6y1D5XF51CE0no=&Key-Pair-Id=APKAISH5PKOS7WQUJ6SA" expect_any_instance_of(UrlRedirect).to receive(:signed_download_url_for_s3_key_and_filename) .with("attachments/43a5363194e74e9ee75b6203eaea6705/original/chapter1.mp4", "chapter1.mp4", { is_video: true }).and_return(url) url = "https://d3t5lixau6dhwk.cloudfront.net/attachments/43a5363194e74e9ee75b6203eaea6705/original/chapter1.mp4?response-content-disposition=" url += "attachment&Expires=1414098718&Signature=gidpQSe4zFcVs5K9fTzno4wb3RTJrDlwX3s4I4zC1FVaNNSDmMlUj2Vqkaa8S7X7mE4Ep4BHtn+ZZa8" url += "aEJ4WM4JC4fXQJLElrR4XNNOq8UfXsVX6CwNGLeZQue1rCpq9Gj3anqml5zj1jrSGr3qGk6P4eeKJy6y1D5XF51CE0no=&Key-Pair-Id=APKAISH5PKOS7WQUJ6SA" expect(@installment_url_redirect.redirect_or_s3_location) .to eq(url) end end end describe "#is_file_downloadable" do let(:product) { create(:product) } let(:url_redirect) { create(:url_redirect, link: product) } it "returns false if product is a rental and file is streamable" do url_redirect.update!(is_rental: true) product_file = create(:streamable_video, link: product) expect(url_redirect.is_file_downloadable?(product_file)).to eq(false) end it "returns false if file is an external link" do product_file = create(:external_link, link: product) expect(url_redirect.is_file_downloadable?(product_file)).to eq(false) end it "returns false if file is stream-only" do product_file = create(:streamable_video, stream_only: true, link: product) expect(url_redirect.is_file_downloadable?(product_file)).to eq(false) end it "returns true if file can be downloaded" do product_file = create(:readable_document, link: product) expect(url_redirect.is_file_downloadable?(product_file)).to eq(true) end end describe "#entity_archive" do before do @product = create(:product) @url_redirect = create(:url_redirect, link: @product, purchase: create(:purchase, link: @product, purchaser: create(:user))) create(:product_files_archive, link: @product, product_files_archive_state: :ready) @last_product_files_archive = create(:product_files_archive, link: @product, product_files_archive_state: :ready) end it "returns the most recent archive" do expect(@url_redirect.entity_archive).to eq(@last_product_files_archive) end it "returns nil if product has stampable pdfs" do @product.product_files << create(:readable_document, pdf_stamp_enabled: true) expect(@url_redirect.entity_archive).to eq(nil) end end describe "#folder_archive" do before do @product = create(:product) @folder_id = SecureRandom.uuid folder_archive1 = @product.product_files_archives.create!(folder_id: @folder_id) folder_archive1.mark_in_progress! folder_archive1.mark_ready! @folder_archive2 = @product.product_files_archives.create!(folder_id: @folder_id) @folder_archive2.mark_in_progress! @folder_archive2.mark_ready! purchase = create(:purchase, link: @product, purchaser: create(:user)) @url_redirect = create(:url_redirect, link: @product, purchase:) end it "returns the most recent archive" do expect(@url_redirect.folder_archive(@folder_id)).to eq(@folder_archive2) end it "returns nil if product has stampable pdfs" do @product.product_files << create(:readable_document, pdf_stamp_enabled: true) expect(UrlRedirect.find(@url_redirect.id).folder_archive(@folder_id)).to eq(nil) end end describe "streaming" do before do @product = create(:product) @product.product_files << create( :product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/43a5363194e74e9ee75b6203eaea6705/original/episode1.mp4" ) @product.product_files << create( :product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/43a5363194e74e9ee75b6203eaea6705/original/episode2.mp4" ) @product.product_files << create( :product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/43a5363194e74e9ee75b6203eaea6705/original/manual.pdf" ) @product.save! @url_redirect = create(:url_redirect, link: @product, purchase: nil) end it "creates the right signed url for a file" do signed_s3_url = @url_redirect.signed_location_for_file(@product.product_files.first) expect(signed_s3_url).to match(/X-Amz-Signature=/) expect(signed_s3_url).to match(/episode1/) expect(signed_s3_url).to_not match(/episode2/) expect(signed_s3_url).to_not match(/manual/) end it "creates the correct signed URL for a stamped pdf" do pdf_product_file = @product.product_files.alive.pdf.last pdf_product_file.update!(pdf_stamp_enabled: true) url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/43a5363194e74e9ee75b6203eaea6705/original/stamped_manual.pdf" @url_redirect.stamped_pdfs.create!(product_file: pdf_product_file, url:) signed_s3_url = @url_redirect.signed_location_for_file(pdf_product_file) expect(signed_s3_url).to match(/X-Amz-Signature=/) expect(signed_s3_url).to match(/stamped_manual/) end end describe "product_file_json_data_for_mobile" do context "when there is an associated purchase" do it "contains the purchase information if there is an associated purchase" do product = create(:product) product.product_files << create( :product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/6996320f4de6424990904fcda5808cef/original/Don&amp;#39;t Stop.mp3" ) product.product_files << create( :product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/a1a5b8c8c38749e2b3cb27099a817517/original/Alice&#39;s Adventures in Wonderland.pdf" ) purchase = create(:purchase, link: product, purchaser: create(:user)) url_redirect = create(:url_redirect, link: product, purchase:) product_json = url_redirect.product_json_data expect(product_json[:purchased_at]).to eq purchase.created_at expect(product_json[:user_id]).to eq purchase.purchaser.external_id end it "includes deprecated `custom_delivery_url` attribute" do product = create(:product) purchase = create(:purchase, link: product) url_redirect = create(:url_redirect, link: product, purchase:) expect(url_redirect.product_json_data).to include(custom_delivery_url: nil) end end end describe "#video_files_playlist" do let(:product) { create(:product) } let(:file2) { create(:product_file, link: product, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4", position: 3) } let(:file4) { create(:product_file, link: product, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/4/original/chapter4.mp4", position: 0) } let(:file1) { create(:product_file, link: product, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/1/original/chapter1.mp4", position: 2) } let(:file3) { create(:product_file, link: product, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/3/original/chapter3.mp4", position: 1) } before do allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000) product.product_files = [file2, file4, file1, file3] product.save! end context "when the purchased product has rich content" do let(:rich_content_description) do [ { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Hello" }] }, { "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "World" }] }, { "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Lorem ipsum" }] }, { "type" => "fileEmbed", "attrs" => { "id" => file3.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file4.external_id, "uid" => SecureRandom.uuid } }, ] end context "when the purchase is associated with the product" do let(:purchase) { build(:purchase, link: product) } let(:url_redirect) { create(:url_redirect, link: product, purchase:) } let!(:rich_content) { create(:product_rich_content, entity: product, description: rich_content_description) } it "returns the video files playlist with files ordered by how they appear in the product-level rich content" do video_playlist = url_redirect.video_files_playlist(file1)[:playlist] expect(video_playlist.size).to eq 4 expect(video_playlist[0][:sources][1]).to include file1.s3_filename expect(video_playlist[1][:sources][1]).to include file2.s3_filename expect(video_playlist[2][:sources][1]).to include file3.s3_filename expect(video_playlist[3][:sources][1]).to include file4.s3_filename end end context "when the purchase is associated with a product variant" do let(:category) { create(:variant_category, link: product) } let(:variant1) { create(:variant, variant_category: category, product_files: [file1, file3, file4, file2]) } let(:variant2) { create(:variant, variant_category: category, product_files: [file2]) } let(:purchase) { build(:purchase, link: product, variant_attributes: [variant1]) } let(:url_redirect) { create(:url_redirect, link: product, purchase:) } let!(:variant1_rich_content) { create(:product_rich_content, entity: variant1, description: rich_content_description) } let!(:variant2_rich_content) { create(:product_rich_content, entity: variant2, description: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Hello" }] }, { "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } }]) } it "returns the video files playlist with files ordered by how they appear in the variant-level rich content" do video_playlist = url_redirect.video_files_playlist(file1)[:playlist] expect(video_playlist.size).to eq 4 expect(video_playlist[0][:sources][1]).to include file1.s3_filename expect(video_playlist[1][:sources][1]).to include file2.s3_filename expect(video_playlist[2][:sources][1]).to include file3.s3_filename expect(video_playlist[3][:sources][1]).to include file4.s3_filename end end end it "returns the video files playlist with files ordered by their position for an installment" do installment = create(:installment) installment.product_files = [file2, file4, file1, file3] url_redirect = create(:installment_url_redirect, installment:) url_redirect_id = url_redirect.id video_playlist = url_redirect.video_files_playlist(file2)[:playlist] expect(video_playlist.size).to eq 4 expect(video_playlist[0][:sources][1]).to include file4.s3_filename expect(video_playlist[1][:sources][1]).to include file3.s3_filename expect(video_playlist[2][:sources][1]).to include file1.s3_filename expect(video_playlist[3][:sources][1]).to include file2.s3_filename [file1, file2, file3, file4].each_with_index do |file, index| file.position = index file.save! end url_redirect = UrlRedirect.find(url_redirect_id) # clears the cached #alive_product_files video_playlist = url_redirect.video_files_playlist(file2)[:playlist] expect(video_playlist.size).to eq 4 expect(video_playlist[0][:sources][1]).to include file1.s3_filename expect(video_playlist[1][:sources][1]).to include file2.s3_filename expect(video_playlist[2][:sources][1]).to include file3.s3_filename expect(video_playlist[3][:sources][1]).to include file4.s3_filename end it "sets the `index_to_play` to 0 if there are no files to include" do url_redirect = create(:url_redirect, link: product, purchase: build(:purchase, link: product)) product.product_files.destroy_all expect(url_redirect.video_files_playlist(file2)[:index_to_play]).to eq(0) end it "sets the `index_to_play` to 0 if the initial_product_file is not a part of the products belonging to the UrlRedirect" do url_redirect = create(:url_redirect, link: product, purchase: build(:purchase, link: product)) expect(url_redirect.video_files_playlist(create(:product_file))[:index_to_play]).to eq(0) end end describe "#html5_video_url_and_guid_for_product_file" do before do @multifile_product = create(:product) @file_1 = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4") @multifile_product.product_files << @file_1 @file_2 = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/3/original/chapter3.mp4") @multifile_product.product_files << @file_2 @multifile_url_redirect = create(:url_redirect, link: @multifile_product, purchase: nil) allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000) end it "returns the video URL and GUID for the file" do expected_video_url = @multifile_url_redirect.signed_video_url(@file_1) expected_guid = expected_video_url[described_class::GUID_GETTER_FROM_S3_URL_REGEX, 1] expected_video_url.sub!(expected_guid, described_class::FAKE_VIDEO_URL_GUID_FOR_OBFUSCATION) video_url, guid = @multifile_url_redirect.send(:html5_video_url_and_guid_for_product_file, @file_1) expect(video_url).to eq(expected_video_url) expect(guid).to eq(expected_guid) expected_video_url = @multifile_url_redirect.signed_video_url(@file_2) expected_guid = expected_video_url[described_class::GUID_GETTER_FROM_S3_URL_REGEX, 1] expected_video_url.sub!(expected_guid, described_class::FAKE_VIDEO_URL_GUID_FOR_OBFUSCATION) video_url, guid = @multifile_url_redirect.send(:html5_video_url_and_guid_for_product_file, @file_2) expect(video_url).to eq(expected_video_url) expect(guid).to eq(expected_guid) end end describe "#update_rental_expired" do it "updates purchase rental_expired if is_rental is set to false" do url_redirect = create(:url_redirect, is_rental: true) url_redirect.update!(is_rental: false) expect(url_redirect.purchase.rental_expired).to eq(nil) end end describe "#with_product_files" do it "returns the correct object when associated with an installment" do product = create(:product_with_files) purchase = create(:purchase, link: product) installment = create(:installment, link: product, installment_type: "product") installment.product_files << product.product_files.first installment.save! url_redirect = create(:url_redirect, link: product, purchase:, installment:) expect(url_redirect.with_product_files).to eq installment end it "returns the correct object when associated with a product" do product = create(:product) purchase = create(:purchase, link: product) url_redirect = create(:url_redirect, purchase:) expect(url_redirect.with_product_files).to eq product end context "for a variant" do before do @product = create(:product_with_files) @variant = create(:variant, variant_category: create(:variant_category, link: @product)) @variant.product_files << @product.product_files.first @purchase = create(:purchase, link: @variant.link, variant_attributes: [@variant]) @url_redirect = create(:url_redirect, purchase: @purchase) end context "when the variant has no associated product files" do before do @variant.product_files = [] @variant.save! end it "returns the variant" do expect(@url_redirect.with_product_files).to eq(@variant) end end it "returns the correct object" do expect(@url_redirect.with_product_files).to eq @variant end it "returns the correct object when associated with a variant that has been deleted" do @variant.mark_deleted! expect(@url_redirect.reload.with_product_files).to eq @variant end it "returns the object for the non-deleted variant if only some variants have been deleted" do @variant.mark_deleted! live_variant = create(:variant, variant_category: create(:variant_category, link: @product)) @variant.product_files << @product.product_files.last @purchase.variant_attributes << live_variant expect(@url_redirect.reload.with_product_files).to eq live_variant end end end describe "#rich_content_json" do it "returns empty hash if there's no associated object" do url_redirect = create(:url_redirect) expect(url_redirect.rich_content_json).to eq([]) end it "returns nil when associated with an installment" do product = create(:product_with_files) create(:product_rich_content, entity: product) purchase = create(:purchase, link: product) installment = create(:installment, link: product, installment_type: "product") installment.product_files << product.product_files.first installment.save! url_redirect = create(:url_redirect, link: product, purchase:, installment:) expect(url_redirect.rich_content_json).to be_nil end context "when associated with a variant" do before do @product = create(:product_with_files) create(:rich_content, entity: @product, title: "Product-level page", description: [{ "type" => "paragraph", "content" => [{ "text" => "This is product-level rich content", "type" => "text" }] }]) @variant = create(:variant, variant_category: create(:variant_category, link: @product), price_difference_cents: 100) @variant.product_files << @product.product_files.first create(:rich_content, entity: @variant, title: "Variant-level page", description: [{ "type" => "paragraph", "content" => [{ "text" => "This is variant-level rich content", "type" => "text" }] }]) @purchase = create(:purchase, link: @variant.link, variant_attributes: [@variant]) @url_redirect = create(:url_redirect, purchase: @purchase) end context "when associated product's `has_same_rich_content_for_all_variants` is set to true" do before do @product.update!(has_same_rich_content_for_all_variants: true) end it "returns the product-level rich content" do rich_content = @product.alive_rich_contents.first expect(@url_redirect.rich_content_json).to eq([{ id: rich_content.external_id, page_id: rich_content.external_id, variant_id: nil, title: "Product-level page", description: { type: "doc", content: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "This is product-level rich content" }] }] }, updated_at: rich_content.updated_at }]) end end context "when associated product's `has_same_rich_content_for_all_variants` is set to false" do before do @product.update!(has_same_rich_content_for_all_variants: false) end it "returns the variant-level rich content" do rich_content = @variant.alive_rich_contents.first expect(@url_redirect.rich_content_json).to eq([{ id: rich_content.external_id, page_id: rich_content.external_id, variant_id: @variant.external_id, title: "Variant-level page", description: { type: "doc", content: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "This is variant-level rich content" }] }] }, updated_at: rich_content.updated_at }]) end end it "returns the rich content of the cheapest variant when the purchase is associated with a deleted variant" do @product.alive_rich_contents.find_each(&:mark_deleted!) variant_category = create(:variant_category, link: @product) old_variant = create(:variant, variant_category:, price_difference_cents: 100, product_files: @product.product_files) variant1 = create(:variant, variant_category:, price_difference_cents: 100, product_files: @product.product_files) variant2 = create(:variant, variant_category:, price_difference_cents: 50, product_files: @product.product_files) old_variant_rich_content = create(:rich_content, entity: old_variant, title: "Old variant page title", description: [{ "type" => "paragraph", "content" => [{ "text" => "Lorem ipsum", "type" => "text" }] }]) create(:rich_content, entity: variant1, title: "Variant 1 page title", description: [{ "type" => "paragraph", "content" => [{ "text" => "Lorem ipsum", "type" => "text" }] }]) variant2_rich_content = create(:rich_content, entity: variant2, title: "Variant 2 page title", description: [{ "type" => "paragraph", "content" => [{ "text" => "Lorem ipsum", "type" => "text" }] }]) @purchase.variant_attributes = [old_variant] expect(@url_redirect.rich_content_json).to eq([{ id: old_variant_rich_content.external_id, page_id: old_variant_rich_content.external_id, variant_id: old_variant.external_id, title: "Old variant page title", description: { type: "doc", content: old_variant_rich_content.description }, updated_at: old_variant_rich_content.updated_at }]) old_variant.mark_deleted! old_variant.alive_rich_contents.find_each(&:mark_deleted!) expect(UrlRedirect.find(@url_redirect.id).rich_content_json).to eq([{ id: variant2_rich_content.external_id, page_id: variant2_rich_content.external_id, variant_id: variant2.external_id, title: "Variant 2 page title", description: { type: "doc", content: variant2_rich_content.description }, updated_at: variant2_rich_content.updated_at }]) end it "returns the product-level rich content when the purchase is associated with a deleted variant and there are no other variants" do old_variant_rich_content = @variant.alive_rich_contents.first expect(@url_redirect.rich_content_json).to eq([{ id: old_variant_rich_content.external_id, page_id: old_variant_rich_content.external_id, variant_id: @variant.external_id, title: "Variant-level page", description: { type: "doc", content: old_variant_rich_content.description }, updated_at: old_variant_rich_content.updated_at }]) @variant.mark_deleted! @variant.alive_rich_contents.find_each(&:mark_deleted!) product_level_rich_content = @product.alive_rich_contents.first expect(UrlRedirect.find(@url_redirect.id).rich_content_json).to eq([{ id: product_level_rich_content.external_id, page_id: product_level_rich_content.external_id, variant_id: nil, title: "Product-level page", description: { type: "doc", content: product_level_rich_content.description }, updated_at: product_level_rich_content.updated_at }]) end end context "when associated with a product" do before do @product = create(:product_with_files) @rich_content = create(:product_rich_content, entity: @product, title: "Page title", description: [{ "type" => "paragraph", "content" => [{ "text" => "Lorem ipsum", "type" => "text" }] }]) @purchase = create(:purchase, link: @product) @url_redirect = create(:url_redirect, purchase: @purchase) end it "returns product-level rich content" do expect(@url_redirect.rich_content_json).to eq([{ id: @rich_content.external_id, page_id: @rich_content.external_id, variant_id: nil, title: "Page title", description: { type: "doc", content: @rich_content.description }, updated_at: @rich_content.updated_at }]) end it "returns the rich content of the cheapest variant when the purchase is associated with the product but there are variants" do variant_category = create(:variant_category, link: @product) variant1 = create(:variant, variant_category:, price_difference_cents: 100, product_files: @product.product_files) variant2 = create(:variant, variant_category:, price_difference_cents: 50, product_files: @product.product_files) create(:rich_content, entity: variant1, title: "Variant 1 page title", description: [{ "type" => "paragraph", "content" => [{ "text" => "Lorem ipsum", "type" => "text" }] }]) variant2_rich_content = create(:rich_content, entity: variant2, title: "Variant 2 page title", description: [{ "type" => "paragraph", "content" => [{ "text" => "Lorem ipsum", "type" => "text" }] }]) # On adding a variant, the product-level rich content gets deleted automatically @product.alive_rich_contents.find_each(&:mark_deleted!) expect(@url_redirect.rich_content_json).to eq([{ id: variant2_rich_content.external_id, page_id: variant2_rich_content.external_id, variant_id: variant2.external_id, title: "Variant 2 page title", description: { type: "doc", content: variant2_rich_content.description }, updated_at: variant2_rich_content.updated_at }]) end end context "when associated with a completed commission", :vcr do let(:commission) { create(:commission, status: Commission::STATUS_COMPLETED) } before do commission.files.attach(file_fixture("smilie.png")) commission.files.attach(file_fixture("test.pdf")) commission.deposit_purchase.create_url_redirect! end it "includes commission files in the rich content json" do rich_content_json = commission.deposit_purchase.url_redirect.rich_content_json expect(rich_content_json).to eq( [ { id: "", page_id: "", title: "Downloads", variant_id: nil, description: { type: "doc", content: [ { type: "fileEmbed", attrs: { id: commission.files.first.signed_id, } }, {
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/ach_account_spec.rb
spec/models/ach_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe AchAccount do describe "#routing_number" do let(:ach_account) { build(:ach_account) } describe "is valid" do before do expect(described_class).to receive(:routing_number_valid?).and_return(true) end it "does not valid" do expect(ach_account).to be_valid end end describe "is invalid" do before do expect(described_class).to receive(:routing_number_valid?).and_return(false) end it "is not valid" do expect(ach_account).not_to be_valid end end end describe "#account_number" do let(:ach_account) { build(:ach_account) } describe "is valid" do before do expect(described_class).to receive(:account_number_valid?).and_return(true) end it "does not valid" do expect(ach_account).to be_valid end end describe "is invalid" do before do expect(described_class).to receive(:account_number_valid?).and_return(false) end it "is not valid" do expect(ach_account).not_to be_valid end end end describe "account types" do it "allows checking account types" do ach = build(:ach_account, account_type: AchAccount::AccountType::CHECKING) expect(ach).to be_valid expect(ach.account_type).to eq(AchAccount::AccountType::CHECKING) end it "allows savings account types" do ach = build(:ach_account, account_type: AchAccount::AccountType::SAVINGS) expect(ach).to be_valid expect(ach.account_type).to eq(AchAccount::AccountType::SAVINGS) end it "invalidates other account types" do ach = build(:ach_account, account_type: "evil_account_type") expect(ach).to_not be_valid end it "translates a nil account type to the default (checking)" do ach = build(:ach_account, account_type: nil) expect(ach).to be_valid expect(ach.account_type).to eq(AchAccount::AccountType::CHECKING) end end describe ".routing_number_valid?" do describe "is 9 numerics" do let(:routing_number) { "121000497" } it "returns true" do expect(described_class.routing_number_valid?(routing_number)).to eq(true) end end describe "is nil" do let(:routing_number) { nil } it "returns false" do expect(described_class.routing_number_valid?(routing_number)).to eq(false) end end describe "is 9 numerics plus whitespace" do let(:routing_number) { "121000497 " } it "returns false" do expect(described_class.routing_number_valid?(routing_number)).to eq(false) end end describe "is 9 alphanumerics" do let(:routing_number) { "12100049a" } it "returns false" do expect(described_class.routing_number_valid?(routing_number)).to eq(false) end end describe "is > 9 numerics" do let(:routing_number) { "1210004971" } it "returns false" do expect(described_class.routing_number_valid?(routing_number)).to eq(false) end end describe "is < 9 numerics" do let(:routing_number) { "12100049" } it "returns false" do expect(described_class.routing_number_valid?(routing_number)).to eq(false) end end end describe ".routing_number_check_digit_valid?" do describe "valid check digit" do let(:valid_routing_numbers) do [ "121000497", "110000000", # Some of US Bank's Routing Numbers "122105155", "082000549", "121122676", "122235821", "102101645", "102000021", "123103729", "071904779", "081202759", "074900783", "104000029", "073000545", "101000187", "042100175", "083900363", "091215927", "091300023", "091000022", "081000210", "101200453", "092900383", "104000029", "121201694", "107002312", "091300023", "041202582", "042000013", "123000220", "091408501", "064000059", "124302150", "125000105", "075000022", "307070115", "091000022", # Some of WellsFargo's Routing Numbers "125200057", "121042882", "321270742" ] end let(:routing_number) { "121000497" } it "returns true" do valid_routing_numbers.each do |valid_routing_number| expect(described_class.routing_number_check_digit_valid?(valid_routing_number)).to eq(true) end end end describe "invalid check digit" do describe "example" do let(:routing_number) { "121000498" } it "returns false" do expect(described_class.routing_number_check_digit_valid?(routing_number)).to eq(false) end end describe "example" do let(:routing_number) { "110000001" } it "returns false" do expect(described_class.routing_number_check_digit_valid?(routing_number)).to eq(false) end end end end describe ".account_number_valid?" do describe "is 1 numerics" do let(:account_number) { "1" } it "returns true" do expect(described_class.account_number_valid?(account_number)).to eq(true) end end describe "is 10 numerics" do let(:account_number) { "1234567890" } it "returns true" do expect(described_class.account_number_valid?(account_number)).to eq(true) end end describe "is 17 numerics" do let(:account_number) { "12345678901234567" } it "returns true" do expect(described_class.account_number_valid?(account_number)).to eq(true) end end describe "is nil" do let(:account_number) { nil } it "returns false" do expect(described_class.account_number_valid?(account_number)).to eq(false) end end describe "is 10 numerics plus whitespace" do let(:account_number) { "1234567890 " } it "returns false" do expect(described_class.account_number_valid?(account_number)).to eq(false) end end describe "is 10 alphanumerics" do let(:account_number) { "123456789a" } it "returns false" do expect(described_class.account_number_valid?(account_number)).to eq(false) end end describe "is > 17 numerics" do let(:account_number) { "12345678901234567890" } it "returns false" do expect(described_class.account_number_valid?(account_number)).to eq(false) end end describe "is < 1 numerics" do let(:account_number) { "" } it "returns false" do expect(described_class.account_number_valid?(account_number)).to eq(false) end end end describe "#validate_bank_name" do it "disallows records with bank name 'GREEN DOT BANK'" do ach_account = build(:ach_account, bank_number: create(:bank, routing_number: "121000497", name: "GREEN DOT BANK").routing_number) expect(ach_account).to_not be_valid expect(ach_account.errors.full_messages.to_sentence).to eq("Sorry, we don't support that bank account provider.") end it "disallows records with bank name 'METABANK MEMPHIS'" do ach_account = build(:ach_account, bank_number: create(:bank, routing_number: "121000497", name: "METABANK MEMPHIS").routing_number) expect(ach_account).to_not be_valid expect(ach_account.errors.full_messages.to_sentence).to eq("Sorry, we don't support that bank account provider.") end it "allows records with any other bank name" do ach_account = build(:ach_account) expect(ach_account).to be_valid end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/user_compliance_info_spec.rb
spec/models/user_compliance_info_spec.rb
# frozen_string_literal: true require "spec_helper" describe UserComplianceInfo do describe "encrypted" do describe "individual_tax_id" do let(:user_compliance_info) { create(:user_compliance_info, individual_tax_id: "123456789") } it "is encrypted" do expect(user_compliance_info.individual_tax_id).to be_a(Strongbox::Lock) expect(user_compliance_info.individual_tax_id.decrypt("1234")).to eq("123456789") end it "outputs '*encrypted*' if no password given to decrypt" do expect(user_compliance_info.individual_tax_id.decrypt(nil)).to eq("*encrypted*") end end end describe "has_completed_compliance_info?" do describe "individual" do describe "all fields completed" do let(:user_compliance_info) { create(:user_compliance_info) } it "returns true" do expect(user_compliance_info.has_completed_compliance_info?).to eq(true) end end describe "some fields completed" do let(:user_compliance_info) { create(:user_compliance_info_empty, first_name: "First Name") } it "returns false" do expect(user_compliance_info.has_completed_compliance_info?).to eq(false) end end describe "all fields but individual tax id completed" do let(:user_compliance_info) { create(:user_compliance_info, individual_tax_id: nil) } it "returns false" do expect(user_compliance_info.has_completed_compliance_info?).to eq(false) end end describe "no fields completed" do let(:user_compliance_info) { create(:user_compliance_info_empty) } it "returns false" do expect(user_compliance_info.has_completed_compliance_info?).to eq(false) end end end describe "business" do describe "all fields completed" do let(:user_compliance_info) { create(:user_compliance_info_business) } it "returns true" do expect(user_compliance_info.has_completed_compliance_info?).to eq(true) end end describe "some fields completed" do let(:user_compliance_info) { create(:user_compliance_info_empty, is_business: true, business_name: "My Business") } it "returns false" do expect(user_compliance_info.has_completed_compliance_info?).to eq(false) end end describe "all fields but business tax id completed" do let(:user_compliance_info) { create(:user_compliance_info_business, business_tax_id: nil) } it "returns false" do expect(user_compliance_info.has_completed_compliance_info?).to eq(false) end end describe "no fields completed" do let(:user_compliance_info) { create(:user_compliance_info_empty, is_business: true) } it "returns false" do expect(user_compliance_info.has_completed_compliance_info?).to eq(false) end end end end describe "legal entity fields" do describe "legal_entity_country" do describe "is an individual" do let(:user_compliance_info) { create(:user_compliance_info, country: "Canada") } it "returns the individual country" do expect(user_compliance_info.legal_entity_country).to eq("Canada") end end describe "is a business" do describe "has business_country set" do let(:user_compliance_info) { create(:user_compliance_info_business, country: "Canada", business_country: "United States") } it "returns the individual country" do expect(user_compliance_info.legal_entity_country).to eq("United States") end end describe "does not have business_country set" do let(:user_compliance_info) { create(:user_compliance_info_business, country: "Canada", business_country: nil) } it "returns the individual country" do expect(user_compliance_info.legal_entity_country).to eq("Canada") end end end end describe "legal_entity_country_code" do describe "is an individual" do let(:user_compliance_info) { create(:user_compliance_info, country: "Canada") } it "returns the individual country" do expect(user_compliance_info.legal_entity_country_code).to eq("CA") end end describe "is a business" do describe "has business_country set" do let(:user_compliance_info) { create(:user_compliance_info_business, country: "Canada", business_country: "United States") } it "returns the individual country" do expect(user_compliance_info.legal_entity_country_code).to eq("US") end end describe "does not have business_country set" do let(:user_compliance_info) { create(:user_compliance_info_business, country: "Canada", business_country: nil) } it "returns the individual country" do expect(user_compliance_info.legal_entity_country_code).to eq("CA") end end end end end describe "legal_entity_payable_business_type" do describe "individual" do let(:user_compliance_info) { create(:user_compliance_info) } it "returns INDIVIDUAL type" do expect(user_compliance_info.legal_entity_payable_business_type).to eq("INDIVIDUAL") end end describe "llc" do let(:user_compliance_info) { create(:user_compliance_info_business) } it "returns LLC_PARTNER type" do expect(user_compliance_info.legal_entity_payable_business_type).to eq("LLC_PARTNER") end end describe "corporation" do let(:user_compliance_info) { create(:user_compliance_info_business, business_type: UserComplianceInfo::BusinessTypes::CORPORATION) } it "returns CORPORATION type" do expect(user_compliance_info.legal_entity_payable_business_type).to eq("CORPORATION") end end end describe "#first_and_last_name" do let(:user_compliance_info) { create(:user_compliance_info, first_name: " Alice ", last_name: nil) } it "returns stripped first_name and last_name after converting to strings" do expect(user_compliance_info.first_and_last_name).to eq "Alice" user_compliance_info.last_name = " Smith " expect(user_compliance_info.first_and_last_name).to eq "Alice Smith" end end describe "stripped_fields" do let(:user_compliance_info) { create(:user_compliance_info, first_name: " Alice ", last_name: " Bob ", business_name: " My Business ") } it "strips all fields" do expect(user_compliance_info.first_name).to eq "Alice" expect(user_compliance_info.last_name).to eq "Bob" expect(user_compliance_info.business_name).to eq "My Business" end it "doesn't strip fields for existing records because they are immutable" do user_compliance_info = build(:user_compliance_info, first_name: " Alice ") user_compliance_info.save!(validate: false) expect { user_compliance_info.mark_deleted! }.not_to raise_exception expect(user_compliance_info.first_name).to eq " Alice " expect(user_compliance_info.deleted_at).to_not be_nil end end describe "#has_individual_tax_id?" do describe "when individual_tax_id is present" do let(:user_compliance_info) { create(:user_compliance_info, individual_tax_id: "123456789") } it "returns true" do expect(user_compliance_info.has_individual_tax_id?).to eq(true) end end describe "when individual_tax_id is nil" do let(:user_compliance_info) { create(:user_compliance_info, individual_tax_id: nil) } it "returns false" do expect(user_compliance_info.has_individual_tax_id?).to eq(false) end end end describe "#has_business_tax_id?" do describe "when business_tax_id is present" do let(:user_compliance_info) { create(:user_compliance_info_business, business_tax_id: "98-7654321") } it "returns true" do expect(user_compliance_info.has_business_tax_id?).to eq(true) end end describe "when business_tax_id is nil" do let(:user_compliance_info) { create(:user_compliance_info_business, business_tax_id: nil) } it "returns false" do expect(user_compliance_info.has_business_tax_id?).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/models/third_party_analytic_spec.rb
spec/models/third_party_analytic_spec.rb
# frozen_string_literal: true require "spec_helper" describe ThirdPartyAnalytic do before do @user = create(:user) @product = create(:product, user: @user) end describe "#save_third_party_analytics" do describe "new analytics" do it "creates a new third_party_analytic for creator" do params = [{ name: "Snippet 1", location: "product", product: "#all_products", code: "<span>The first analytics</span>" }] expect(ThirdPartyAnalytic.save_third_party_analytics(params, @user)).to eq([ThirdPartyAnalytic.last.external_id]) expect(@user.third_party_analytics.count).to eq(1) expect(@user.third_party_analytics.first.name).to eq("Snippet 1") expect(@user.third_party_analytics.first.location).to eq("product") expect(@user.third_party_analytics.first.analytics_code).to eq("<span>The first analytics</span>") expect(@product.third_party_analytics.count).to eq(0) end it "creates a new third_party_analytic for product" do params = [{ name: "Snippet 1", location: "product", product: @product.unique_permalink, code: "<span>The first analytics</span>" }] expect(ThirdPartyAnalytic.save_third_party_analytics(params, @user)).to eq([ThirdPartyAnalytic.last.external_id]) expect(@product.third_party_analytics.count).to eq(1) expect(@user.third_party_analytics.first.name).to eq("Snippet 1") expect(@user.third_party_analytics.first.location).to eq("product") expect(@product.third_party_analytics.first.analytics_code).to eq("<span>The first analytics</span>") expect(@user.third_party_analytics.count).to eq(1) end context "when two snippets have the same location" do it "doesn't allow them to belong to the same user" do params = [ { name: "Snippet 1", location: "product", product: "#all_products", code: "<span>The first analytics</span>" }, { name: "Snippet 2", location: "product", product: "#all_products", code: "<span>number 2</span>" } ] expect { ThirdPartyAnalytic.save_third_party_analytics(params, @user) }.to raise_error(ThirdPartyAnalytic::ThirdPartyAnalyticInvalid) expect(ThirdPartyAnalytic.count).to eq(0) end it "doesn't allow them to belong to the same product" do params = [ { name: "Snippet 1", location: "product", product: @product.unique_permalink, code: "<span>The first analytics</span>" }, { name: "Snippet 2", location: "product", product: @product.unique_permalink, code: "<span>number 2</span>" } ] expect { ThirdPartyAnalytic.save_third_party_analytics(params, @user) }.to raise_error(ThirdPartyAnalytic::ThirdPartyAnalyticInvalid) expect(ThirdPartyAnalytic.count).to eq(0) end end context "when two snippets have different locations" do it "allows them to belong to the same user" do params = [ { name: "Snippet 1", location: "product", product: "#all_products", code: "<span>The first analytics</span>" }, { name: "Snippet 2", location: "all", product: "#all_products", code: "<span>number 2</span>" } ] expect(ThirdPartyAnalytic.save_third_party_analytics(params, @user)).to eq [ThirdPartyAnalytic.second_to_last.external_id, ThirdPartyAnalytic.last.external_id] expect(ThirdPartyAnalytic.count).to eq(2) end it "doesn't allow them to belong to the same product" do params = [ { name: "Snippet 1", location: "product", product: @product.unique_permalink, code: "<span>The first analytics</span>" }, { name: "Snippet 2", location: "receipt", product: @product.unique_permalink, code: "<span>number 2</span>" } ] expect(ThirdPartyAnalytic.save_third_party_analytics(params, @user)).to eq [ThirdPartyAnalytic.second_to_last.external_id, ThirdPartyAnalytic.last.external_id] expect(ThirdPartyAnalytic.count).to eq(2) end end end describe "existing analytics" do before do @third_party_analytics = create(:third_party_analytic, user: @user, link: nil) end it "updates the new third_party_analytic for creator" do params = [{ id: @third_party_analytics.external_id, name: "Snippet 1", location: "product", product: "#all_products", code: "HERE COMES THE PARTY" }] expect(ThirdPartyAnalytic.save_third_party_analytics(params, @user)).to eq([@third_party_analytics.external_id]) @third_party_analytics.reload expect(@user.third_party_analytics.count).to eq(1) expect(@third_party_analytics.name).to eq("Snippet 1") expect(@third_party_analytics.location).to eq("product") expect(@third_party_analytics.analytics_code).to eq("HERE COMES THE PARTY") expect(@product.third_party_analytics.count).to eq(0) end it "updates the new third_party_analytic for product" do @third_party_analytics.update_attribute(:link, @product) params = [{ id: @third_party_analytics.external_id, name: "Snippet 1", location: "product", product: @product.unique_permalink, code: "HERE COMES THE PARTY!" }] expect(ThirdPartyAnalytic.save_third_party_analytics(params, @user)).to eq([@third_party_analytics.external_id]) @third_party_analytics.reload expect(@product.third_party_analytics.count).to eq(1) expect(@third_party_analytics.name).to eq("Snippet 1") expect(@third_party_analytics.location).to eq("product") expect(@third_party_analytics.analytics_code).to eq("HERE COMES THE PARTY!") expect(@user.third_party_analytics.count).to eq(1) end it "deletes the users third_party_analytics" do expect(ThirdPartyAnalytic.save_third_party_analytics({}, @user)).to eq([]) expect(@user.third_party_analytics.alive.count).to eq(0) end end end describe "#clear_related_products_cache" do before do create(:product, user: @user) @tpa = create(:third_party_analytic, user: @user, link: @product) end it "calls cache invalidate on all user's links" do expect(@user).to receive(:clear_products_cache).once @tpa.link = nil @tpa.save! end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/installment_rule_spec.rb
spec/models/installment_rule_spec.rb
# frozen_string_literal: true require "spec_helper" describe InstallmentRule do describe "version" do before do @product = create(:product) @post = create(:installment, link: @product, installment_type: "product") @post_rule = create(:installment_rule, installment: @post, to_be_published_at: 1.week.from_now) end it "has the installment_rule starting version be 1" do expect(@post_rule.reload.version).to eq(1) end it "increments the version when to_be_published_at changes" do expect do @post_rule.update(to_be_published_at: 1.month.from_now) end.to change { @post_rule.reload.version }.by(1) expect(@post_rule.reload.version).to eq(2) end it "increments the version if delayed_delivery_time is changed" do expect do @post_rule.delayed_delivery_time = 100 @post_rule.save end.to change { @post_rule.reload.version }.by(1) expect(@post_rule.reload.version).to eq(2) end it "does not increment the version if period is changed" do expect do @post_rule.time_period = "DAY" @post_rule.save end.to_not change { @post_rule.reload.version } end it "does not increment the version if period is changed" do expect do @post_rule.time_period = "DAY" @post_rule.save end.to_not change { @post_rule.reload.version } end end describe "displayable_time_duration" do before do @product = create(:product) @post = create(:installment, link: @product, installment_type: "product") @post_rule = create(:installment_rule, installment: @post, delayed_delivery_time: 1.week, time_period: "week") end it "returns the correct duration based on the time period" do expect(@post_rule.displayable_time_duration).to eq(1) @post_rule.update(delayed_delivery_time: 2.weeks, time_period: "day") expect(@post_rule.displayable_time_duration).to eq(14) @post_rule.update(delayed_delivery_time: 2.hours, time_period: "hour") expect(@post_rule.displayable_time_duration).to eq(2) @post_rule.update(delayed_delivery_time: 1.month, time_period: "month") expect(@post_rule.displayable_time_duration).to eq(1) end end describe "validations" do describe "to_be_published_at_cannot_be_in_the_past" do before do post = create(:post, workflow: create(:audience_workflow)) @post_rule = create(:installment_rule, to_be_published_at: nil, installment: post) end it "allows to_be_published_at to be nil" do expect(@post_rule.to_be_published_at).to be_nil expect(@post_rule).to be_valid end it "disallows to_be_published_at to be in the past" do @post_rule.to_be_published_at = Time.current expect(@post_rule).not_to be_valid expect(@post_rule.errors.full_messages).to include("Please select a date and time in the future.") end context "when about to be marked as deleted" do it "allows to_be_published_at to be in the past" do @post_rule.to_be_published_at = Time.current @post_rule.deleted_at = Time.current expect(@post_rule).to be_valid end end end describe "to_be_published_at_must_exist_for_non_workflow_posts" do it "disallows to_be_published_at to be nil" do post_rule = build(:installment_rule, to_be_published_at: nil) expect(post_rule).not_to be_valid expect(post_rule.errors.full_messages).to include("Please select a date and time in the future.") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/czech_republic_bank_account_spec.rb
spec/models/czech_republic_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe CzechRepublicBankAccount do describe "#bank_account_type" do it "returns CZ" do expect(create(:czech_republic_bank_account).bank_account_type).to eq("CZ") end end describe "#country" do it "returns CZ" do expect(create(:czech_republic_bank_account).country).to eq("CZ") end end describe "#currency" do it "returns czk" do expect(create(:czech_republic_bank_account).currency).to eq("czk") end end describe "#routing_number" do it "returns nil" do expect(create(:czech_republic_bank_account).routing_number).to be nil end end describe "#account_number_visual" do it "returns the visual account number with country code prefixed" do expect(create(:czech_republic_bank_account, account_number_last_four: "3000").account_number_visual).to eq("CZ******3000") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:czech_republic_bank_account)).to be_valid expect(build(:czech_republic_bank_account, account_number: "CZ65 0800 0000 1920 0014 5399")).to be_valid cz_bank_account = build(:czech_republic_bank_account, account_number: "CZ12345") expect(cz_bank_account).to_not be_valid expect(cz_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") cz_bank_account = build(:czech_republic_bank_account, account_number: "DE6508000000192000145399") expect(cz_bank_account).to_not be_valid expect(cz_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") cz_bank_account = build(:czech_republic_bank_account, account_number: "8937040044053201300000") expect(cz_bank_account).to_not be_valid expect(cz_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") cz_bank_account = build(:czech_republic_bank_account, account_number: "CZABCDE") expect(cz_bank_account).to_not be_valid expect(cz_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/variant_category_spec.rb
spec/models/variant_category_spec.rb
# frozen_string_literal: true require "spec_helper" describe VariantCategory do describe "scopes" do describe ".is_tier_category" do it "returns variant categories with title 'Tier'" do create(:variant_category) tier_category = create(:variant_category, title: "Tier") second_tier_category = create(:variant_category, title: "Tier") result = VariantCategory.is_tier_category expect(result).to eq [tier_category, second_tier_category] end end end describe "#has_alive_grouping_variants_with_purchases?" do describe "non-product file grouping category" do before do @variant_category = create(:variant_category, link: create(:product)) end describe "has no variants" do it "returns false" do expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) end end describe "has alive variants" do before do @variant = create(:variant, variant_category: @variant_category) end describe "variants have no purchases" do it "returns false" do expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) end end describe "variants have purchases" do it "returns false" do expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) @purchase = create(:purchase) @purchase.variant_attributes << @variant @purchase.save expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) end end end describe "has dead variants" do before do @variant = create(:variant, variant_category: @variant_category) @variant.deleted_at = Time.current @variant.save end describe "variants have no purchases" do it "returns false" do expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) end end describe "variants have purchases" do it "returns false" do expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) @purchase = create(:purchase) @purchase.variant_attributes << @variant @purchase.save expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) end end end end describe "with associated files" do before do @product = create(:product) @product_file_a = create(:product_file, link: @product) @variant_category = create(:variant_category, link: @product) end describe "has no variants" do it "returns false" do expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) end end describe "has alive variants" do before do @variant = build(:variant, variant_category: @variant_category) @variant.product_files << @product_file_a @variant.save! end describe "variants have no purchases" do it "returns false" do expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) end end describe "variants have successful purchases" do it "returns true" do purchase = create(:purchase, variant_attributes: [@variant]) %w(preorder_authorization_successful successful not_charged gift_receiver_purchase_successful).each do |purchase_state| purchase.update!(purchase_state:) expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq true end end end describe "variants have non-successful or test purchases" do it "returns false" do %w(test_successful failed in_progress preorder_authorization_failed).each do |purchase_state| create(:purchase, variant_attributes: [@variant], purchase_state:) end expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq false end end end describe "has dead variants" do before do @variant = build(:variant, variant_category: @variant_category) @variant.product_files << @product_file_a @variant.save! @variant.deleted_at = Time.current @variant.save end describe "variants have no purchases" do it "returns false" do expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) end end describe "variants have purchases" do it "returns false" do expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) @purchase = create(:purchase) @purchase.variant_attributes << @variant @purchase.save expect(@variant_category.has_alive_grouping_variants_with_purchases?).to eq(false) 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/models/south_africa_bank_account_spec.rb
spec/models/south_africa_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe SouthAfricaBankAccount do describe "#bank_account_type" do it "returns ZA" do expect(create(:south_africa_bank_account).bank_account_type).to eq("ZA") end end describe "#country" do it "returns ZA" do expect(create(:south_africa_bank_account).country).to eq("ZA") end end describe "#currency" do it "returns zar" do expect(create(:south_africa_bank_account).currency).to eq("zar") end end describe "#routing_number" do it "returns valid for 8 characters" do ba = create(:south_africa_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("FIRNZAJJ") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:south_africa_bank_account, account_number_last_four: "1234").account_number_visual).to eq("******1234") end end describe "#validate_bank_code" do it "allows 8 to 11 characters only" do expect(build(:south_africa_bank_account, bank_code: "FIRNZAJJ")).to be_valid expect(build(:south_africa_bank_account, bank_code: "FIRNZAJJXXX")).to be_valid expect(build(:south_africa_bank_account, bank_code: "FIRNZAJ")).not_to be_valid expect(build(:south_africa_bank_account, bank_code: "FIRNZAJJXXXX")).not_to be_valid end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/cart_product_spec.rb
spec/models/cart_product_spec.rb
# frozen_string_literal: true require "spec_helper" describe CartProduct do describe "callbacks" do it "assigns default url parameters after initialization" do cart_product = build(:cart_product) expect(cart_product.url_parameters).to eq({}) end it "assigns accepted offer details after initialization" do cart_product = build(:cart_product) expect(cart_product.accepted_offer_details).to eq({}) end end describe "validations" do describe "url parameters" do context "when url parameters are empty" do it "marks the cart product as valid" do cart_product = build(:cart_product, url_parameters: {}) expect(cart_product).to be_valid end end context "when url parameters is not a hash" do it "marks the cart product as invalid" do cart_product = build(:cart_product, url_parameters: []) expect(cart_product).to be_invalid expect(cart_product.errors.full_messages.join).to include("The property '#/' of type array did not match the following type: object") end end context "when url parameters contain invalid keys" do it "marks the cart product as invalid" do cart_product = build(:cart_product, url_parameters: { "hello" => 123 }) expect(cart_product).to be_invalid expect(cart_product.errors.full_messages.join).to include("The property '#/hello' of type integer did not match the following type: string in schema") end end end describe "accepted offer details" do context "when accepted offer details is empty" do it "marks the cart product as valid" do cart_product = build(:cart_product, accepted_offer_details: {}) expect(cart_product).to be_valid end end context "when accepted offer details is not a hash" do it "marks the cart product as invalid" do cart_product = build(:cart_product, accepted_offer_details: []) expect(cart_product).to be_invalid expect(cart_product.errors.full_messages.join).to include("The property '#/' of type array did not match the following type: object") end end context "when accepted offer details contains invalid keys" do it "marks the cart product as invalid" do cart_product = build(:cart_product, accepted_offer_details: { "hello" => 123 }) expect(cart_product).to be_invalid expect(cart_product.errors.full_messages.join).to include("The property '#/' contains additional properties [\"hello\"] outside of the schema when none are allowed in schema") end end context "allows original_variant_id to be nil" do it "marks the cart product as valid" do cart_product = build(:cart_product, accepted_offer_details: { original_product_id: "123", original_variant_id: nil }) expect(cart_product).to be_valid cart_product = build(:cart_product, accepted_offer_details: { original_product_id: "123", original_variant_id: "456" }) expect(cart_product).to be_valid 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/models/upsell_spec.rb
spec/models/upsell_spec.rb
# frozen_string_literal: true require "spec_helper" describe Upsell do describe "validations" do context "when any products don't belong to the seller" do before do @upsell = build(:upsell, selected_products: [create(:product)]) end it "adds an error" do expect(@upsell.valid?).to eq(false) expect(@upsell.errors.full_messages.first).to eq("All offered products must belong to the current seller.") end end context "when all products belong to the seller" do before do @seller = create(:user) @upsell = build(:upsell, selected_products: [create(:product, user: @seller)], seller: @seller) end it "doesn't add an error" do expect(@upsell.valid?).to eq(true) end end context "when the offered product doesn't belong to the seller" do before do @upsell = build(:upsell, product: create(:product)) end it "adds an error" do expect(@upsell.valid?).to eq(false) expect(@upsell.errors.full_messages.first).to eq("The offered product must belong to the current seller.") end end context "when the offered product belongs to the seller" do before do @seller = create(:user) @upsell = build(:upsell, product: create(:product, user: @seller), seller: @seller) end it "doesn't add an error" do expect(@upsell.valid?).to eq(true) end end context "when the offered product is a call" do before do @seller = create(:user, :eligible_for_service_products) @upsell = build(:upsell, product: create(:call_product, user: @seller), seller: @seller) end it "adds an error" do expect(@upsell.valid?).to eq(false) expect(@upsell.errors.full_messages.first).to eq("Calls cannot be offered as upsells.") end end context "when the offered variant doesn't belong to the the offered product" do before do @upsell = build(:upsell, variant: create(:variant)) end it "adds an error" do expect(@upsell.valid?).to eq(false) expect(@upsell.errors.full_messages.first).to eq("The offered variant must belong to the offered product.") end end context "when the offered variant belongs to the offered product" do before do @seller = create(:user) @product = create(:product, user: @seller) @upsell = build(:upsell, product: @product, variant: create(:variant, variant_category: create(:variant_category, link: @product)), seller: @seller) end it "doesn't add an error" do expect(@upsell.valid?).to eq(true) end end context "when the offer code doesn't belong to the seller and the offered product" do before do @upsell = build(:upsell, offer_code: create(:offer_code)) end it "adds an error" do expect(@upsell.valid?).to eq(false) expect(@upsell.errors.full_messages.first).to eq("The offer code must belong to the seller and the offered product.") end end context "when the offer code belongs to the seller and the offered product" do before do @seller = create(:user) @product = create(:product, user: @seller) @upsell = build(:upsell, product: @product, offer_code: create(:offer_code, user: @seller, products: [@product]), seller: @seller) end it "doesn't add an error" do expect(@upsell.valid?).to eq(true) end end context "when there is more than one upsell variant per selected variant" do before do @seller = create(:user) @product = create(:product, user: @seller) @selected_variant = create(:variant, variant_category: create(:variant_category, link: @product)) @upsell = build(:upsell, seller: @seller, product: @product) create_list(:upsell_variant, 2, upsell: @upsell, selected_variant: @selected_variant) end it "adds an error" do expect(@upsell.valid?).to eq(false) expect(@upsell.errors.full_messages.first).to eq("The upsell cannot have more than one upsell variant per selected variant.") end end context "when there is only one upsell variant per selected variant" do before do @seller = create(:user) @upsell = build(:upsell, seller: @seller) create_list(:upsell_variant, 2, upsell: @upsell) end it "doesn't add an error" do expect(@upsell.valid?).to eq(true) end end context "when there is already an upsell for the product" do before do @seller = create(:user) @product = create(:product, user: @seller) @existing_upsell = create(:upsell, seller: @seller, product: @product) @upsell = build(:upsell, seller: @seller, product: @product) end it "adds an error" do expect(@upsell.valid?).to eq(false) expect(@upsell.errors.full_messages.first).to eq("You can only create one upsell per product.") end context "when `deleted_at` is set for the upsell" do before do @upsell.deleted_at = Time.current end it "doesn't add an error" do expect(@upsell.valid?).to eq(true) end end end context "when there isn't an upsell for the product" do before do @seller = create(:user) @product = create(:product, user: @seller) @existing_cross_sell = create(:upsell, cross_sell: true, seller: @seller, product: @product) @upsell = build(:upsell, seller: @seller, product: @product) end it "doesn't add an error" do expect(@upsell.valid?).to eq(true) end end end describe "#as_json" do let(:seller) { create(:named_seller) } let(:product1) { create(:product_with_digital_versions, user: seller, price_cents: 1000) } let(:product2) { create(:product_with_digital_versions, user: seller, price_cents: 500) } let!(:upsell1) { create(:upsell, product: product1, variant: product1.alive_variants.second, name: "Upsell 1", seller:, cross_sell: true, replace_selected_products: true) } let!(:upsell2) { create(:upsell, product: product2, offer_code: create(:offer_code, products: [product2], user: seller), name: "Upsell 2", seller:) } let!(:upsell2_variant) { create(:upsell_variant, upsell: upsell2, selected_variant: product2.alive_variants.first, offered_variant: product2.alive_variants.second) } before do build_list :product, 5 do |product, i| product.name = "Product #{i}" create_list(:upsell_purchase, 2, upsell: upsell1, selected_product: product) upsell1.selected_products << product end create_list(:upsell_purchase, 20, upsell: upsell2, selected_product: product2, upsell_variant: upsell2_variant) end it "returns the upsell encoded in an object" do expect(upsell1.as_json).to eq( { description: "This offer will only last for a few weeks.", id: upsell1.external_id, name: "Upsell 1", text: "Take advantage of this excellent offer!", cross_sell: true, replace_selected_products: true, universal: false, paused: false, discount: nil, product: { id: product1.external_id, currency_type: "usd", name: "The Works of Edgar Gumstein", variant: { id: product1.alive_variants.second.external_id, name: "Untitled 2" }, }, selected_products: [ { id: upsell1.selected_products[0].external_id, name: "Product 0" }, { id: upsell1.selected_products[1].external_id, name: "Product 1" }, { id: upsell1.selected_products[2].external_id, name: "Product 2" }, { id: upsell1.selected_products[3].external_id, name: "Product 3" }, { id: upsell1.selected_products[4].external_id, name: "Product 4" }, ], upsell_variants: [], }) expect(upsell2.as_json).to eq( { description: "This offer will only last for a few weeks.", id: upsell2.external_id, name: "Upsell 2", text: "Take advantage of this excellent offer!", cross_sell: false, replace_selected_products: false, universal: false, paused: false, discount: { cents: 100, type: "fixed", product_ids: [product2.external_id], expires_at: nil, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, }, product: { id: product2.external_id, currency_type: "usd", name: "The Works of Edgar Gumstein", variant: nil, }, selected_products: [], upsell_variants: [{ id: upsell2_variant.external_id, selected_variant: { id: upsell2_variant.selected_variant.external_id, name: upsell2_variant.selected_variant.name, }, offered_variant: { id: upsell2_variant.offered_variant.external_id, name: upsell2_variant.offered_variant.name, }, }], } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/asset_preview_spec.rb
spec/models/asset_preview_spec.rb
# frozen_string_literal: true require "spec_helper" describe AssetPreview, :vcr do describe "Attachment" do it "scales down a big image and keeps original" do asset_preview = create(:asset_preview) expect(asset_preview.file.url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{asset_preview.file.key}") expect(asset_preview.retina_variant.url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{asset_preview.retina_variant.key}") expect(asset_preview.width).to eq(1633) expect(asset_preview.height).to eq(512) expect(asset_preview.display_width).to eq(670) expect(asset_preview.display_height).to eq(210) expect(asset_preview.retina_width).to eq(1005) end it "does not scale up a smaller image" do asset_preview = create(:asset_preview_jpg) expect(asset_preview.width).to eq(25) expect(asset_preview.height).to eq(25) expect(asset_preview.display_width).to eq(25) expect(asset_preview.display_height).to eq(25) end it "succeeds with video" do asset_preview = create(:asset_preview_mov) expect(asset_preview.url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{asset_preview.file.key}") end it "doesn't post process GIFs and keeps the original" do asset_preview = create(:asset_preview_gif) expect(asset_preview.url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{asset_preview.file.key}") expect(asset_preview.display_width).to eq(670) expect(asset_preview.display_height).to eq(500) expect(asset_preview.retina_width).to eq(670) end it "fails with an arbitrary filetype" do asset_preview = create(:asset_preview) asset_preview.file.attach Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "test.zip"), "application/octet-stream") expect(asset_preview.save).to eq(false) expect(asset_preview.errors.full_messages).to eq(["Could not process your preview, please try again."]) end describe "#analyze_file" do it "fails with a video which cannot be analyzed" do asset_preview = create(:asset_preview) blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("invalid_asset_preview_video.MOV"), filename: "invalid_asset_preview_video.MOV", content_type: "video/quicktime") blob.analyze asset_preview.file.attach(blob) expect(asset_preview.save).to eq(false) expect(asset_preview.errors.full_messages).to include("Could not analyze cover. Please check the uploaded file.") end it "fails with a script disguised as an image" do asset_preview = create(:asset_preview) blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("disguised_html_script.png"), filename: "disguised_html_script.png", content_type: "image/png") blob.analyze asset_preview.file.attach(blob) expect(asset_preview.save).to eq(false) expect(asset_preview.errors.full_messages).to include("Could not process your preview, please try again.") end it "fails with an image which cannot be analyzed" do asset_preview = create(:asset_preview) blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("invalid_asset_preview_image.jpeg"), filename: "invalid_asset_preview_image.jpeg", content_type: "image/jpeg") blob.analyze asset_preview.file.attach(blob) expect(asset_preview.save).to eq(false) expect(asset_preview.errors.full_messages).to include("Could not analyze cover. Please check the uploaded file.") end end it "does not allow unsupported image formats" do asset_preview = create(:asset_preview) asset_preview.file.attach(Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "webp_image.webp"), "image/webp")) expect(asset_preview.save).to eq(false) expect(asset_preview.errors.full_messages).to eq(["Could not process your preview, please try again."]) end context "deleted" do it "allows marking deleted existing records with unsupported image formats " do asset_preview = create(:asset_preview) asset_preview.file.attach(Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "webp_image.webp"), "image/webp")) asset_preview.save(validate: false) asset_preview.reload asset_preview.mark_deleted! expect(asset_preview.reload).to be_deleted end end end describe "Embeddable link" do it "succeeds with a video URL" do asset_preview = create(:asset_preview, url: "https://www.youtube.com/watch?v=huKYieB4evw") expect(asset_preview.display_type).to eq("oembed") expect(asset_preview.url).to eq("https://www.youtube.com/embed/huKYieB4evw?feature=oembed&showinfo=0&controls=0&rel=0&enablejsapi=1") expect(asset_preview.oembed_thumbnail_url).to eq("https://i.ytimg.com/vi/huKYieB4evw/hqdefault.jpg") end it "succeeds with a sound URL" do asset_preview = create(:asset_preview, url: "https://soundcloud.com/user-656397481/tbl31-here-comes-the-new-year") expect(asset_preview.display_type).to eq("oembed") expect(asset_preview.oembed_url).to eq("https://w.soundcloud.com/player/?visual=true&url=https%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F376574774&auto_play=false&show_artwork=false&show_comments=false&buying=false&sharing=false&download=false&show_playcount=false&show_user=false&liking=false&maxwidth=670") expect(asset_preview.oembed_thumbnail_url).to match("https://i1.sndcdn.com/artworks-000278260091-nbg7dg-t500x500.jpg") end it "fails with a dodgy URL and keeps attachment" do expect do expect do asset_preview = AssetPreview.new(link: create(:product)) asset_preview.url = "https://www.nsa.gov" asset_preview.save! end.to raise_error(ActiveRecord::RecordInvalid) end.to_not change { AssetPreview.count } end it "fails when oembed has no width or height" do expect do expect(OEmbedFinder).to receive(:embeddable_from_url) .and_return({ html: "<iframe src=\"https://madeup.url\"></iframe>", info: { "thumbnail_url" => "https://madeup.thumbnail.url" } }) allow_any_instance_of(ActiveStorage::Blob).to receive(:purge).and_return(nil) asset_preview = create(:asset_preview) asset_preview.url = "https://madeup.url" asset_preview.save! end.to raise_error(ActiveRecord::RecordInvalid, "Validation failed: Could not analyze cover. Please check the uploaded file.") end it "fails if URL is not of a supported provider" do expect do create(:asset_preview, url: "https://www.tiktok.com/@soflofooodie/video/7164885074863787307") end.to raise_error(ActiveRecord::RecordInvalid, "Validation failed: A URL from an unsupported platform was provided. Please try again.") end end describe "#url=" do let(:asset_preview) { create(:asset_preview) } it "works as expected with a public URL" do expect do asset_preview.url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test.png" asset_preview.analyze_file asset_preview.save! end.to_not raise_error expect(asset_preview.file.url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{asset_preview.file.key}") expect(asset_preview.retina_variant.url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{asset_preview.retina_variant.key}") end it "works as expected when a URL with square brackets is encoded and passed as an argument" do expect do asset_preview.url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test-small+with+%5Bsquare+brackets%5D.jpg" asset_preview.analyze_file asset_preview.save! end.to_not raise_error expect(asset_preview.file.url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{asset_preview.file.key}") expect(asset_preview.retina_variant.url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{asset_preview.retina_variant.key}") end it "prevents non-http urls from being downloaded" do expect do asset_preview.url = "/etc/sudoers" end.to raise_error(URI::InvalidURIError, /not a web url/) end it "blocks SSRF attempts to localhost", :skip_ssrf_stub do expect do asset_preview.url = "http://127.0.0.1:6379/" asset_preview.save! end.to raise_error(SsrfFilter::PrivateIPAddress) end it "blocks SSRF attempts to cloud metadata endpoint", :skip_ssrf_stub do expect do asset_preview.url = "http://169.254.169.254/latest/meta-data/" asset_preview.save! end.to raise_error(SsrfFilter::PrivateIPAddress) end it "blocks SSRF attempts to private IP ranges", :skip_ssrf_stub do expect do asset_preview.url = "http://192.168.1.1/" asset_preview.save! end.to raise_error(SsrfFilter::PrivateIPAddress) end end it "auto-generates a GUID on creation" do asset_preview = create(:asset_preview) expect(asset_preview.guid).to be_present end it "does not auto-generate a GUID on creation if one is supplied" do guid = "a" * 32 # Same length as one generated by `SecureRandom.hex` asset_preview = create(:asset_preview, guid:) expect(asset_preview.guid).to be_present expect(asset_preview.guid).to eq(guid) end describe "product update on save" do it "updates the updated_at timestamp of the product after creating asset_preview" do product = create(:product, updated_at: 1.month.ago) travel_to(Time.current) do expect do create(:asset_preview, link: product) end.to change { product.updated_at }.to(Time.current) end end end describe "position" do it "auto-increments position on creation" do product = create(:product) a = create(:asset_preview, link: product) expect(a.position).to eq 0 b = create(:asset_preview, link: product) expect(b.position).to eq 1 c = create(:asset_preview, link: product) expect(c.position).to eq 2 b.mark_deleted! d = create(:asset_preview, link: product) expect(d.position).to eq 3 end it "properly sets position on creation if the previous preview is missing position" do product = create(:product) pre_existing = create(:asset_preview, link: product) pre_existing.position = nil pre_existing.save! a = create(:asset_preview, link: product) expect(a.position).to eq 1 b = create(:asset_preview, link: product) expect(b.position).to eq 2 end end describe "file attachment" do let!(:asset_preview) { create(:asset_preview) } context "with file attached" do it "returns proper width" do expect(asset_preview.width).to eq(1633) expect(asset_preview.display_width).to eq(670) expect(asset_preview.retina_width).to eq(1005) end it "returns proper height" do expect(asset_preview.height).to eq(512) expect(asset_preview.display_height).to eq(210) end describe "#url" do it "returns retina variant" do expect(asset_preview.url).to match(asset_preview.retina_variant.key) end it "returns original file for non-image files" do asset_preview.file.attach(Rack::Test::UploadedFile.new( Rails.root.join("spec", "support", "fixtures", "sample.gif"), "image/gif")) asset_preview.save! asset_preview.file.analyze expect(asset_preview.url).to match(asset_preview.file.url) end it "works well with video types" do asset_preview.file.attach(Rack::Test::UploadedFile.new( Rails.root.join("spec", "support", "fixtures", "thing.mov"), "video/quicktime")) asset_preview.save! asset_preview.file.analyze expect(asset_preview.url).to match(asset_preview.file.url) end end end end describe "callbacks" do describe "#reset_moderated_by_iffy_flag" do let(:product) { create(:product, moderated_by_iffy: true) } let(:asset_preview) { create(:asset_preview, link: product) } context "when a new asset preview is created" do it "resets moderated_by_iffy flag on the associated product" do expect do create(:asset_preview, link: product) end.to change { product.reload.moderated_by_iffy }.from(true).to(false) end end end end describe "#image_url?" do it "returns true for image assets" do image = create(:asset_preview_jpg) expect(image.image_url?).to eq(true) video = create(:asset_preview_mov) expect(video.image_url?).to eq(false) end end shared_examples "rejects unsafe URLs" do |method, url_key| let(:asset_preview) { build(:asset_preview) } let(:dangerous_urls) do [ "javascript:alert('xss')", "data:text/html,<script>alert('xss')</script>", "vbscript:msgbox('xss')", "file:///etc/passwd", " javascript:alert('xss')", # Leading whitespace "JavaScript:alert('xss')", # Mixed case "\njavascript:alert('xss')" # Leading newline ] end it "returns nil for dangerous URLs" do dangerous_urls.each do |url| if method == :oembed_thumbnail_url asset_preview.oembed = { "info" => { url_key => url } } else asset_preview.oembed = { "html" => "<iframe src=\"#{url}\"></iframe>" } end expect(asset_preview.public_send(method)).to be_nil, "Expected #{url} to be rejected" end end end describe "#oembed_thumbnail_url" do let(:asset_preview) { build(:asset_preview) } it "returns nil when oembed is not present" do expect(asset_preview.oembed_thumbnail_url).to be_nil end it "returns nil for blank thumbnail URLs" do ["", " "].each do |blank_url| asset_preview.oembed = { "info" => { "thumbnail_url" => blank_url } } expect(asset_preview.oembed_thumbnail_url).to be_nil end end include_examples "rejects unsafe URLs", :oembed_thumbnail_url, "thumbnail_url" it "returns safe thumbnail URLs unchanged" do url = "https://example.com/thumb.jpg" asset_preview.oembed = { "info" => { "thumbnail_url" => url } } expect(asset_preview.oembed_thumbnail_url).to eq(url) end end describe "#oembed_url" do let(:asset_preview) { build(:asset_preview) } it "returns nil when oembed is not present or has no iframe" do expect(asset_preview.oembed_url).to be_nil asset_preview.oembed = { "html" => "<div>No iframe here</div>" } expect(asset_preview.oembed_url).to be_nil end include_examples "rejects unsafe URLs", :oembed_url, "src" it "handles protocol-relative and absolute URLs" do { "//example.com/embed" => "https://example.com/embed", "https://example.com/embed" => "https://example.com/embed" }.each do |input, expected| asset_preview.oembed = { "html" => "<iframe src=\"#{input}\"></iframe>" } expect(asset_preview.oembed_url).to eq(expected) end end it "adds platform-specific parameters" do { "https://youtube.com/embed/123?feature=oembed" => "&enablejsapi=1", "https://vimeo.com/video/123" => "?api=1" }.each do |url, param| asset_preview.oembed = { "html" => "<iframe src=\"#{url}\"></iframe>" } expect(asset_preview.oembed_url).to eq(url + param) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/utm_link_spec.rb
spec/models/utm_link_spec.rb
# frozen_string_literal: true require "spec_helper" describe UtmLink do describe "associations" do it { is_expected.to belong_to(:seller).class_name("User").optional(false) } it { is_expected.to belong_to(:target_resource).optional(true) } it { is_expected.to have_many(:utm_link_visits).dependent(:destroy) } it { is_expected.to have_many(:utm_link_driven_sales).dependent(:destroy) } it { is_expected.to have_many(:purchases).through(:utm_link_driven_sales) } it { is_expected.to have_many(:successful_purchases).through(:utm_link_driven_sales) } describe "successful_purchases" do let(:seller) { create(:user) } subject(:utm_link) { create(:utm_link, seller:) } let(:product) { create(:product, user: seller) } let(:purchase1) { create(:purchase, price_cents: 1000, seller:, link: product) } let(:purchase2) { create(:purchase, price_cents: 2000, seller:, link: product) } let(:test_purchase) { create(:test_purchase, price_cents: 3000, seller:, link: product) } let(:failed_purchase) { create(:failed_purchase, price_cents: 1000, seller:, link: product) } let!(:utm_link_driven_sale1) { create(:utm_link_driven_sale, utm_link: subject, purchase: purchase1) } let!(:utm_link_driven_sale2) { create(:utm_link_driven_sale, utm_link: subject, purchase: purchase2) } let!(:utm_link_driven_sale3) { create(:utm_link_driven_sale, utm_link: subject, purchase: test_purchase) } let!(:utm_link_driven_sale4) { create(:utm_link_driven_sale, utm_link: subject, purchase: failed_purchase) } it "returns successful purchases" do expect(subject.successful_purchases).to eq([purchase1, purchase2]) end end end describe "validations" do it { is_expected.to be_versioned } it { is_expected.to validate_presence_of(:title) } it { is_expected.to define_enum_for(:target_resource_type) .with_values(profile_page: "profile_page", subscribe_page: "subscribe_page", product_page: "product_page", post_page: "post_page") .backed_by_column_of_type(:string) .with_prefix(:target) } describe "target_resource_id" do context "when target_resource_type is product_page" do subject(:utm_link) { build(:utm_link, target_resource_type: :product_page) } it "is invalid when absent" do expect(subject).to be_invalid expect(subject.errors[:target_resource_id]).to include("can't be blank") end it "is valid when present" do subject.target_resource_id = create(:product).id expect(subject).to be_valid end end context "when target_resource_type is post_page" do subject(:utm_link) { build(:utm_link, target_resource_type: :post_page) } it "is invalid when absent" do expect(subject).to be_invalid expect(subject.errors[:target_resource_id]).to include("can't be blank") end it "is valid when present" do subject.target_resource_id = create(:post).id expect(subject).to be_valid end end context "when target_resource_type is profile_page" do subject(:utm_link) { build(:utm_link, target_resource_type: :profile_page) } it "is valid" do expect(subject).to be_valid end end context "when target_resource_type is subscribe_page" do subject(:utm_link) { build(:utm_link, target_resource_type: :subscribe_page) } it "is valid when absent" do expect(subject).to be_valid end end end context "permalink" do subject(:utm_link) { build(:utm_link, permalink: "existing") } it { is_expected.to validate_uniqueness_of(:permalink).case_insensitive } it { is_expected.to allow_value("existin1").for(:permalink) } it { is_expected.not_to allow_value("long-val-with-$ymbols").for(:permalink) } end it { is_expected.to validate_presence_of(:utm_campaign) } it { is_expected.to validate_length_of(:utm_campaign).is_at_most(UtmLink::MAX_UTM_PARAM_LENGTH) } it { is_expected.to validate_presence_of(:utm_medium) } it { is_expected.to validate_length_of(:utm_medium).is_at_most(UtmLink::MAX_UTM_PARAM_LENGTH) } it { is_expected.to validate_presence_of(:utm_source) } it { is_expected.to validate_length_of(:utm_source).is_at_most(UtmLink::MAX_UTM_PARAM_LENGTH) } it { is_expected.to validate_length_of(:utm_term).is_at_most(UtmLink::MAX_UTM_PARAM_LENGTH) } it { is_expected.to validate_length_of(:utm_content).is_at_most(UtmLink::MAX_UTM_PARAM_LENGTH) } describe "last_click_at_is_same_or_after_first_click_at" do context "when last_click_at is not present" do it "is valid" do utm_link = build(:utm_link, last_click_at: nil) expect(utm_link).to be_valid end end context "when last_click_at is present" do it "is invalid if first_click_at is nil" do utm_link = build(:utm_link, first_click_at: nil, last_click_at: 3.days.ago) expect(utm_link).to be_invalid expect(utm_link.errors[:last_click_at]).to include("must be same or after the first click at") end it "is invalid if last_click_at is before first_click_at" do utm_link = build(:utm_link, first_click_at: 2.days.ago, last_click_at: 3.days.ago) expect(utm_link).to be_invalid expect(utm_link.errors[:last_click_at]).to include("must be same or after the first click at") end it "is valid if last_click_at is same as first_click_at" do first_click_at = 2.days.ago utm_link = build(:utm_link, first_click_at:, last_click_at: first_click_at) expect(utm_link).to be_valid end it "is valid if last_click_at is after first_click_at" do utm_link = build(:utm_link, first_click_at: 2.days.ago, last_click_at: 1.day.ago) expect(utm_link).to be_valid end end end describe "utm_fields_are_unique" do let(:seller) { create(:user) } let!(:product) { create(:product, user: seller) } it "prevents duplicate UTM parameters for the same target resource and seller" do create(:utm_link, seller:, target_resource_type: "product_page", target_resource_id: product.id, utm_source: "facebook", utm_medium: "social", utm_campaign: "spring", utm_term: "sale", utm_content: "banner", ) duplicate = build(:utm_link, seller:, utm_source: "facebook", utm_medium: "social", utm_campaign: "spring", utm_term: "sale", utm_content: "banner", target_resource_type: "product_page", target_resource_id: product.id ) expect(duplicate).not_to be_valid expect(duplicate.errors[:target_resource_id]).to include("A link with similar UTM parameters already exists for this destination!") end it "allows same UTM parameters for different target resources of the same seller" do create(:utm_link, seller:, target_resource_type: "product_page", target_resource_id: product.id, utm_source: "facebook", utm_medium: "social", utm_campaign: "spring", utm_term: "sale", utm_content: "banner" ) duplicate_with_different_target_resource = build(:utm_link, seller:, target_resource_type: "profile_page", target_resource_id: nil, utm_source: "facebook", utm_medium: "social", utm_campaign: "spring", utm_term: "sale", utm_content: "banner" ) expect(duplicate_with_different_target_resource).to be_valid end it "allows duplicate UTM parameters for the same target resource for different sellers" do create(:utm_link, seller:, target_resource_type: "product_page", target_resource_id: product.id, utm_source: "facebook", utm_medium: "social", utm_campaign: "spring", utm_term: "sale", utm_content: "banner" ) duplicate_for_other_seller = build(:utm_link, seller: create(:user), target_resource_type: "product_page", target_resource_id: product.id, utm_source: "facebook", utm_medium: "social", utm_campaign: "spring", utm_term: "sale", utm_content: "banner" ) expect(duplicate_for_other_seller).to be_valid end it "allows duplicate UTM parameters if original is deleted" do create(:utm_link, seller:, target_resource_type: "product_page", target_resource_id: product.id, utm_source: "facebook", utm_medium: "social", utm_campaign: "spring", utm_term: "sale", utm_content: "banner", deleted_at: Time.current ) duplicate = build(:utm_link, seller:, target_resource_type: "product_page", target_resource_id: product.id, utm_source: "facebook", utm_medium: "social", utm_campaign: "spring", utm_term: "sale", utm_content: "banner" ) expect(duplicate).to be_valid end it "allows updating a UTM link without triggering UTM parameters' uniqueness validation" do utm_link = create(:utm_link, seller:, target_resource_type: "product_page", target_resource_id: product.id, utm_source: "facebook", utm_medium: "social", utm_campaign: "spring" ) utm_link.title = "Updated Title" expect(utm_link).to be_valid expect(utm_link.save).to be(true) end end end describe "scopes" do describe "enabled" do it "returns only enabled utm links" do enabled_link = create(:utm_link) create(:utm_link, disabled_at: Time.current) expect(described_class.enabled).to eq([enabled_link]) end end describe "active" do it "returns only alive and enabled utm links" do active_link = create(:utm_link) create(:utm_link, disabled_at: Time.current) create(:utm_link, deleted_at: Time.current) expect(described_class.active).to eq([active_link]) end end end describe "callbacks" do describe "#set_permalink" do it "sets the permalink before validation" do utm_link = build(:utm_link) utm_link.valid? expect(utm_link.permalink).to be_present end it "does not set the permalink if it is already set" do utm_link = create(:utm_link) utm_link.permalink = "existing-permalink" utm_link.valid? expect(utm_link.permalink).to eq("existing-permalink") end end end describe "#enabled?" do it "returns true when utm link is not disabled" do expect(create(:utm_link)).to be_enabled end it "returns false when utm link is disabled" do expect(create(:utm_link, disabled_at: Time.current)).not_to be_enabled end end describe "#active?" do it "returns true when utm link is enabled and not deleted" do expect(create(:utm_link)).to be_active end it "returns false when utm link is disabled" do expect(create(:utm_link, disabled_at: Time.current)).not_to be_active end it "returns false when utm link is deleted" do expect(create(:utm_link, deleted_at: Time.current)).not_to be_active end end describe "#mark_disabled!" do it "marks the utm link as disabled" do utm_link = create(:utm_link) utm_link.mark_disabled! expect(utm_link.disabled_at).to be_within(2.second).of(Time.current) expect(utm_link).not_to be_enabled end end describe "#mark_enabled!" do it "marks the utm link as enabled" do utm_link = create(:utm_link, disabled_at: Time.current) utm_link.mark_enabled! expect(utm_link).to be_enabled end end describe "#short_url" do it "returns the short URL" do utm_link = create(:utm_link) expect(utm_link.short_url).to eq("#{UrlService.short_domain_with_protocol}/u/#{utm_link.permalink}") end end describe "#utm_url" do context "when target_resource_type is profile_page" do it "returns the seller's profile URL with UTM parameters" do utm_link = create(:utm_link, target_resource_type: :profile_page, utm_term: "hello", utm_content: "world") expect(utm_link.utm_url).to eq("#{utm_link.seller.profile_url}?utm_campaign=#{utm_link.utm_campaign}&utm_content=#{utm_link.utm_content}&utm_medium=#{utm_link.utm_medium}&utm_source=#{utm_link.utm_source}&utm_term=#{utm_link.utm_term}") end end context "when target_resource_type is subscribe_page" do it "returns the seller's profile URL with UTM parameters" do utm_link = create(:utm_link, target_resource_type: :subscribe_page) expect(utm_link.utm_url).to eq("#{Rails.application.routes.url_helpers.custom_domain_subscribe_url(host: utm_link.seller.subdomain_with_protocol)}?utm_campaign=#{utm_link.utm_campaign}&utm_medium=#{utm_link.utm_medium}&utm_source=#{utm_link.utm_source}") end end context "when target_resource_type is product_page" do it "returns the product's long URL with UTM parameters" do product = create(:product) utm_link = create(:utm_link, target_resource_type: :product_page, target_resource_id: product.id, seller: product.user) expect(utm_link.utm_url).to eq("#{product.long_url}?utm_campaign=#{utm_link.utm_campaign}&utm_medium=#{utm_link.utm_medium}&utm_source=#{utm_link.utm_source}") end end context "when target_resource_type is post_page" do it "returns the post's full URL with UTM parameters" do post = create(:audience_post) utm_link = create(:utm_link, target_resource_type: :post_page, target_resource_id: post.id, seller: post.seller) expect(utm_link.utm_url).to eq("#{post.full_url}?utm_campaign=#{utm_link.utm_campaign}&utm_medium=#{utm_link.utm_medium}&utm_source=#{utm_link.utm_source}") end end end describe "#target_resource" do it "returns correct target resource" do seller = create(:user) product = create(:product, user: seller) utm_link = create(:utm_link, target_resource_type: :product_page, target_resource_id: product.id, seller:) expect(utm_link.target_resource).to eq(product) post = create(:audience_post, seller:) utm_link = create(:utm_link, target_resource_type: :post_page, target_resource_id: post.id, seller:) expect(utm_link.target_resource).to eq(post) utm_link = create(:utm_link, target_resource_type: :profile_page, seller:) expect(utm_link.target_resource).to be_nil utm_link = create(:utm_link, target_resource_type: :subscribe_page, seller:) expect(utm_link.target_resource).to be_nil end end describe "#default_title" do context "when target is product page" do let(:product) { create(:product, name: "My Product") } let(:utm_link) { build(:utm_link, target_resource_type: :product_page, target_resource_id: product.id) } it "returns appropriate title" do expect(utm_link.default_title).to eq("Product — My Product (auto-generated)") end end context "when target is post page" do let(:post) { create(:installment, name: "My Post") } let(:utm_link) { build(:utm_link, target_resource_type: :post_page, target_resource_id: post.id) } it "returns appropriate title" do expect(utm_link.default_title).to eq("Post — My Post (auto-generated)") end end context "when target is profile page" do let(:utm_link) { build(:utm_link) } it "returns appropriate title" do expect(utm_link.default_title).to eq("Profile page (auto-generated)") end end context "when target is subscribe page" do let(:utm_link) { build(:utm_link, target_resource_type: :subscribe_page) } it "returns appropriate title" do expect(utm_link.default_title).to eq("Subscribe page (auto-generated)") end end end describe ".generate_permalink" do it "generates an 8-character alphanumeric permalink" do permalink = described_class.generate_permalink expect(permalink).to match(/^[a-z0-9]{8}$/) end it "generates unique permalinks" do existing_permalink = described_class.generate_permalink create(:utm_link, permalink: existing_permalink) new_permalink = described_class.generate_permalink expect(new_permalink).not_to eq(existing_permalink) end it "retries until finding a unique permalink" do # Force the first two attempts to generate existing permalinks allow(SecureRandom).to receive(:alphanumeric).and_return( "existin1", "existin2", "unique12" ) create(:utm_link, permalink: "existin1") create(:utm_link, permalink: "existin2") expect(described_class.generate_permalink).to eq("unique12") expect(SecureRandom).to have_received(:alphanumeric).exactly(3).times end it "raises an error after max retries" do allow(SecureRandom).to receive(:alphanumeric).and_return("existing") create(:utm_link, permalink: "existing") expect do described_class.generate_permalink(max_retries: 3) end.to raise_error("Failed to generate unique permalink after 3 attempts") expect(SecureRandom).to have_received(:alphanumeric).exactly(3).times end end describe ".polymorphic_class_for" do context "when target_resource_type is product_page" do it "returns Link" do expect(described_class.polymorphic_class_for("product_page")).to eq(Link) end end context "when target_resource_type is post_page" do it "returns Installment" do expect(described_class.polymorphic_class_for(:post_page)).to eq(Installment) end end context "when target_resource_type is profile_page" do it "returns nil" do expect(described_class.polymorphic_class_for(:profile_page)).to be_nil end end context "when target_resource_type is subscribe_page" do it "returns nil" do expect(described_class.polymorphic_class_for(:subscribe_page)).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/models/malaysia_bank_account_spec.rb
spec/models/malaysia_bank_account_spec.rb
# frozen_string_literal: true describe MalaysiaBankAccount do describe "#bank_account_type" do it "returns MY" do expect(create(:malaysia_bank_account).bank_account_type).to eq("MY") end end describe "#country" do it "returns MY" do expect(create(:malaysia_bank_account).country).to eq("MY") end end describe "#currency" do it "returns myr" do expect(create(:malaysia_bank_account).currency).to eq("myr") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:malaysia_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("HBMBMYKL") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:malaysia_bank_account, account_number_last_four: "6000").account_number_visual).to eq("******6000") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:malaysia_bank_account)).to be_valid expect(build(:malaysia_bank_account, account_number: "00012345678910111")).to be_valid expect(build(:malaysia_bank_account, account_number: "00012")).to be_valid ma_bank_account = build(:malaysia_bank_account, account_number: "MA123") expect(ma_bank_account).to_not be_valid expect(ma_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ma_bank_account = build(:malaysia_bank_account, account_number: "MY123456789101112") expect(ma_bank_account).to_not be_valid expect(ma_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ma_bank_account = build(:malaysia_bank_account, account_number: "000123456789101112") expect(ma_bank_account).to_not be_valid expect(ma_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ma_bank_account = build(:malaysia_bank_account, account_number: "CRABC") expect(ma_bank_account).to_not be_valid expect(ma_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/subtitle_file_spec.rb
spec/models/subtitle_file_spec.rb
# frozen_string_literal: true require "spec_helper" describe SubtitleFile do describe "validations" do describe "file types" do shared_examples "common invalid type behavior" do |file_type:| before do @subtitle = build(:subtitle_file, url: "subtitle.#{file_type}") end it "is invalid" do expect(@subtitle).not_to be_valid end it "does not save the record" do expect do @subtitle.save end.not_to change { SubtitleFile.count } end it "displays an unsupported file type error message" do @subtitle.save expect(@subtitle.errors.full_messages[0]).to include("Subtitle type not supported.") end end shared_examples "common valid type behavior" do |file_type:| before do @subtitle = build(:subtitle_file, url: "subtitle.#{file_type}") end it "is valid" do expect(@subtitle).to be_valid end it "saves the record" do expect do @subtitle.save end.to change { SubtitleFile.count }.by(1) end end context "when uploading an invalid type" do include_examples "common invalid type behavior", file_type: "txt" include_examples "common invalid type behavior", file_type: "mov" include_examples "common invalid type behavior", file_type: "mp4" include_examples "common invalid type behavior", file_type: "mp3" context "and subtitle is an S3 URL" do before do @subtitle = build(:subtitle_file, url: "#{AWS_S3_ENDPOINT}/gumroad/attachments/1234/abcdef/original/My Awesome Youtube video.mov") end it "is invalid" do expect(@subtitle).not_to be_valid end end end context "when uploading a valid type" do include_examples "common valid type behavior", file_type: "srt" include_examples "common valid type behavior", file_type: "sub" include_examples "common valid type behavior", file_type: "sbv" include_examples "common valid type behavior", file_type: "vtt" context "and subtitle is an S3 URL" do before do @subtitle = build(:subtitle_file, url: "#{AWS_S3_ENDPOINT}/gumroad/attachments/1234/abcdef/original/My Subtitle.sub") end it "is valid" do expect(@subtitle).to be_valid end end end context "when updating an invalid type" do before do @subtitle = build(:subtitle_file, url: "subtitle.pdf") @subtitle.save!(validate: false) end it "is invalid" do @subtitle.url = "subtitle.txt" expect(@subtitle.save).to eq(false) expect(@subtitle.errors.full_messages[0]).to include("Subtitle type not supported.") end end end end describe "#has_alive_duplicate_files?" do let!(:file_1) { create(:subtitle_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/some-file.srt") } let!(:file_2) { create(:subtitle_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/some-file.srt") } it "returns true if there's an alive record with the same url" do file_1.mark_deleted file_1.save! expect(file_1.has_alive_duplicate_files?).to eq(true) expect(file_2.has_alive_duplicate_files?).to eq(true) end it "returns false if there's no other alive record with the same url" do file_1.mark_deleted file_1.save! file_2.mark_deleted file_2.save! expect(file_1.has_alive_duplicate_files?).to eq(false) expect(file_2.has_alive_duplicate_files?).to eq(false) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/dropbox_file_spec.rb
spec/models/dropbox_file_spec.rb
# frozen_string_literal: true require "spec_helper" describe DropboxFile do describe "validations" do it "does not allow you to create a dropbox file without a dropbox url" do dropbox_file = DropboxFile.new(dropbox_url: nil) expect(dropbox_file.valid?).to eq false end end describe "#multipart_transfer_to_s3", :vcr do let(:dropbox_file_info) do file = HTTParty.post("https://api.dropboxapi.com/2/files/get_temporary_link", headers: { "Authorization" => "Bearer #{GlobalConfig.get("DROPBOX_API_KEY")}", "Content-Type" => "application/json" }, body: { path: "/db_upload_testing/Download-Card.pdf" }.to_json) { link: file["link"], name: file["metadata"]["name"], size: file["metadata"]["size"], content_type: "application/pdf" } end it "copies the file from Dropbox to S3" do filename = dropbox_file_info[:name] dropbox_url = dropbox_file_info[:link] content_type = dropbox_file_info[:content_type] content_length = dropbox_file_info[:size] allow_any_instance_of(DropboxFile).to receive(:fetch_content_type).and_return(content_type) s3_guid = "db" + (SecureRandom.uuid.split("")[1..-1] - ["-"]).join create(:dropbox_file, dropbox_url:).multipart_transfer_to_s3(filename, s3_guid) s3_object = Aws::S3::Resource.new.bucket(S3_BUCKET).object("attachments/#{s3_guid}/original/#{filename}") expect(s3_object.content_type).to eq content_type expect(s3_object.content_length).to eq content_length end end describe "callbacks" do describe "#schedule_dropbox_file_analyze" do it "enqueues the job to transfer the file to S3" do create(:dropbox_file) expect(TransferDropboxFileToS3Worker).to have_enqueued_sidekiq_job(kind_of(Integer)) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/legacy_permalink_spec.rb
spec/models/legacy_permalink_spec.rb
# frozen_string_literal: true require "spec_helper" describe LegacyPermalink do describe "validations" do describe "product" do it "must be present" do expect(build(:legacy_permalink, product: nil)).to_not be_valid end end describe "permalink" do it "must be present" do expect(build(:legacy_permalink, permalink: nil)).to_not be_valid expect(build(:legacy_permalink, permalink: "")).to_not be_valid end it "may contain letters" do expect(build(:legacy_permalink, permalink: "abcd")).to be_valid end it "may contain numbers" do expect(build(:legacy_permalink, permalink: "1234")).to be_valid end it "may contain underscores" do expect(build(:legacy_permalink, permalink: "_").valid?).to be(true) end it "may contain dashes" do expect(build(:legacy_permalink, permalink: "-").valid?).to be(true) end it "may not contain illegal characters" do expect(build(:legacy_permalink, permalink: ".&*!")).to_not be_valid end it "must be unique in a case-insensitive way" do create(:legacy_permalink, permalink: "custom") expect(build(:legacy_permalink, permalink: "custom")).to_not be_valid expect(build(:legacy_permalink, permalink: "CUSTOM")).to_not be_valid end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/paraguay_bank_account_spec.rb
spec/models/paraguay_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe ParaguayBankAccount do describe "#bank_account_type" do it "returns PY" do expect(create(:paraguay_bank_account).bank_account_type).to eq("PY") end end describe "#country" do it "returns PY" do expect(create(:paraguay_bank_account).country).to eq("PY") end end describe "#currency" do it "returns pyg" do expect(create(:paraguay_bank_account).currency).to eq("pyg") end end describe "#bank_code" do it "returns valid for 1 to 2 characters" do expect(create(:paraguay_bank_account, bank_code: "12")).to be_valid expect(create(:paraguay_bank_account, bank_code: "1")).to be_valid end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:paraguay_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:paraguay_bank_account)).to be_valid expect(build(:paraguay_bank_account, account_number: "1234567890123456")).to be_valid expect(build(:paraguay_bank_account, account_number: "123")).to be_valid py_bank_account = build(:paraguay_bank_account, account_number: "12345678901234567") expect(py_bank_account).to_not be_valid expect(py_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") py_bank_account = build(:paraguay_bank_account, account_number: "ABC123") expect(py_bank_account).to_not be_valid expect(py_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/variant_price_spec.rb
spec/models/variant_price_spec.rb
# frozen_string_literal: true require "spec_helper" describe VariantPrice do describe "associations" do it "belongs to a variant" do price = create(:variant_price) expect(price.variant).to be_a Variant end end describe "validations" do it "requires that the variant is present" do invalid_price = create(:variant_price) invalid_price.variant = nil expect(invalid_price).not_to be_valid expect(invalid_price.errors.full_messages).to include "Variant can't be blank" end it "requires that price_cents is present" do invalid_price = create(:variant_price) invalid_price.price_cents = nil expect(invalid_price).not_to be_valid expect(invalid_price.errors.full_messages).to include "Please provide a price for all selected payment options." end it "requires that currency is present" do invalid_price = create(:variant_price) invalid_price.currency = nil expect(invalid_price).not_to be_valid expect(invalid_price.errors.full_messages).to include "Currency can't be blank" end describe "recurrence validation" do context "when present" do it "must be one of the permitted recurrences" do BasePrice::Recurrence.all.each do |recurrence| expect(build(:variant_price, recurrence:)).to be_valid end invalid_price = build(:variant_price, recurrence: "whenever") expect(invalid_price).not_to be_valid expect(invalid_price.errors.full_messages).to include "Please provide a valid payment option." end end it "can be blank" do expect(build(:variant_price, recurrence: nil)).to be_valid end end end describe "is_default_recurrence?" do let(:product) { create(:membership_product, subscription_duration: "monthly") } it "returns true if the recurrence is the same as product's subscription duration" do price = create(:variant_price, variant: product.tiers.first, recurrence: "monthly") expect(price.is_default_recurrence?).to eq true end it "returns false if the recurrence is not the same as the product's subscription duration" do prices = [ create(:variant_price, variant: product.tiers.first, recurrence: "yearly"), create(:variant_price, variant: product.tiers.first, recurrence: nil), create(:variant_price, recurrence: "monthly") ] prices.each do |price| expect(price.is_default_recurrence?).to eq false end end end describe "#price_formatted_without_symbol" do it "returns the formatted price without a symbol" do price = create(:variant_price, price_cents: 299) expect(price.price_formatted_without_symbol).to eq "2.99" end context "when price_cents is blank" do it "returns an empty string" do price = build(:variant_price, price_cents: nil) expect(price.price_formatted_without_symbol).to eq "" end end end describe "#suggested_price_formatted_without_symbol" do it "returns the formatted suggested price without a symbol" do price = create(:variant_price, suggested_price_cents: 299) expect(price.suggested_price_formatted_without_symbol).to eq "2.99" end context "when suggested_price_cents is blank" do it "returns nil" do price = build(:variant_price, suggested_price_cents: nil) expect(price.suggested_price_formatted_without_symbol).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/models/integration_spec.rb
spec/models/integration_spec.rb
# frozen_string_literal: true require "spec_helper" describe Integration do describe "#type_for" do it "returns the type for the given integration name" do { Integration::CIRCLE => CircleIntegration.name, Integration::DISCORD => DiscordIntegration.name, Integration::ZOOM => ZoomIntegration.name, Integration::GOOGLE_CALENDAR => GoogleCalendarIntegration.name }.each do |name, expected_type| expect(Integration.type_for(name)).to eq(expected_type) end end end describe "#class_for" do it "returns the class for the given integration name" do { Integration::CIRCLE => CircleIntegration, Integration::DISCORD => DiscordIntegration, Integration::ZOOM => ZoomIntegration, Integration::GOOGLE_CALENDAR => GoogleCalendarIntegration }.each do |name, expected_class| expect(Integration.class_for(name)).to eq(expected_class) end end end describe "#name" do it "returns the name" do { Integration::CIRCLE => create(:circle_integration), Integration::DISCORD => create(:discord_integration), Integration::ZOOM => create(:zoom_integration), Integration::GOOGLE_CALENDAR => create(:google_calendar_integration) }.each do |expected_name, integration| expect(integration.name).to eq(expected_name) end end end describe ".enabled_integrations_for" do it "returns the enabled integrations on a purchase" do product = create(:product, active_integrations: [create(:circle_integration)]) purchase = create(:purchase, link: product) expect(Integration.enabled_integrations_for(purchase)).to eq({ "circle" => true, "discord" => false, "zoom" => false, "google_calendar" => false }) end it "does not consider deleted integrations as enabled" do product = create(:product, active_integrations: [create(:circle_integration), create(:discord_integration)]) product.product_integrations.first.mark_deleted! purchase = create(:purchase, link: product) expect(Integration.enabled_integrations_for(purchase)).to eq({ "circle" => false, "discord" => true, "zoom" => false, "google_calendar" => false }) end end describe "scopes" do describe "by_name" do it "returns collection of integrations of the given integration type" do integration_1 = create(:circle_integration) create(:discord_integration) integration_3 = create(:circle_integration) expect(Integration.by_name(Integration::CIRCLE)).to eq([integration_1, integration_3]) end end end describe "associations" do context "has one `product_integration`" do it "returns product_integration if exists" do integration = create(:circle_integration) product = create(:product, active_integrations: [integration]) expect(integration.product_integration.product_id).to eq(product.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/models/liechtenstein_bank_account_spec.rb
spec/models/liechtenstein_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe LiechtensteinBankAccount do describe "#bank_account_type" do it "returns LI" do expect(create(:liechtenstein_bank_account).bank_account_type).to eq("LI") end end describe "#country" do it "returns LI" do expect(create(:liechtenstein_bank_account).country).to eq("LI") end end describe "#currency" do it "returns chf" do expect(create(:liechtenstein_bank_account).currency).to eq("chf") end end describe "#routing_number" do it "returns nil" do expect(create(:liechtenstein_bank_account).routing_number).to be nil end end describe "#account_number_visual" do it "returns the visual account number with country code prefixed" do expect(create(:liechtenstein_bank_account, account_number_last_four: "8777").account_number_visual).to eq("******8777") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:liechtenstein_bank_account)).to be_valid expect(build(:liechtenstein_bank_account, account_number: "LI0508800636123378777")).to be_valid li_bank_account = build(:liechtenstein_bank_account, account_number: "LI938601111") expect(li_bank_account).to_not be_valid expect(li_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") li_bank_account = build(:liechtenstein_bank_account, account_number: "LIABCDEFGHIJKLM") expect(li_bank_account).to_not be_valid expect(li_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") li_bank_account = build(:liechtenstein_bank_account, account_number: "LI9386011117947123456") expect(li_bank_account).to_not be_valid expect(li_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") li_bank_account = build(:liechtenstein_bank_account, account_number: "129386011117947") expect(li_bank_account).to_not be_valid expect(li_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/balance_transaction_spec.rb
spec/models/balance_transaction_spec.rb
# frozen_string_literal: true require "spec_helper" describe BalanceTransaction, :vcr do describe BalanceTransaction::Amount do describe "create_issued_amount_for_affiliate" do let(:issued_affiliate_cents) { 10_00 } let(:flow_of_funds) { raise "You must define `flow_of_funds`." } let(:amount) do BalanceTransaction::Amount.create_issued_amount_for_affiliate( flow_of_funds:, issued_affiliate_cents: ) end describe "issued amount and settled amounts are the same, no merchant account" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), merchant_account_gross_amount: nil, merchant_account_net_amount: nil ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.gumroad_amount.currency) expect(amount.gross_cents).to eq(issued_affiliate_cents) expect(amount.net_cents).to eq(issued_affiliate_cents) end end describe "issued amount and settled amounts are the same, a merchant accounts" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 30_00), merchant_account_gross_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), merchant_account_net_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 70_00) ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.gumroad_amount.currency) expect(amount.gross_cents).to eq(issued_affiliate_cents) expect(amount.net_cents).to eq(issued_affiliate_cents) end end describe "issued amount and settled amounts are not the same, a merchant account" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 30_00), merchant_account_gross_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110_00), merchant_account_net_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 80_00) ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.gumroad_amount.currency) expect(amount.gross_cents).to eq(issued_affiliate_cents) expect(amount.net_cents).to eq(issued_affiliate_cents) end end end describe "create_holding_amount_for_affiliate" do let(:issued_affiliate_cents) { 10_00 } let(:flow_of_funds) { raise "You must define `flow_of_funds`." } let(:amount) do BalanceTransaction::Amount.create_holding_amount_for_affiliate( flow_of_funds:, issued_affiliate_cents: ) end describe "issued amount and settled amounts are the same, no merchant account" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), merchant_account_gross_amount: nil, merchant_account_net_amount: nil ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.gumroad_amount.currency) expect(amount.gross_cents).to eq(issued_affiliate_cents) expect(amount.net_cents).to eq(issued_affiliate_cents) end end describe "issued amount and settled amounts are the same, a merchant accounts" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 30_00), merchant_account_gross_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), merchant_account_net_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 70_00) ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.gumroad_amount.currency) expect(amount.gross_cents).to eq(issued_affiliate_cents) expect(amount.net_cents).to eq(issued_affiliate_cents) end end describe "issued amount and settled amounts are not the same, a merchant account" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 30_00), merchant_account_gross_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110_00), merchant_account_net_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 80_00) ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.gumroad_amount.currency) expect(amount.gross_cents).to eq(issued_affiliate_cents) expect(amount.net_cents).to eq(issued_affiliate_cents) end end end describe "create_issued_amount_for_seller" do let(:issued_net_cents) { 70_00 } let(:flow_of_funds) { raise "You must define `flow_of_funds`." } let(:amount) do BalanceTransaction::Amount.create_issued_amount_for_seller( flow_of_funds:, issued_net_cents: ) end describe "issued amount and settled amounts are the same, no merchant account" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), merchant_account_gross_amount: nil, merchant_account_net_amount: nil ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.issued_amount.currency) expect(amount.gross_cents).to eq(flow_of_funds.issued_amount.cents) expect(amount.net_cents).to eq(issued_net_cents) end end describe "issued amount and settled amounts are the same, a merchant accounts" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 30_00), merchant_account_gross_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), merchant_account_net_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 70_00) ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.issued_amount.currency) expect(amount.gross_cents).to eq(flow_of_funds.issued_amount.cents) expect(amount.net_cents).to eq(issued_net_cents) end end describe "issued amount and settled amounts are not the same, a merchant account" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 30_00), merchant_account_gross_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110_00), merchant_account_net_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 80_00) ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.issued_amount.currency) expect(amount.gross_cents).to eq(flow_of_funds.issued_amount.cents) expect(amount.net_cents).to eq(issued_net_cents) end end end describe "create_holding_amount_for_seller" do let(:issued_net_cents) { 70_00 } let(:flow_of_funds) { raise "You must define `flow_of_funds`." } let(:amount) do BalanceTransaction::Amount.create_holding_amount_for_seller( flow_of_funds:, issued_net_cents: ) end describe "issued amount and settled amounts are the same, no merchant account" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), merchant_account_gross_amount: nil, merchant_account_net_amount: nil ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.issued_amount.currency) expect(amount.gross_cents).to eq(flow_of_funds.issued_amount.cents) expect(amount.net_cents).to eq(issued_net_cents) end end describe "issued amount and settled amounts are the same, a merchant accounts" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 30_00), merchant_account_gross_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), merchant_account_net_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 70_00) ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.issued_amount.currency) expect(amount.gross_cents).to eq(flow_of_funds.issued_amount.cents) expect(amount.net_cents).to eq(issued_net_cents) end end describe "issued amount and settled amounts are not the same, a merchant account" do let(:flow_of_funds) do FlowOfFunds.new( issued_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100_00), settled_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110_00), gumroad_amount: FlowOfFunds::Amount.new(currency: Currency::USD, cents: 30_00), merchant_account_gross_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110_00), merchant_account_net_amount: FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 80_00) ) end it "creates an amount" do expect(amount.currency).to eq(flow_of_funds.merchant_account_gross_amount.currency) expect(amount.currency).to eq(flow_of_funds.merchant_account_net_amount.currency) expect(amount.gross_cents).to eq(flow_of_funds.merchant_account_gross_amount.cents) expect(amount.net_cents).to eq(flow_of_funds.merchant_account_net_amount.cents) end end end end describe "create!" do let(:user) { create(:user) } let(:link) { create(:product, user:) } let(:merchant_account) { create(:merchant_account) } describe "for a purchase" do let!(:purchase) { travel_to(1.day.ago) { create(:purchase, link:, seller: user, merchant_account:) } } let(:balance_transaction) do BalanceTransaction.create!( user:, merchant_account:, purchase:, issued_amount: BalanceTransaction::Amount.new( currency: Currency::USD, gross_cents: 100_00, net_cents: 88_90 ), holding_amount: BalanceTransaction::Amount.new( currency: Currency::CAD, gross_cents: 110_00, net_cents: 97_79 ) ) end it "saves all the associations on the balance_transaction record" do Balance.destroy_all expect(balance_transaction.user).to eq(user) expect(balance_transaction.merchant_account).to eq(merchant_account) expect(balance_transaction.purchase).to eq(purchase) expect(balance_transaction.refund).to eq(nil) expect(balance_transaction.dispute).to eq(nil) expect(balance_transaction.credit).to eq(nil) end it "saves all the amounts on the balance_transaction record" do expect(balance_transaction.issued_amount_currency).to eq(Currency::USD) expect(balance_transaction.issued_amount_gross_cents).to eq(100_00) expect(balance_transaction.issued_amount_net_cents).to eq(88_90) expect(balance_transaction.holding_amount_currency).to eq(Currency::CAD) expect(balance_transaction.holding_amount_gross_cents).to eq(110_00) expect(balance_transaction.holding_amount_net_cents).to eq(97_79) end it "results in a balance object having the new balance" do expect { balance_transaction }.to change { user.unpaid_balance_cents }.by(88_90) end describe "balance update" do before { Balance.destroy_all } describe "no balances exist" do it "creates a balance for the day of purchase and update its amounts" do expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(purchase.succeeded_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(88_90) expect(balance_transaction.balance.holding_amount_cents).to eq(97_79) end end describe "unpaid balance exists on another day, but not the day of purchase" do let(:balance) do create( :balance, state: "unpaid", user:, merchant_account:, date: (purchase.succeeded_at + 2.days).to_date, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::CAD, holding_amount_cents: 110_00 ) end before do balance end it "creates a balance for the day of purchase and update it's amounts" do expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(purchase.succeeded_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(88_90) expect(balance_transaction.balance.holding_amount_cents).to eq(97_79) end end describe "paid balance exists on another day, but not the day of purchase" do let(:balance) do create( :balance, state: "paid", user:, merchant_account:, date: (purchase.succeeded_at + 2.days).to_date, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::CAD, holding_amount_cents: 110_00 ) end before do balance end it "creates a balance for the day of purchase and update it's amounts" do expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(purchase.succeeded_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(88_90) expect(balance_transaction.balance.holding_amount_cents).to eq(97_79) end end describe "unpaid balance exists on day of purchase, but with different holding currency" do let(:balance) do create( :balance, state: "unpaid", user:, merchant_account:, date: purchase.succeeded_at.to_date, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::USD, holding_amount_cents: 100_00 ) end before do balance end it "creates a balance for the day of purchase and update it's amounts" do expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(purchase.succeeded_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(88_90) expect(balance_transaction.balance.holding_amount_cents).to eq(97_79) end end describe "unpaid balance exists on day of purchase" do let(:balance) do create( :balance, state: "unpaid", user:, merchant_account:, date: purchase.succeeded_at.to_date, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::CAD, holding_amount_cents: 110_00 ) end before do balance end it "updates the balance's amounts" do expect(balance_transaction.balance).to eq(balance) expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(purchase.succeeded_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(188_90) expect(balance_transaction.balance.holding_amount_cents).to eq(207_79) end end describe "processing balance exists on day of purchase" do let(:balance) do create( :balance, state: "processing", user:, merchant_account:, date: purchase.succeeded_at.to_date, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::CAD, holding_amount_cents: 110_00 ) end before do balance end it "creates a new unpaid balance record" do expect { balance_transaction }.to change { user.balances.count }.by(1) expect(balance_transaction.balance).not_to eq(balance) expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(purchase.succeeded_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(88_90) expect(balance_transaction.balance.holding_amount_cents).to eq(97_79) end end describe "paid balance exists on day of purchase" do let(:balance) do create( :balance, state: "paid", user:, merchant_account:, date: purchase.succeeded_at.to_date, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::CAD, holding_amount_cents: 110_00 ) end before do balance end it "creates a new unpaid balance record" do expect { balance_transaction }.to change { user.balances.count }.by(1) expect(balance_transaction.balance).not_to eq(balance) expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(purchase.succeeded_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(88_90) expect(balance_transaction.balance.holding_amount_cents).to eq(97_79) end end end end describe "for a refund" do let!(:purchase) { travel_to(30.days.ago) { create(:purchase, link:, seller: user, merchant_account:) } } let!(:refund) { travel_to(1.day.ago) { create(:refund, purchase:) } } let(:balance_transaction) do BalanceTransaction.create!( user:, merchant_account:, refund:, issued_amount: BalanceTransaction::Amount.new( currency: Currency::USD, gross_cents: -100_00, net_cents: -88_90 ), holding_amount: BalanceTransaction::Amount.new( currency: Currency::CAD, gross_cents: -110_00, net_cents: -97_79 ) ) end it "saves all the associations on the balance_transaction record" do expect(balance_transaction.user).to eq(user) expect(balance_transaction.merchant_account).to eq(merchant_account) expect(balance_transaction.purchase).to eq(nil) expect(balance_transaction.refund).to eq(refund) expect(balance_transaction.dispute).to eq(nil) expect(balance_transaction.credit).to eq(nil) end it "saves all the amounts on the balance_transaction record" do expect(balance_transaction.issued_amount_currency).to eq(Currency::USD) expect(balance_transaction.issued_amount_gross_cents).to eq(-100_00) expect(balance_transaction.issued_amount_net_cents).to eq(-88_90) expect(balance_transaction.holding_amount_currency).to eq(Currency::CAD) expect(balance_transaction.holding_amount_gross_cents).to eq(-110_00) expect(balance_transaction.holding_amount_net_cents).to eq(-97_79) end it "results in a balance object having the new balance" do expect { balance_transaction }.to change { user.unpaid_balance_cents }.by(-88_90) end describe "balance update" do describe "no balances exist" do it "creates a balance for the day of refund and update it's amounts" do expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(refund.created_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(-88_90) expect(balance_transaction.balance.holding_amount_cents).to eq(-97_79) end end describe "unpaid balance exists on day of refund's purchase" do let(:balance) do create( :balance, state: "unpaid", user:, merchant_account:, date: refund.purchase.succeeded_at.to_date, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::CAD, holding_amount_cents: 110_00 ) end before do balance end it "updates the balance's amounts" do expect(balance_transaction.balance).to eq(balance) expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(refund.purchase.succeeded_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(11_10) expect(balance_transaction.balance.holding_amount_cents).to eq(12_21) end end describe "unpaid balance exists on another day, but not the day of refund's purchase" do let(:balance) do create( :balance, state: "unpaid", user:, merchant_account:, date: (refund.purchase.succeeded_at + 2.days).to_date, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::CAD, holding_amount_cents: 110_00 ) end before do balance end it "updates the balance's amounts" do expect(balance_transaction.balance).to eq(balance) expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq((refund.purchase.succeeded_at + 2.days).to_date) expect(balance_transaction.balance.amount_cents).to eq(11_10) expect(balance_transaction.balance.holding_amount_cents).to eq(12_21) end end describe "paid balance exists on day of purchase, and unpaid balance exists on the day of refund" do let(:balance_1) do create( :balance, state: "paid", user:, merchant_account:, date: purchase.succeeded_at.to_date, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::CAD, holding_amount_cents: 110_00 ) end let(:balance_2) do create( :balance, state: "unpaid", user:, merchant_account:, date: (refund.created_at - 1.day).to_date, currency: Currency::USD, amount_cents: 200_00, holding_currency: Currency::CAD, holding_amount_cents: 220_00 ) end let(:balance_3) do create( :balance, state: "unpaid", user:, merchant_account:, date: refund.created_at.to_date, currency: Currency::USD, amount_cents: 300_00, holding_currency: Currency::CAD, holding_amount_cents: 330_00 ) end before do balance_1 balance_2 balance_3 end it "creates a balance for the earliest unpaid balance and update it's amounts" do expect(balance_transaction.balance).to eq(balance_2) expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq((refund.created_at - 1.day).to_date) expect(balance_transaction.balance.amount_cents).to eq(111_10) expect(balance_transaction.balance.holding_amount_cents).to eq(122_21) end end describe "processing balance exists on day of refund's purchase" do let(:balance) do create( :balance, state: "processing", user:, merchant_account:, date: refund.purchase.succeeded_at.to_date, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::CAD, holding_amount_cents: 110_00 ) end before do balance end it "creates a balance at the date of the refund and update it's amounts" do expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(refund.created_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(-88_90) expect(balance_transaction.balance.holding_amount_cents).to eq(-97_79) end end describe "paid balance exists on day of refund's purchase" do let(:balance) do create( :balance, state: "paid", user:, merchant_account:, date: refund.purchase.succeeded_at.to_date, currency: Currency::USD, amount_cents: 100_00, holding_currency: Currency::CAD, holding_amount_cents: 110_00 ) end before do balance end it "creates a balance for the date of the refund and update it's amounts" do expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(refund.created_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(-88_90) expect(balance_transaction.balance.holding_amount_cents).to eq(-97_79) end end end end describe "for a dispute" do let!(:purchase) { travel_to(30.days.ago) { create(:purchase, link:, seller: user, merchant_account:) } } let!(:dispute) { travel_to(1.day.ago) { create(:dispute_formalized, purchase:) } } let(:balance_transaction) do BalanceTransaction.create!( user:, merchant_account:, dispute:, issued_amount: BalanceTransaction::Amount.new( currency: Currency::USD, gross_cents: -100_00, net_cents: -88_90 ), holding_amount: BalanceTransaction::Amount.new( currency: Currency::CAD, gross_cents: -110_00, net_cents: -97_79 ) ) end it "saves all the associations on the balance_transaction record" do expect(balance_transaction.user).to eq(user) expect(balance_transaction.merchant_account).to eq(merchant_account) expect(balance_transaction.purchase).to eq(nil) expect(balance_transaction.refund).to eq(nil) expect(balance_transaction.dispute).to eq(dispute) expect(balance_transaction.credit).to eq(nil) end it "saves all the amounts on the balance_transaction record" do expect(balance_transaction.issued_amount_currency).to eq(Currency::USD) expect(balance_transaction.issued_amount_gross_cents).to eq(-100_00) expect(balance_transaction.issued_amount_net_cents).to eq(-88_90) expect(balance_transaction.holding_amount_currency).to eq(Currency::CAD) expect(balance_transaction.holding_amount_gross_cents).to eq(-110_00) expect(balance_transaction.holding_amount_net_cents).to eq(-97_79) end it "results in a balance object having the new balance" do expect { balance_transaction }.to change { user.unpaid_balance_cents }.by(-88_90) end describe "balance update" do describe "no balances exist" do it "creates a balance for the day of dispute and update it's amounts" do expect(balance_transaction.balance.user).to eq(user) expect(balance_transaction.balance.merchant_account).to eq(merchant_account) expect(balance_transaction.balance.date).to eq(dispute.formalized_at.to_date) expect(balance_transaction.balance.amount_cents).to eq(-88_90) expect(balance_transaction.balance.holding_amount_cents).to eq(-97_79)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/team_membership_spec.rb
spec/models/team_membership_spec.rb
# frozen_string_literal: true require "spec_helper" describe TeamMembership do describe "validations" do let(:user) { create(:user) } let(:seller) { create(:named_seller) } it "requires user, seller, role to be present" do team_membership = TeamMembership.new expect(team_membership.valid?).to eq(false) expect(team_membership.errors.full_messages).to include("User can't be blank") expect(team_membership.errors.full_messages).to include("Seller can't be blank") expect(team_membership.errors.full_messages).to include("Role is not included in the list") end it "requires valid role" do team_membership = TeamMembership.new(user:, seller:, role: :foo) expect(team_membership.valid?).to eq(false) expect(team_membership.errors.full_messages).to include("Role is not included in the list") end it "validates uniqueness for seller and user when record alive" do team_membership = create(:team_membership, user:, seller:, role: TeamMembership::ROLE_ADMIN) team_membership_dupe = team_membership.dup expect(team_membership_dupe.valid?).to eq(false) expect(team_membership_dupe.errors.full_messages).to include("Seller has already been taken") end it "validates role_owner_cannot_be_assigned_to_other_users" do team_membership = TeamMembership.new(user:, seller:, role: TeamMembership::ROLE_OWNER) expect(team_membership.valid?).to eq(false) expect(team_membership.errors.full_messages).to include("Seller must match user for owner role") end it "validates owner_membership_must_exist" do team_membership = user.user_memberships.new(seller:, role: TeamMembership::ROLE_ADMIN) expect(team_membership.valid?).to eq(false) expect(team_membership.errors.full_messages).to include("User requires owner membership to be created first") end describe "validate only_owner_role_can_be_assigned_to_natural_owner" do TeamMembership::ROLES.excluding(TeamMembership::ROLE_OWNER).each do |role| it "#{role} role cannot be assigned to owner" do team_membership = user.user_memberships.new(seller: user, role:) expect(team_membership.valid?).to eq(false) expect(team_membership.errors.full_messages).to include("Role cannot be assigned to owner's membership") end end end context "with deleted record" do let(:team_membership) { create(:team_membership, user:, seller:, role: TeamMembership::ROLE_ADMIN) } before do team_membership.update_as_deleted! end it "allows creating a new record" do expect do user.user_memberships.create!(seller:, role: TeamMembership::ROLE_ADMIN) end.to change { TeamMembership.count }.by(1) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/antigua_and_barbuda_bank_account_spec.rb
spec/models/antigua_and_barbuda_bank_account_spec.rb
# frozen_string_literal: true describe AntiguaAndBarbudaBankAccount do describe "#bank_account_type" do it "returns AG" do expect(create(:antigua_and_barbuda_bank_account).bank_account_type).to eq("AG") end end describe "#country" do it "returns AG" do expect(create(:antigua_and_barbuda_bank_account).country).to eq("AG") end end describe "#currency" do it "returns xcd" do expect(create(:antigua_and_barbuda_bank_account).currency).to eq("xcd") end end describe "#routing_number" do it "returns valid for 8 to 11 characters" do expect(build(:antigua_and_barbuda_bank_account, bank_code: "AAAAAGAGXYZ")).to be_valid expect(build(:antigua_and_barbuda_bank_account, bank_code: "AAAAAGAG")).to be_valid expect(build(:antigua_and_barbuda_bank_account, bank_code: "AAAAAGAGXYZZ")).not_to be_valid expect(build(:antigua_and_barbuda_bank_account, bank_code: "AAAAAGA")).not_to be_valid end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:antigua_and_barbuda_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:antigua_and_barbuda_bank_account)).to be_valid expect(build(:antigua_and_barbuda_bank_account, account_number: "000123456789")).to be_valid expect(build(:antigua_and_barbuda_bank_account, account_number: "00012345678910111213141516171819")).to be_valid expect(build(:antigua_and_barbuda_bank_account, account_number: "ABC12345678910111213141516171819")).to be_valid expect(build(:antigua_and_barbuda_bank_account, account_number: "12345678910111213141516171819ABC")).to be_valid ag_bank_account = build(:antigua_and_barbuda_bank_account, account_number: "000123456789101112131415161718192") expect(ag_bank_account).to_not be_valid expect(ag_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ag_bank_account = build(:antigua_and_barbuda_bank_account, account_number: "ABCD12345678910111213141516171819") expect(ag_bank_account).to_not be_valid expect(ag_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ag_bank_account = build(:antigua_and_barbuda_bank_account, account_number: "12345678910111213141516171819ABCD") expect(ag_bank_account).to_not be_valid expect(ag_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ag_bank_account = build(:antigua_and_barbuda_bank_account, account_number: "AB12345678910111213141516171819CD") expect(ag_bank_account).to_not be_valid expect(ag_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/european_bank_account_spec.rb
spec/models/european_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe EuropeanBankAccount do describe "#bank_account_type" do it "returns european" do expect(create(:european_bank_account).bank_account_type).to eq("EU") expect(create(:fr_bank_account).bank_account_type).to eq("EU") expect(create(:nl_bank_account).bank_account_type).to eq("EU") end end describe "#country" do it "returns the country based on first two digits of the IBAN account number" do expect(create(:european_bank_account).country).to eq("DE") expect(create(:fr_bank_account).country).to eq("FR") expect(create(:nl_bank_account).country).to eq("NL") end end describe "#currency" do it "returns eur" do expect(create(:european_bank_account).currency).to eq("eur") expect(create(:fr_bank_account).currency).to eq("eur") expect(create(:nl_bank_account).currency).to eq("eur") end end describe "#routing_number" do it "returns nil" do expect(create(:european_bank_account).routing_number).to be nil end end describe "#account_number_visual" do it "returns the visual account number with country code prefixed" do expect(create(:european_bank_account, account_number_last_four: "3000").account_number_visual).to eq("DE******3000") expect(create(:fr_bank_account, account_number_last_four: "3000").account_number_visual).to eq("FR******3000") expect(create(:nl_bank_account, account_number_last_four: "3000").account_number_visual).to eq("NL******3000") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:european_bank_account, account_number: "DE89370400440532013000")).to be_valid expect(build(:european_bank_account, account_number: "FR1420041010050500013M02606")).to be_valid expect(build(:european_bank_account, account_number: "NL91ABNA0417164300")).to be_valid de_bank_account = build(:european_bank_account, account_number: "DE12345") expect(de_bank_account).to_not be_valid expect(de_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") fr_bank_account = build(:european_bank_account, account_number: "893704004405320130001234567") expect(fr_bank_account).to_not be_valid expect(fr_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") nl_bank_account = build(:european_bank_account, account_number: "NLABCDE") expect(nl_bank_account).to_not be_valid expect(nl_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/base_variant_integration_spec.rb
spec/models/base_variant_integration_spec.rb
# frozen_string_literal: true require "spec_helper" describe BaseVariantIntegration do describe "validations" do before do @integration = create(:circle_integration) @variant = create(:variant) end it "raises error if base_variant_id is not present" do base_variant_integration = BaseVariantIntegration.new(integration_id: @integration.id) expect(base_variant_integration.valid?).to eq(false) expect(base_variant_integration.errors.full_messages).to include("Base variant can't be blank") end it "raises error if integration_id is not present" do base_variant_integration = BaseVariantIntegration.new(base_variant_id: @variant.id) expect(base_variant_integration.valid?).to eq(false) expect(base_variant_integration.errors.full_messages).to include("Integration can't be blank") end it "raises error if (base_variant_id, integration_id) is not unique" do BaseVariantIntegration.create!(integration_id: @integration.id, base_variant_id: @variant.id) base_variant_integration_2 = BaseVariantIntegration.new(integration_id: @integration.id, base_variant_id: @variant.id) expect(base_variant_integration_2.valid?).to eq(false) expect(base_variant_integration_2.errors.full_messages).to include("Integration has already been taken") end it "raises error if different variants linked to the same integration are not from the same product" do BaseVariantIntegration.create!(integration_id: @integration.id, base_variant_id: @variant.id) base_variant_integration_2 = BaseVariantIntegration.new(integration_id: @integration.id, base_variant_id: create(:variant).id) expect(base_variant_integration_2.valid?).to eq(false) expect(base_variant_integration_2.errors.full_messages).to include("Integration has already been taken by a variant from a different product.") end it "is successful if different variants of the same product have the same integration" do category = create(:variant_category, link: create(:product)) variant_1 = create(:variant, variant_category: category) variant_2 = create(:variant, variant_category: category) BaseVariantIntegration.create!(integration_id: @integration.id, base_variant_id: variant_1.id) BaseVariantIntegration.create!(integration_id: @integration.id, base_variant_id: variant_2.id) expect(BaseVariantIntegration.count).to eq(2) end it "is successful if (product_id, integration_id) is not unique but all clashing entries have been deleted" do base_variant_integration_1 = BaseVariantIntegration.create!(integration_id: @integration.id, base_variant_id: @variant.id) base_variant_integration_1.mark_deleted! BaseVariantIntegration.create!(integration_id: @integration.id, base_variant_id: @variant.id) expect(BaseVariantIntegration.count).to eq(2) expect(@variant.active_integrations.count).to eq(1) end it "is successful if same variant has different integrations" do BaseVariantIntegration.create!(integration_id: @integration.id, base_variant_id: @variant.id) BaseVariantIntegration.create!(integration_id: create(:circle_integration).id, base_variant_id: @variant.id) expect(BaseVariantIntegration.count).to eq(2) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/seller_refund_policy_spec.rb
spec/models/seller_refund_policy_spec.rb
# frozen_string_literal: true require "spec_helper" describe SellerRefundPolicy do let(:seller) { create(:named_seller) } let(:refund_policy) { seller.refund_policy } describe "validations" do it "validates presence" do refund_policy = SellerRefundPolicy.new expect(refund_policy.valid?).to be false expect(refund_policy.errors.details[:seller].first[:error]).to eq :blank end context "when refund policy for seller exists" do it "validates seller uniqueness" do new_refund_policy = refund_policy.dup expect(new_refund_policy.valid?).to be false expect(new_refund_policy.errors.details[:seller].first[:error]).to eq :taken end end it "validates fine_print length" do refund_policy.fine_print = "a" * 3001 expect(refund_policy.valid?).to be false expect(refund_policy.errors.details[:fine_print].first[:error]).to eq :too_long end it "strips tags" do refund_policy.fine_print = "<p>This is a account-level refund policy</p>" refund_policy.save! expect(refund_policy.fine_print).to eq "This is a account-level refund policy" end end describe "stripped_fields" do before do refund_policy.update!(fine_print: " This is a account-level refund policy ") end it "strips leading and trailing spaces for fine_print" do expect(refund_policy.fine_print).to eq "This is a account-level refund policy" end it "nullifies fine_print" do refund_policy.update!(fine_print: "") expect(refund_policy.fine_print).to be_nil end end describe "#as_json" do it "returns a hash with refund details" do expect(refund_policy.as_json).to eq( { fine_print: refund_policy.fine_print, id: refund_policy.external_id, title: refund_policy.title, } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/call_limitation_info_spec.rb
spec/models/call_limitation_info_spec.rb
# frozen_string_literal: true describe CallLimitationInfo do describe "validations" do context "call is not a call product" do let(:call_limitation_info) { build(:call_limitation_info, call: create(:product)) } it "adds an error" do expect(call_limitation_info).not_to be_valid expect(call_limitation_info.errors.full_messages).to eq(["Cannot create call limitations for a non-call product."]) end end end describe "#can_take_more_calls_on?" do let(:call_product) { create(:call_product, :available_for_a_year) } let(:call_limitation_info) { call_product.call_limitation_info } let(:tomorrow_noon) { Time.current.in_time_zone(call_product.user.timezone).tomorrow.noon } context "when maximum_calls_per_day is not set" do before { call_limitation_info.update!(maximum_calls_per_day: nil) } it "returns true" do expect(call_limitation_info.can_take_more_calls_on?(tomorrow_noon)).to be true end end context "when maximum_calls_per_day is set" do before { call_limitation_info.update!(maximum_calls_per_day: 2, minimum_notice_in_minutes: nil) } it "returns true when the number of calls is less than the maximum on that date" do create(:call, start_time: tomorrow_noon, end_time: tomorrow_noon + 1.hour, link: call_product) expect(call_limitation_info.can_take_more_calls_on?(tomorrow_noon)).to be true create(:call, start_time: tomorrow_noon + 1.hour, end_time: tomorrow_noon + 2.hours, link: call_product) expect(call_limitation_info.can_take_more_calls_on?(tomorrow_noon)).to be false expect(call_limitation_info.can_take_more_calls_on?(tomorrow_noon.next_day)).to be true end end end describe "#has_enough_notice?", :freeze_time do let(:call_product) { create(:call_product, :available_for_a_year) } let(:call_limitation_info) { call_product.call_limitation_info } context "when minimum_notice_in_minutes is set" do let(:notice_period) { 2.hours } before { call_limitation_info.update!(minimum_notice_in_minutes: notice_period.in_minutes) } it "returns false when start time is before the minimum notice period" do expect(call_limitation_info.has_enough_notice?(notice_period.from_now)).to be true expect(call_limitation_info.has_enough_notice?(notice_period.from_now + 1.minute)).to be true with_in_grace_period = notice_period.from_now - CallLimitationInfo::CHECKOUT_GRACE_PERIOD expect(call_limitation_info.has_enough_notice?(with_in_grace_period)).to be true expect(call_limitation_info.has_enough_notice?(with_in_grace_period - 1.minute)).to be false end end context "when minimum_notice_in_minutes is not set" do before { call_limitation_info.update!(minimum_notice_in_minutes: nil) } it "returns false if start time is in the past" do expect(call_limitation_info.has_enough_notice?(1.minute.ago)).to be false expect(call_limitation_info.has_enough_notice?(1.minute.from_now)).to be true end end end describe "#allows?" do let(:call_product) { create(:call_product, :available_for_a_year) } let(:call_limitation_info) { call_product.call_limitation_info } it "returns true iff has enough notice and can take more calls" do start_time = 1.day.from_now allow(call_limitation_info).to receive(:has_enough_notice?).with(start_time).and_return(false) allow(call_limitation_info).to receive(:can_take_more_calls_on?).with(start_time).and_return(false) expect(call_limitation_info.allows?(start_time)).to be false allow(call_limitation_info).to receive(:has_enough_notice?).with(start_time).and_return(true) expect(call_limitation_info.allows?(start_time)).to be false allow(call_limitation_info).to receive(:can_take_more_calls_on?).with(start_time).and_return(true) expect(call_limitation_info.allows?(start_time)).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/models/resource_subscription_spec.rb
spec/models/resource_subscription_spec.rb
# frozen_string_literal: true require "spec_helper" describe ResourceSubscription do before do @user = create(:user) end describe "#assign_content_type_to_json_for_zapier" do it "sets content_type to application/json for Zapier subscriptions" do resource_subscription = create(:resource_subscription, post_url: "https://hooks.zapier.com/sample", user: @user) expect(resource_subscription.content_type).to eq "application/json" end it "doesn't overwrite the default content_type application/x-www-form-urlencoded for non-Zapier subscriptions" do resource_subscription = create(:resource_subscription, post_url: "https://hooks.example.com/sample", user: @user) expect(resource_subscription.content_type).to eq "application/x-www-form-urlencoded" end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/email_event_spec.rb
spec/models/email_event_spec.rb
# frozen_string_literal: true require "spec_helper" describe EmailEvent do let(:emails) { ["one@example.com", "two@example.com", "three@example.com"] } let(:emails_digests) { emails.map { Digest::SHA1.hexdigest(_1).first(12) } } let(:email) { emails.first } let(:email_digest) { emails_digests.first } let(:timestamp) { Time.current } describe ".log_send_events" do context "when email logging is enabled" do it "logs email sent event" do # create a new record (passing an email as a string) described_class.log_send_events(emails.first, timestamp) expect(EmailEvent.count).to eq 1 record = EmailEvent.find_by(email_digest: emails_digests.first) expect(record.sent_emails_count).to eq 1 expect(record.unopened_emails_count).to eq 1 expect(record.last_email_sent_at.to_i).to eq timestamp.to_i expect(record.first_unopened_email_sent_at.to_i).to eq timestamp.to_i # create a new record and update the existing one (passing an array of emails) timestamp_2 = 1.minute.from_now described_class.log_send_events(emails.first(2), timestamp_2) expect(EmailEvent.count).to eq 2 record = EmailEvent.find_by(email_digest: emails_digests.first) expect(record.sent_emails_count).to eq 2 expect(record.unopened_emails_count).to eq 2 expect(record.last_email_sent_at.to_i).to eq timestamp_2.to_i expect(record.first_unopened_email_sent_at.to_i).to eq timestamp.to_i record = EmailEvent.find_by(email_digest: emails_digests.second) expect(record.sent_emails_count).to eq 1 expect(record.unopened_emails_count).to eq 1 expect(record.last_email_sent_at.to_i).to eq timestamp_2.to_i expect(record.first_unopened_email_sent_at.to_i).to eq timestamp_2.to_i # create a new record and updates two existing ones timestamp_3 = 2.minutes.from_now described_class.log_send_events(emails, timestamp_3) expect(EmailEvent.count).to eq 3 record = EmailEvent.find_by(email_digest: emails_digests.first) expect(record.sent_emails_count).to eq 3 expect(record.unopened_emails_count).to eq 3 expect(record.last_email_sent_at.to_i).to eq timestamp_3.to_i expect(record.first_unopened_email_sent_at.to_i).to eq timestamp.to_i record = EmailEvent.find_by(email_digest: emails_digests.second) expect(record.sent_emails_count).to eq 2 expect(record.unopened_emails_count).to eq 2 expect(record.last_email_sent_at.to_i).to eq timestamp_3.to_i expect(record.first_unopened_email_sent_at.to_i).to eq timestamp_2.to_i record = EmailEvent.find_by(email_digest: emails_digests.third) expect(record.sent_emails_count).to eq 1 expect(record.unopened_emails_count).to eq 1 expect(record.last_email_sent_at.to_i).to eq timestamp_3.to_i expect(record.first_unopened_email_sent_at.to_i).to eq timestamp_3.to_i end end context "when email logging is disabled" do before do Feature.deactivate(:log_email_events) end it "doesn't log email sent event" do described_class.log_send_events(email, timestamp) record = EmailEvent.find_by(email_digest:) expect(record).to be_nil end end end describe ".log_open_event" do context "when email logging is disabled" do before do described_class.log_send_events(email, timestamp) Feature.deactivate(:log_email_events) end it "doesn't log email open event" do expect(described_class.log_open_event(email, timestamp)).to be_nil end end context "when email logging is enabled" do context "when EmailEvent record doesn't exist" do it "returns nil" do expect(described_class.log_open_event(email, timestamp)).to be_nil end end context "when EmailEvent record exists" do before do described_class.log_send_events(email, timestamp) end it "logs email open event" do described_class.log_open_event(email, timestamp) 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 timestamp.to_i end end end end describe ".log_click_event" do context "when email logging is disabled" do before do described_class.log_send_events(email, timestamp) Feature.deactivate(:log_email_events) end it "doesn't log email click event" do expect(described_class.log_click_event(email, timestamp)).to be_nil end end context "when email logging is enabled" do context "when EmailEvent record doesn't exist" do it "returns nil" do expect(described_class.log_click_event(email, timestamp)).to be_nil end end context "when EmailEvent record exists" do before do described_class.log_send_events(email, timestamp) end it "logs email click event" do described_class.log_click_event(email, timestamp) record = EmailEvent.find_by(email_digest:) expect(record.click_count).to eq 1 expect(record.last_clicked_at.to_i).to eq timestamp.to_i end end end end describe ".stale_recipient?" do context "when EmailEvent record doesn't exist" do it "returns false" do expect(described_class.stale_recipient?(email)).to be false end end context "when EmailEvent record exists" do before do described_class.log_send_events(email, timestamp) end context "when first_unopened_email_sent_at is nil" do before do described_class.log_open_event(email, timestamp) end it "returns false" do expect(described_class.stale_recipient?(email)).to be false end end context "when first_unopened_email_sent_at is within threshold" do before do event = EmailEvent.find_by(email_digest:) event.update!(first_unopened_email_sent_at: 364.days.ago) end it "returns false" do expect(described_class.stale_recipient?(email)).to be false end end context "when first_unopened_email_sent_at is beyond threshold" do before do event = EmailEvent.find_by(email_digest:) event.update!(first_unopened_email_sent_at: 366.days.ago) end context "when unopened_emails_count is below threshold" do before do event = EmailEvent.find_by(email_digest:) event.update!(unopened_emails_count: 9) end it "returns false" do expect(described_class.stale_recipient?(email)).to be false end end context "when unopened_emails_count meets threshold" do before do event = EmailEvent.find_by(email_digest:) event.update!(unopened_emails_count: 10) end context "when last_clicked_at is within threshold" do before do event = EmailEvent.find_by(email_digest:) event.update!(last_clicked_at: 364.days.ago) end it "returns false" do expect(described_class.stale_recipient?(email)).to be false end end context "when last_clicked_at is beyond threshold" do before do event = EmailEvent.find_by(email_digest:) event.update!(last_clicked_at: 366.days.ago) end it "returns true" do expect(described_class.stale_recipient?(email)).to be true end end context "when last_clicked_at is nil" do it "returns true" do expect(described_class.stale_recipient?(email)).to be true end end end end end end describe ".mark_as_stale" do context "when EmailEvent record doesn't exist" do it "returns nil" do expect(described_class.mark_as_stale(email, timestamp)).to be_nil end end context "when EmailEvent record exists" do before do described_class.log_send_events(email, timestamp) end it "marks the record as stale" do described_class.mark_as_stale(email, timestamp) record = EmailEvent.find_by(email_digest:) expect(record.marked_as_stale_at.to_i).to eq timestamp.to_i end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/blocked_customer_object_spec.rb
spec/models/blocked_customer_object_spec.rb
# frozen_string_literal: true require "spec_helper" describe BlockedCustomerObject do describe "validations" do subject(:blocked_customer_object) { build(:blocked_customer_object, object_type: nil, object_value: nil) } describe "presence" do it "doesn't allow an empty seller_id" do blocked_customer_object.seller = nil expect(blocked_customer_object).to be_invalid expect(blocked_customer_object.errors.full_messages).to include("Seller must exist") end it "doesn't allow an empty object_type" do expect(blocked_customer_object).to be_invalid expect(blocked_customer_object.errors.full_messages).to include("Object type can't be blank") end it "doesn't allow an empty object_value" do expect(blocked_customer_object).to be_invalid expect(blocked_customer_object.errors.full_messages).to include("Object value can't be blank") end end describe "inclusion" do it "doesn't allow an unsupported object_type" do blocked_customer_object.object_type = "something" expect(blocked_customer_object).to be_invalid expect(blocked_customer_object.errors.full_messages).to include("Object type is not included in the list") end end describe "format" do it "doesn't allow an object_value with an invalid email if object_type is 'email'" do blocked_customer_object.object_type = "email" blocked_customer_object.object_value = "invalid-email" expect(blocked_customer_object).to be_invalid expect(blocked_customer_object.errors.full_messages).to include("Object value is invalid") end end end describe "scopes" do let(:seller) { create(:named_seller) } let!(:blocked_email1) { create(:blocked_customer_object, seller:, object_type: "email", object_value: "john@example.com", blocked_at: DateTime.current) } let!(:blocked_email2) { create(:blocked_customer_object, seller:, object_type: "email", object_value: "alice@example.com") } describe ".email" do it "returns records matching object_type 'email'" do expect(described_class.email.count).to eq(2) expect(described_class.email).to match_array([blocked_email1, blocked_email2]) end end describe ".active" do it "returns records having non-nil blocked_at" do expect(described_class.active.count).to eq(1) expect(described_class.active).to match_array([blocked_email1]) end end describe ".inactive" do it "returns records having nil blocked_at" do expect(described_class.inactive.count).to eq(1) expect(described_class.inactive).to match_array([blocked_email2]) end end end describe ".email_blocked?" do let(:seller) { create(:named_seller) } context "when the given email is blocked by the seller" do before do BlockedCustomerObject.block_email!(email: "customer@example.com", seller_id: seller.id) end it "returns true" do expect(described_class.email_blocked?(email: "cuST.omer+test1234@example.com", seller_id: seller.id)).to be(true) end end context "when the given email is not blocked by the seller" do let(:another_seller) { create(:user) } before do BlockedCustomerObject.block_email!(email: "customer@example.com", seller_id: another_seller.id) BlockedCustomerObject.block_email!(email: "another-customer@example.com", seller_id: seller.id) BlockedCustomerObject.block_email!(email: "customer@example.com", seller_id: seller.id) seller.blocked_customer_objects.active.email.find_by(object_value: "customer@example.com").unblock! end it "returns false" do expect(described_class.email_blocked?(email: "customer@example.com", seller_id: seller.id)).to be(false) end end end describe ".block_email!" do let(:seller) { create(:named_seller) } context "when the email is not blocked or unblocked" do it "blocks the email" do expect(seller.blocked_customer_objects.active.email.count).to eq(0) expect do described_class.block_email!(email: "john@example.com", seller_id: seller.id) end.to change(described_class, :count).by(1) expect(seller.blocked_customer_objects.active.email.pluck(:object_value)).to match_array(["john@example.com"]) end end context "when the email is already blocked" do let!(:blocked_email_object) { create(:blocked_customer_object, seller:, object_type: "email", object_value: "john@example.com", blocked_at: 5.minutes.ago) } it "does nothing" do expect do described_class.block_email!(email: "john@example.com", seller_id: seller.id) end.not_to change(described_class, :count) expect(seller.blocked_customer_objects.active.email).to match_array([blocked_email_object]) end end context "when the email is unblocked" do let!(:blocked_email_object) { create(:blocked_customer_object, seller:, object_type: "email", object_value: "john@example.com") } it "blocks the email" do freeze_time do expect do expect do described_class.block_email!(email: "john@example.com", seller_id: seller.id) end.not_to change(described_class, :count) end.to change { blocked_email_object.reload.blocked_at }.from(nil).to(DateTime.current) end end end end describe "#unblock!" do let(:seller) { create(:named_seller) } let!(:blocked_object) { create(:blocked_customer_object, seller:, object_type: "email", object_value: "john@example.com", blocked_at: DateTime.parse("January 1, 2023")) } it "unblocks the object" do expect do blocked_object.unblock! end.to change { blocked_object.reload.blocked_at }.from(DateTime.parse("January 1, 2023")).to(nil) end it "does nothing if the object is already unblocked" do blocked_object.update!(blocked_at: nil) expect do blocked_object.reload.unblock! end.not_to change { blocked_object.reload.blocked_at } expect(blocked_object.blocked_at).to be_nil end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/namibia_bank_account_spec.rb
spec/models/namibia_bank_account_spec.rb
# frozen_string_literal: true describe NamibiaBankAccount do describe "#bank_account_type" do it "returns NA" do expect(create(:namibia_bank_account).bank_account_type).to eq("NA") end end describe "#country" do it "returns NA" do expect(create(:namibia_bank_account).country).to eq("NA") end end describe "#currency" do it "returns nad" do expect(create(:namibia_bank_account).currency).to eq("nad") end end describe "#routing_number" do it "returns valid for 8 to 11 characters" do expect(build(:namibia_bank_account, bank_code: "AAAANANXXYZ")).to be_valid expect(build(:namibia_bank_account, bank_code: "AAAANANX")).to be_valid expect(build(:namibia_bank_account, bank_code: "AAAANANXXYZZ")).not_to be_valid expect(build(:namibia_bank_account, bank_code: "AAAANAN")).not_to be_valid end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:namibia_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:namibia_bank_account)).to be_valid expect(build(:namibia_bank_account, account_number: "000123456789")).to be_valid expect(build(:namibia_bank_account, account_number: "12345678")).to be_valid expect(build(:namibia_bank_account, account_number: "NAM45678")).to be_valid expect(build(:namibia_bank_account, account_number: "0001234567NAM")).to be_valid na_bank_account = build(:namibia_bank_account, account_number: "1234567") expect(na_bank_account).to_not be_valid expect(na_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") na_bank_account = build(:namibia_bank_account, account_number: "12345678910111") expect(na_bank_account).to_not be_valid expect(na_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") na_bank_account = build(:namibia_bank_account, account_number: "0001234567NAMI") expect(na_bank_account).to_not be_valid expect(na_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") na_bank_account = build(:namibia_bank_account, account_number: "1234NAM") expect(na_bank_account).to_not be_valid expect(na_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/early_fraud_warning_spec.rb
spec/models/early_fraud_warning_spec.rb
# frozen_string_literal: true require "spec_helper" describe EarlyFraudWarning do describe "validations" do describe "for Purchase" do let(:purchase_efw) { create(:early_fraud_warning) } it "validates uniqueness of processor_id" do new_record = build(:early_fraud_warning, processor_id: purchase_efw.processor_id) expect(new_record).not_to be_valid expect(new_record.errors.messages).to eq( processor_id: ["has already been taken"] ) end it "validates uniqueness of purchase" do new_record = build(:early_fraud_warning, processor_id: "issfr_new", purchase: purchase_efw.purchase) expect(new_record).not_to be_valid expect(new_record.errors.messages).to eq( purchase: ["has already been taken"] ) end end describe "for Charge" do let(:charge_efw) { create(:early_fraud_warning, charge: create(:charge), purchase: nil) } context "when both a purchase and charge are present" do it "is not valid" do charge_efw.purchase = create(:purchase) expect(charge_efw).not_to be_valid expect(charge_efw.errors.messages).to eq( base: ["Only a purchase or a charge is allowed."] ) end end it "validates uniqueness of charge" do new_record = build(:early_fraud_warning, processor_id: "issfr_new", charge: charge_efw.charge, purchase: nil) expect(new_record).not_to be_valid expect(new_record.errors.messages).to eq( charge: ["has already been taken"] ) end end end describe "#update_from_stripe!" do let(:early_fraud_warning) { create(:early_fraud_warning) } it "calls the service" do expect(EarlyFraudWarning::UpdateService).to receive(:new).with(early_fraud_warning).and_return(double(perform!: true)) early_fraud_warning.update_from_stripe! end context "when EarlyFraudWarning::UpdateService::AlreadyResolvedError is raised" do it "ignores the error" do expect(EarlyFraudWarning::UpdateService).to receive(:new).with(early_fraud_warning) .and_raise(EarlyFraudWarning::UpdateService::AlreadyResolvedError) expect { early_fraud_warning.update_from_stripe! }.not_to raise_error end end end describe "#chargeable_refundable_for_fraud?" do RSpec.shared_examples "for a Chargeable" do context "when eligible" do it "returns true" do expect(early_fraud_warning.chargeable_refundable_for_fraud?).to eq(true) end end context "when the purchase was created before the dispute window" do before do chargeable.update!(created_at: (EarlyFraudWarning::ELIGIBLE_DISPUTE_WINDOW_DURATION + 1).days.ago) expect_any_instance_of(chargeable.class).not_to receive(:buyer_blocked?) end it "returns false" do expect(early_fraud_warning.chargeable_refundable_for_fraud?).to eq(false) end end end describe "for a Purchase" do let(:purchase) { create(:purchase, stripe_transaction_id: "ch_2O8n7J9e1RjUNIyY1rs9MIRL") } let!(:early_fraud_warning) { create(:early_fraud_warning, purchase:) } let(:chargeable) { purchase } include_examples "for a Chargeable" end describe "for a Charge" do let(:charge) do create( :charge, processor_transaction_id: "ch_2O8n7J9e1RjUNIyY1rs9MIRL", purchases: [create(:purchase, stripe_transaction_id: "ch_2O8n7J9e1RjUNIyY1rs9MIRL")] ) end let!(:early_fraud_warning) { create(:early_fraud_warning, charge:, purchase: nil) } let(:chargeable) { charge } include_examples "for a Chargeable" end end describe "#purchase_for_subscription_contactable?" do let!(:early_fraud_warning) do create( :early_fraud_warning, purchase:, fraud_type: EarlyFraudWarning::FRAUD_TYPE_UNAUTHORIZED_USE_OF_CARD, charge_risk_level: EarlyFraudWarning::CHARGE_RISK_LEVEL_NORMAL ) end context "when the purchase is not a subscription" do let(:purchase) { create(:purchase, stripe_transaction_id: "ch_2O8n7J9e1RjUNIyY1rs9MIRL") } it "returns false" do expect(early_fraud_warning.purchase_for_subscription_contactable?).to eq(false) end end context "when the purchase is for a subscription" do let(:purchase) { create(:membership_purchase) } context "when the purchase doesn't have a CustomerEmailInfo record" do it "returns false" do expect(early_fraud_warning.purchase_for_subscription_contactable?).to eq(false) end end context "when the purchase has a CustomerEmailInfo record" do context "when the CustomerEmailInfo has an eligible state" do before do create(:customer_email_info_sent, purchase:) end it "returns true" do expect(early_fraud_warning.purchase_for_subscription_contactable?).to eq(true) end context "when the risk level is not eligible" do before do early_fraud_warning.update!(charge_risk_level: EarlyFraudWarning::CHARGE_RISK_LEVEL_ELEVATED) end it "returns false" do expect(early_fraud_warning.purchase_for_subscription_contactable?).to eq(false) end end context "when the fraud_type is not unauthorized use of card" do before do early_fraud_warning.update!(fraud_type: EarlyFraudWarning::FRAUD_TYPE_MISC) end it "returns false" do expect(early_fraud_warning.purchase_for_subscription_contactable?).to eq(false) end end end context "when the CustomerEmailInfo doesn't have an eligible state" do before do create(:customer_email_info, purchase:) # created state end it "returns false" do expect(early_fraud_warning.purchase_for_subscription_contactable?).to eq(false) end end end end end describe "#associated_early_fraud_warning_ids_for_subscription_contacted" do let(:purchase) { create(:membership_purchase) } let(:subscription) { purchase.subscription } describe "for a Purchase" do let(:early_fraud_warning) { create(:early_fraud_warning, purchase:) } context "without associated purchases" do it "returns an empty array" do expect( early_fraud_warning.associated_early_fraud_warning_ids_for_subscription_contacted ).to eq([]) end end context "with associated purchases" do let!(:other_purchase) { create(:purchase, subscription:) } let!(:other_early_fraud_warning) do create(:early_fraud_warning, purchase: other_purchase, processor_id: "issfr_other") end context "when the associated purchase early fraud warning is not resolved" do it "returns an empty array" do expect( early_fraud_warning.associated_early_fraud_warning_ids_for_subscription_contacted ).to eq([]) end end context "when the associated purchase early fraud warning is resolved as ignored" do before do other_early_fraud_warning.update!(resolution: EarlyFraudWarning::RESOLUTION_RESOLVED_IGNORED) end it "returns an empty array" do expect( early_fraud_warning.associated_early_fraud_warning_ids_for_subscription_contacted ).to eq([]) end end context "when the associated purchase early fraud warning is resolved as contacted" do before do other_early_fraud_warning.update!( resolution: EarlyFraudWarning::RESOLUTION_RESOLVED_CUSTOMER_CONTACTED ) end it "returns the associated purchase early fraud warning ids" do expect( early_fraud_warning.associated_early_fraud_warning_ids_for_subscription_contacted ).to eq([other_early_fraud_warning.id]) end end end end describe "for a Charge" do let(:charge) { create(:charge, purchases: [purchase]) } let(:early_fraud_warning) { create(:early_fraud_warning, charge:, purchase: nil) } context "without associated purchases" do it "returns an empty array" do expect( early_fraud_warning.associated_early_fraud_warning_ids_for_subscription_contacted ).to eq([]) end end context "with associated purchases" do let!(:other_purchase) { create(:purchase, subscription:) } let!(:other_early_fraud_warning) do create(:early_fraud_warning, purchase: other_purchase, processor_id: "issfr_other") end context "when the associated purchase early fraud warning is not resolved" do it "returns an empty array" do expect( early_fraud_warning.associated_early_fraud_warning_ids_for_subscription_contacted ).to eq([]) end end context "when the associated purchase early fraud warning is resolved as ignored" do before do other_early_fraud_warning.update!(resolution: EarlyFraudWarning::RESOLUTION_RESOLVED_IGNORED) end it "returns an empty array" do expect( early_fraud_warning.associated_early_fraud_warning_ids_for_subscription_contacted ).to eq([]) end end context "when the associated purchase early fraud warning is resolved as contacted" do before do other_early_fraud_warning.update!( resolution: EarlyFraudWarning::RESOLUTION_RESOLVED_CUSTOMER_CONTACTED ) end it "returns the associated purchase early fraud warning ids" do expect( early_fraud_warning.associated_early_fraud_warning_ids_for_subscription_contacted ).to eq([other_early_fraud_warning.id]) end context "when the associated purchase early fraud warning is associated with a charge" do let(:other_charge) { create(:charge, purchases: [other_purchase]) } let!(:other_early_fraud_warning) do create(:early_fraud_warning, purchase: nil, charge: other_charge, processor_id: "issfr_other") end it "returns the associated purchase early fraud warning ids" do expect( early_fraud_warning.associated_early_fraud_warning_ids_for_subscription_contacted ).to eq([other_early_fraud_warning.id]) end end end end end end describe "#purchase_for_subscription" do describe "for a Purchase" do let(:purchase) { create(:purchase) } let(:early_fraud_warning) { create(:early_fraud_warning, purchase:) } context "when the purchase is not for membership" do it "returns nil" do expect(early_fraud_warning.purchase_for_subscription).to be_nil end end context "when the purchase is for membership" do let(:purchase) { create(:membership_purchase) } it "returns the purchase" do expect(early_fraud_warning.purchase_for_subscription).to eq(purchase) end end end describe "for a Charge" do let(:purchase) { create(:purchase) } let(:charge) { create(:charge, purchases: [purchase]) } let(:early_fraud_warning) { create(:early_fraud_warning, charge:, purchase: nil) } context "when the charge has no membership purchases" do it "returns nil" do expect(early_fraud_warning.purchase_for_subscription).to be_nil end end context "when the charge has a membership purchase" do let(:membership_purchase) { create(:membership_purchase) } before do charge.purchases << membership_purchase end it "returns the purchase" do expect(early_fraud_warning.purchase_for_subscription).to eq(membership_purchase) end end end end describe "#chargeable" do context "with a Purchase" do let(:purchase) { create(:purchase) } let(:early_fraud_warning) { create(:early_fraud_warning, purchase:) } it "returns the purchase" do expect(early_fraud_warning.chargeable).to eq(purchase) end end context "with a Charge" do let(:charge) { create(:charge) } let(:early_fraud_warning) { create(:early_fraud_warning, charge:, purchase: nil) } it "returns the charge" do expect(early_fraud_warning.chargeable).to eq(charge) end end end describe "#receipt_email_info" do let(:early_fraud_warning) { create(:early_fraud_warning) } context "when there are no purchase email infos" do it "returns nil" do expect(early_fraud_warning.send(:receipt_email_info)).to be_nil end end context "when there are purchase email infos" do let(:purchase) { early_fraud_warning.purchase } let!(:email_info_old) { create(:customer_email_info, purchase:, email_name: "receipt", state: "sent") } let!(:email_info) { create(:customer_email_info, purchase:, email_name: "receipt", state: "bounced") } it "returns the last receipt email info" do expect(early_fraud_warning.send(:receipt_email_info)).to eq(email_info) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/dispute_spec.rb
spec/models/dispute_spec.rb
# frozen_string_literal: true require "spec_helper" describe Dispute do describe "creation" do it "sets seller when creating from a purchase" do dispute = create(:dispute) expect(dispute.seller).to eq(dispute.purchase.seller) end it "sets seller when creating from a charge" do dispute = create(:dispute, purchase: nil, charge: create(:charge)) expect(dispute.seller).to eq(dispute.charge.seller) end it "can't be created without a purchase or a charge" do dispute = build(:dispute, purchase: nil) expect(dispute).not_to be_valid expect(dispute.errors[:base][0]).to eq("A Disputable object must be provided.") end it "can't be created with both purchase and charge" do dispute = build(:dispute, charge: create(:charge), purchase: create(:purchase)) expect(dispute).not_to be_valid expect(dispute.errors[:base][0]).to eq("Only one Disputable object must be provided.") end end describe "#disputable" do it "returns the associated purchase if dispute belongs to a purchase" do disputed_purchase = create(:purchase) expect(create(:dispute, purchase: disputed_purchase).disputable).to eq(disputed_purchase) end it "returns the associated charge if dispute belongs to a charge" do disputed_charge = create(:charge) expect(create(:dispute_on_charge, charge: disputed_charge).disputable).to eq(disputed_charge) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/creator_contacting_customers_email_info_spec.rb
spec/models/creator_contacting_customers_email_info_spec.rb
# frozen_string_literal: true require "spec_helper" describe CreatorContactingCustomersEmailInfo do describe "state transitions" do it "transitions to sent" do email_info = create(:creator_contacting_customers_email_info) email_info.update_attribute(:delivered_at, Time.current) expect(email_info.email_name).to eq "purchase_installment" email_info.mark_sent! expect(email_info.reload.state).to eq("sent") expect(email_info.reload.sent_at).to be_present expect(email_info.reload.delivered_at).to be_nil end it "transitions to delivered" do email_info = create(:creator_contacting_customers_email_info_sent) expect(email_info.sent_at).to be_present expect(email_info.delivered_at).to be_nil expect(email_info.opened_at).to be_nil email_info.mark_delivered! expect(email_info.reload.state).to eq("delivered") expect(email_info.reload.delivered_at).to be_present end it "transitions to opened" do email_info = create(:creator_contacting_customers_email_info_delivered) expect(email_info.sent_at).to be_present expect(email_info.delivered_at).to be_present expect(email_info.opened_at).to be_nil email_info.mark_opened! expect(email_info.reload.state).to eq("opened") expect(email_info.reload.opened_at).to be_present end it "transitions to bounced and then sent" do email_info = create(:creator_contacting_customers_email_info_sent) email_info.mark_bounced! expect(email_info.reload.state).to eq("bounced") expect(email_info.reload.sent_at).to be_present email_info.mark_sent! expect(email_info.reload.state).to eq("sent") expect(email_info.reload.sent_at).to be_present end end describe "#mark_bounced!" do it "attempts to unsubscribe the buyer of the purchase" do email_info = create(:creator_contacting_customers_email_info_sent) expect(email_info.purchase).to receive(:unsubscribe_buyer).and_call_original email_info.mark_bounced! end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/sku_spec.rb
spec/models/sku_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/max_purchase_count_concern" describe Sku do it_behaves_like "MaxPurchaseCount concern", :sku describe "sku_category_name" do before do link = create(:product) @variant_category_1 = create(:variant_category, link:, title: "Size") @variant_category_2 = create(:variant_category, link:, title: "Color") @sku = create(:sku, link:) end it "has the proper category name given 2 variants" do expect(@sku.sku_category_name).to eq "Size - Color" end it "has the proper category name given 1 variants" do @variant_category_2.update_attribute(:deleted_at, Time.current) expect(@sku.sku_category_name).to eq "Size" end end describe "as_json" do before do link = create(:product) @variant_category_1 = create(:variant_category, link:, title: "Size") @variant_category_2 = create(:variant_category, link:, title: "Color") @sku = create(:sku, link:, custom_sku: "customSKU") end it "includes custom_sku" do json = @sku.as_json(for_views: true) expect(json["custom_sku"]).to eq("customSKU") end it "does not include custom_sku if it does not exist" do @sku.update_attribute(:custom_sku, nil) json = @sku.as_json(for_views: true) expect(json["custom_sku"]).to be_nil end end describe "#to_option" do it "returns a hash of attributes for use in checkout" do sku = create(:sku, name: "Red") expect(sku.to_option).to eq( id: sku.external_id, name: sku.name, quantity_left: nil, description: "", price_difference_cents: 0, recurrence_price_values: nil, is_pwyw: false, duration_in_minutes: nil, ) end end describe "#to_option_for_product" do it "returns a hash of attributes" do sku = create(:sku, name: "Red") expect(sku.to_option_for_product).to eq( id: sku.external_id, name: sku.name, quantity_left: nil, description: "", price_difference_cents: 0, recurrence_price_values: nil, is_pwyw: false, duration_in_minutes: nil, ) end end describe "updating price_difference_cents" do let(:product) { create(:product) } let!(:sku) { create(:sku, link: product, custom_sku: "customSKU", price_difference_cents: 20) } it "enqueues Elasticsearch update if a price_difference_cents has changed" do expect(product).to receive(:enqueue_index_update_for).with(["available_price_cents"]) sku.update!(price_difference_cents: 10) end it "does not enqueue Elasticsearch update if prices have not changed" do expect(product).not_to receive(:enqueue_index_update_for).with(["available_price_cents"]) sku.update!(price_difference_cents: 20) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/thumbnail_spec.rb
spec/models/thumbnail_spec.rb
# frozen_string_literal: true require "spec_helper" describe Thumbnail do before do @product = create(:product) end describe "#validate_file" do it "does not save if no file attached" do thumbnail = Thumbnail.new(product: @product) expect(thumbnail.save).to eq(false) expect(thumbnail.errors.full_messages).to eq(["Could not process your thumbnail, please try again."]) end it "saves with a valid file attached" do thumbnail = Thumbnail.new(product: @product) blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "smilie.png") blob.analyze thumbnail.file.attach(blob) expect(thumbnail.save).to eq(true) expect(thumbnail.errors.full_messages).to be_empty end it "errors with invalid file attached" do thumbnail = Thumbnail.new(product: @product) thumbnail.file.attach(fixture_file_upload("blah.txt")) expect(thumbnail.save).to eq(false) expect(thumbnail.errors.full_messages).to eq(["Could not process your thumbnail, please try again."]) end it "errors with svg file attached" do thumbnail = Thumbnail.new(product: @product) thumbnail.file.attach(fixture_file_upload("test-svg.svg")) expect(thumbnail.save).to eq(false) expect(thumbnail.errors.full_messages).to eq(["Could not process your thumbnail, please try again."]) end it "errors with a large file attached" do thumbnail = Thumbnail.new(product: @product) blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("error_file.jpeg"), filename: "error_file.jpeg") blob.analyze thumbnail.file.attach(blob) expect(thumbnail.save).to eq(false) expect(thumbnail.errors.full_messages).to eq(["Could not process your thumbnail, please upload an image with size smaller than 5 MB."]) end it "errors with wrong dimensions" do thumbnail = Thumbnail.new(product: @product) blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("kFDzu.png"), filename: "kFDzu.png") blob.analyze thumbnail.file.attach(blob) expect(thumbnail.save).to eq(false) expect(thumbnail.errors.full_messages).to eq(["Please upload a square thumbnail."]) end context "marked deleted" do it "does not validate file" do thumbnail = Thumbnail.new(product: @product) thumbnail.deleted_at = Time.current expect(thumbnail.save).to eq(true) expect(thumbnail.errors.full_messages).to be_empty end end end describe "#alive" do it "returns nil if deleted" do thumbnail = Thumbnail.new(product: @product) thumbnail.deleted_at = Time.current expect(thumbnail.alive).to eq(nil) end it "returns self if alive?" do thumbnail = Thumbnail.new(product: @product) expect(thumbnail.alive).to eq(thumbnail) end end describe "#url" do it "returns url if file is attached" do thumbnail = Thumbnail.new(product: @product) blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "smilie.png") blob.analyze thumbnail.file.attach(blob) thumbnail.save! expect(thumbnail.url).to match(PUBLIC_STORAGE_S3_BUCKET) end it "returns original file instead of variant for gifs" do thumbnail = Thumbnail.new(product: @product) blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("test.gif"), filename: "test.gif") blob.analyze thumbnail.file.attach(blob) thumbnail.save! expect(thumbnail.url).to eq(thumbnail.file.url) end it "returns empty if no file attached" do thumbnail = Thumbnail.new(product: @product) expect(thumbnail.url).to eq(nil) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/order_spec.rb
spec/models/order_spec.rb
# frozen_string_literal: true require "spec_helper" describe Order do let(:product) { create(:product) } let(:purchase) { create(:purchase, link: product) } let(:order) { create(:order, purchases: [purchase]) } describe "#receipt_for_gift_receiver?" do context "when the purchase is not for a gift receiver" do it "returns false" do expect(order.receipt_for_gift_receiver?).to be(false) end end context "when the purchase is for a gift receiver" do let(:gift) { create(:gift) } let!(:gifter_purchase) { create(:purchase, link: gift.link, gift_given: gift, is_gift_sender_purchase: true) } let(:purchase) { create(:purchase, link: gift.link, gift_received: gift, is_gift_receiver_purchase: true) } it "returns true" do expect(order.receipt_for_gift_receiver?).to be(true) end end context "when there are multiple purchases per order" do let(:other_purchase) { create(:purchase) } before do order.purchases << other_purchase end it "raises" do expect { order.receipt_for_gift_receiver? }.to raise_error(NotImplementedError).with_message("Not supported for multi-item orders") end end end describe "#receipt_for_gift_sender?" do context "when the purchase is not for a gift sender" do it "returns false" do expect(order.receipt_for_gift_sender?).to be(false) end end context "when the purchase is for a gift sender" do let(:gift) { create(:gift) } before do purchase.update!(is_gift_sender_purchase: true, gift_given: gift) end it "returns true" do expect(order.receipt_for_gift_sender?).to be(true) end end context "when there are multiple purchases per order" do let(:other_purchase) { create(:purchase) } before do order.purchases << other_purchase end it "raises" do expect { order.receipt_for_gift_sender? }.to raise_error(NotImplementedError).with_message("Not supported for multi-item orders") end end end describe "#email" do it "returns the email of the purchase" do expect(order.email).to eq(purchase.email) end end describe "#locale" do it "returns the locale of the purchase" do expect(order.locale).to eq(purchase.locale) end end describe "#test?" do context "when the purchase is not a test purchase" do it "returns false" do expect(order.test?).to eq(false) end end context "when the purchase is a test purchase" do before do allow_any_instance_of(Purchase).to receive(:is_test_purchase?).and_return(true) end it "returns true" do expect(order.test?).to eq(true) end end end describe "#purchase_with_payment_as_orderable" do let(:purchase) { create(:failed_purchase) } let(:free_purchase) { create(:free_purchase) } before do order.purchases << free_purchase end context "without a successful paid purchase" do it "returns the free purchase" do expect(order.send(:purchase_with_payment_as_orderable)).to eq(free_purchase) end end context "with a successful paid purchase" do let(:paid_purchase) { create(:purchase) } before do order.purchases << paid_purchase end it "returns the paid purchase" do expect(order.send(:purchase_with_payment_as_orderable)).to eq(paid_purchase) end end end describe "Purchase attributes" do let(:purchase) { create(:failed_purchase) } let(:free_purchase) { create(:free_purchase) } let(:paid_purchase) { create(:purchase) } let(:physical_product) { create(:product, :is_physical) } let(:physical_purchase) { create(:physical_purchase, link: physical_product) } before do order.purchases << free_purchase order.purchases << paid_purchase order.purchases << physical_purchase end it "returns the correct purchase attributes" do expect(order.send(:purchase_as_orderable)).to eq(free_purchase) expect(order.send(:purchase_with_payment_as_orderable)).to eq(paid_purchase) expect(order.card_type).to eq(paid_purchase.card_type) expect(order.card_visual).to eq(paid_purchase.card_visual) end end describe "#purchase_as_orderable" do let(:purchase) { create(:failed_purchase) } let(:test_purchase) { create(:test_purchase) } let(:paid_purchase) { create(:purchase) } before do order.purchases << test_purchase order.purchases << paid_purchase end it "returns first successful purchase" do expect(order.send(:purchase_as_orderable)).to eq(test_purchase) end end describe "#send_charge_receipts", :vcr do let(:order) { create(:order) } let(:product_one) { create(:product) } let(:purchase_one) { create(:purchase, link: product_one) } let!(:charge_one) { create(:charge, order:, purchases: [purchase_one]) } let!(:charge_two) { create(:charge, order:, purchases: [create(:purchase)]) } let!(:failed_charge) { create(:charge, order:, purchases: [create(:failed_purchase)]) } it "sends charge receipts" do order.send_charge_receipts expect(SendChargeReceiptJob).to have_enqueued_sidekiq_job(charge_one.id).on("critical") expect(SendChargeReceiptJob).to have_enqueued_sidekiq_job(charge_two.id).on("critical") expect(SendChargeReceiptJob).not_to have_enqueued_sidekiq_job(failed_charge.id) end context "when a product has stampable PDFs" do before do product_one.product_files << create(:readable_document, pdf_stamp_enabled: true) purchase_one.create_url_redirect! end it "enqueues the job on the default job queue" do order.send_charge_receipts expect(SendChargeReceiptJob).to have_enqueued_sidekiq_job(charge_one.id).on("default") expect(SendChargeReceiptJob).to have_enqueued_sidekiq_job(charge_two.id).on("critical") expect(SendChargeReceiptJob).not_to have_enqueued_sidekiq_job(failed_charge.id) end end end describe "#successful_charges", :vcr do let(:order) { create(:order) } let!(:charge_one) { create(:charge, order:, purchases: [create(:purchase)]) } let!(:charge_two) { create(:charge, order:, purchases: [create(:purchase)]) } let!(:failed_charge) { create(:charge, order:, purchases: [create(:failed_purchase)]) } it "returns the successful charges" do expect(order.successful_charges).to eq([charge_one, charge_two]) end end describe "#unsubscribe_buyer" do it "calls unsubscribe_buyer on purchase" do allow_any_instance_of(Purchase).to receive(:unsubscribe_buyer).and_return("unsubscribed!") expect(order.unsubscribe_buyer).to eq("unsubscribed!") end end describe "#schedule_review_reminder!" do let(:order) { create(:order) } let(:purchase) { create(:purchase) } let(:cart) { create(:cart) } before do order.cart = cart end context "when there is a successful and eligible purchase" do it "schedules a review reminder" do expect(OrderReviewReminderJob).to receive(:perform_in).with(ProductReview::REVIEW_REMINDER_DELAY, order.id) order.purchases << purchase order.save end context "when review_reminder_scheduled_at is present" do before { order.update(review_reminder_scheduled_at: Time.current) } it "does not schedule a review reminder" do expect(OrderReviewReminderJob).not_to receive(:perform_in) order.purchases << purchase order.save end end context "when purchases require shipping" do let(:physical_product) { create(:product, :is_physical) } let(:physical_purchase) { create(:physical_purchase, link: physical_product) } it "schedules a reminder with REVIEW_REMINDER_PHYSICAL_DELAY" do expect(OrderReviewReminderJob).to receive(:perform_in).with(ProductReview::REVIEW_REMINDER_PHYSICAL_DELAY, order.id) order.purchases << physical_purchase order.save end end end context "when there are no successful purchases" do let(:purchase) { create(:purchase_in_progress) } it "does not schedule a review reminder" do expect(OrderReviewReminderJob).not_to receive(:perform_in) order.purchases << purchase order.save end end context "when there are successful purchases but none are eligible" do let(:ineligible_purchase) { create(:purchase, :with_review) } it "does not schedule a review reminder" do expect(OrderReviewReminderJob).not_to receive(:perform_in) order.purchases << ineligible_purchase order.save end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/canadian_bank_account_spec.rb
spec/models/canadian_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe CanadianBankAccount do describe "transit_number" do describe "is 5 digits" do let(:canadian_bank_account) { build(:canadian_bank_account, transit_number: "12345") } it "is valid" do expect(canadian_bank_account).to be_valid end end describe "nil" do let(:canadian_bank_account) { build(:canadian_bank_account, transit_number: nil) } it "is not valid" do expect(canadian_bank_account).not_to be_valid end end describe "is 4 digits" do let(:canadian_bank_account) { build(:canadian_bank_account, transit_number: "1234") } it "is not valid" do expect(canadian_bank_account).not_to be_valid end end describe "is 6 digits" do let(:canadian_bank_account) { build(:canadian_bank_account, transit_number: "123456") } it "is not valid" do expect(canadian_bank_account).not_to be_valid end end describe "contains alpha characters" do let(:canadian_bank_account) { build(:canadian_bank_account, transit_number: "1234a") } it "is not valid" do expect(canadian_bank_account).not_to be_valid end end end describe "institution_number" do describe "is 3 digits" do let(:canadian_bank_account) { build(:canadian_bank_account, institution_number: "123") } it "is valid" do expect(canadian_bank_account).to be_valid end end describe "nil" do let(:canadian_bank_account) { build(:canadian_bank_account, institution_number: nil) } it "is not valid" do expect(canadian_bank_account).not_to be_valid end end describe "is 2 digits" do let(:canadian_bank_account) { build(:canadian_bank_account, institution_number: "12") } it "is not valid" do expect(canadian_bank_account).not_to be_valid end end describe "is 4 digits" do let(:canadian_bank_account) { build(:canadian_bank_account, institution_number: "1234") } it "is not valid" do expect(canadian_bank_account).not_to be_valid end end describe "contains alpha characters" do let(:canadian_bank_account) { build(:canadian_bank_account, institution_number: "12a") } it "is not valid" do expect(canadian_bank_account).not_to be_valid end end end describe "routing_number" do let(:canadian_bank_account) { build(:canadian_bank_account, transit_number: "45678", institution_number: "123") } it "is a concat of institution_number, hyphen and transit_number" do expect(canadian_bank_account.routing_number).to eq("45678-123") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/subscription_spec.rb
spec/models/subscription_spec.rb
# frozen_string_literal: true require "spec_helper" describe Subscription, :vcr do include CurrencyHelper include ManageSubscriptionHelpers let(:seller) { create(:user) } before do @product = create(:subscription_product, user: seller, is_licensed: true) @subscription = create(:subscription, user: create(:user), link: @product) @purchase = create(:purchase, link: @product, email: @subscription.user.email, full_name: "squiddy", price_cents: @product.price_cents, is_original_subscription_purchase: true, subscription: @subscription, created_at: 2.days.ago) end describe "associations" do describe "#latest_plan_change" do it "returns the most recent, live plan change" do create(:subscription_plan_change, subscription: @subscription, created_at: 1.month.ago) most_recent = create(:subscription_plan_change, subscription: @subscription, created_at: 1.day.ago) create(:subscription_plan_change, subscription: @subscription, created_at: 1.week.ago) create(:subscription_plan_change, subscription: @subscription, created_at: 1.hour.ago, deleted_at: Time.current) expect(@subscription.latest_plan_change).to eq most_recent end end describe "#latest_applicable_plan_change" do it "returns the most recent, live plan change that is applicable" do create(:subscription_plan_change, subscription: @subscription, created_at: 2.weeks.ago, deleted_at: 1.week.ago) create(:subscription_plan_change, subscription: @subscription, created_at: 10.days.ago, applied: true) create(:subscription_plan_change, subscription: @subscription, created_at: 5.days.ago, for_product_price_change: true, effective_on: 1.week.from_now) create(:subscription_plan_change, subscription: @subscription, created_at: 4.days.ago, for_product_price_change: true, effective_on: 2.days.ago, notified_subscriber_at: nil) create(:subscription_plan_change, subscription: @subscription, created_at: 3.days.ago, for_product_price_change: true, effective_on: 1.day.ago, notified_subscriber_at: 1.day.ago, deleted_at: 12.hours.ago) create(:subscription_plan_change, subscription: @subscription, created_at: 2.days.ago, for_product_price_change: true, effective_on: 1.day.ago, notified_subscriber_at: 1.day.ago, applied: true) most_recent = create(:subscription_plan_change, subscription: @subscription, created_at: 1.day.ago, for_product_price_change: true, effective_on: 1.day.ago, notified_subscriber_at: 1.day.ago) expect(@subscription.latest_applicable_plan_change).to eq most_recent end end end describe "lifecycle hooks" do describe "create_interruption_event", :freeze_time do it "records a deactivated event if deactivated_at is set and was previously blank" do first_deactivation = 1.week.ago expect do @subscription.update!(deactivated_at: first_deactivation) expect(@subscription.reload.subscription_events.deactivated.last.occurred_at).to eq first_deactivation end.to change { @subscription.reload.subscription_events.deactivated.count }.from(0).to(1) expect do @subscription.update!(deactivated_at: Time.current) expect(@subscription.reload.subscription_events.deactivated.last.occurred_at).to eq first_deactivation end.not_to change { @subscription.reload.subscription_events.deactivated.count } expect do create(:subscription, deactivated_at: Time.current) end.to change { SubscriptionEvent.deactivated.count }.from(1).to(2) end it "records a restarted event if deactivated_at is cleared" do @subscription.update!(deactivated_at: Time.current) expect do @subscription.update!(deactivated_at: nil) expect(@subscription.reload.subscription_events.restarted.last.occurred_at).to eq Time.current end.to change { @subscription.reload.subscription_events.restarted.count }.from(0).to(1) end it "does nothing if deactivated_at has not changed" do expect do @subscription.update!(failed_at: Time.current) end.not_to change { @subscription.reload.subscription_events.count } end end describe "send_ended_notification_webhook" do it "sends a 'subscription_ended' notification if the subscription has just been deactivated" do @subscription.update!(deactivated_at: Time.current) expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(nil, nil, ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME, @subscription.id) end it "does not send a 'subscription_ended' notification if the subscription was already deactivated" do @subscription.update!(deactivated_at: Time.current) Sidekiq::Worker.clear_all @subscription.update!(deactivated_at: Time.current) expect(PostToPingEndpointsWorker).not_to have_enqueued_sidekiq_job(nil, nil, ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME, @subscription.id) end it "does not send a 'subscription_ended' notification if the subscription is not deactivated" do @subscription.update!(cancelled_at: Time.current) expect(PostToPingEndpointsWorker).not_to have_enqueued_sidekiq_job(nil, nil, ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME, @subscription.id) end end describe "creation" do it "sets the seller" do expect(@subscription.seller).to eq(@purchase.seller) end end end describe "scopes" do describe ".active_without_pending_cancel" do subject { described_class.active_without_pending_cancel } it "returns only active subscriptions" do is_expected.to contain_exactly(@subscription) end context "when subscription is a test" do before do @subscription.update!(is_test_subscription: true) end it { is_expected.to be_empty } end context "when subscription has failed" do before do @subscription.update!(failed_at: 1.minute.ago) end it { is_expected.to be_empty } end context "when subscription has ended" do before do @subscription.update!(ended_at: 1.minute.ago) end it { is_expected.to be_empty } end context "when subscription was cancelled" do before do @subscription.update!(cancelled_at: 1.minute.ago) end it { is_expected.to be_empty } end context "when subscription is pending cancellation" do before do @subscription.update!(cancelled_at: 1.minute.from_now) end it { is_expected.to be_empty } end end end describe "#as_json" do it "returns the expected JSON representation" do expected = { id: @subscription.external_id, email: @subscription.email, product_id: @subscription.link.external_id, product_name: @subscription.link.name, user_id: @subscription.user.external_id, user_email: @subscription.user.email, purchase_ids: @subscription.purchases.map(&:external_id), created_at: @subscription.created_at, cancelled_at: @subscription.cancelled_at, user_requested_cancellation_at: @subscription.user_requested_cancellation_at, charge_occurrence_count: @subscription.charge_occurrence_count, recurrence: @subscription.recurrence, ended_at: @subscription.ended_at, failed_at: @subscription.failed_at, free_trial_ends_at: @subscription.free_trial_ends_at, status: @subscription.status } expect(@subscription.as_json).to eq(expected) end it "excludes 'not_charged' plan change purchases" do purchase = create(:purchase, link: @product, subscription: @subscription, purchase_state: "not_charged") expect(@subscription.as_json[:purchase_ids]).not_to include purchase.external_id end it "excludes failed purchases" do failed_purchase = create(:failed_purchase, link: @product, subscription: @subscription) expect(@subscription.as_json[:purchase_ids]).not_to include failed_purchase.external_id end it "includes free trial 'not_charged' purchases" do purchase = create(:free_trial_membership_purchase) expect(purchase.subscription.as_json[:purchase_ids]).to eq [purchase.external_id] end it "includes license_key for membership products with licensing enabled" do license = create(:license, link: @product, purchase: @purchase) expect(@subscription.as_json[:license_key]).to eq license.serial end end describe "#subscription_mobile_json_data" do before do travel_to Time.current @product = create(:subscription_product, user: create(:user)) @user = create(:user, credit_card: create(:credit_card)) @very_old_installment = create(:installment, name: "very old installment", link: @product, created_at: 5.months.ago, published_at: 5.months.ago) @old_installment = create(:installment, name: "old installment", link: @product, created_at: 4.months.ago, published_at: 4.months.ago) @new_installment = create(:installment, name: "new installment", link: @product, created_at: Time.current, published_at: Time.current) @unpublished_installment = create(:installment, link: @product, published_at: nil) @workflow = create(:workflow, seller: @product.user, link: @product, created_at: 13.months.ago, published_at: 13.months.ago) @workflow_installment = create(:installment, name: "workflow installment", link: @product, workflow: @workflow, published_at: 13.months.ago) @workflow_installment_rule = create(:installment_rule, installment: @workflow_installment, delayed_delivery_time: 1.day) @subscription = create(:subscription, link: @product, user: @user, created_at: 1.year.ago) @purchase = create(:purchase, is_original_subscription_purchase: true, link: @product, subscription: @subscription, purchaser: @user, created_at: @subscription.created_at) end it "returns nothing if the subscription is no longer alive" do @subscription.cancel_effective_immediately! expect(@subscription.subscription_mobile_json_data).to eq nil end it "returns the correct json format for the mobile api" do create(:creator_contacting_customers_email_info, purchase: @purchase, installment: @workflow_installment) create(:creator_contacting_customers_email_info, purchase: @purchase, installment: @very_old_installment) create(:creator_contacting_customers_email_info, purchase: @purchase, installment: @old_installment) create(:creator_contacting_customers_email_info, purchase: @purchase, installment: @new_installment) [@subscription, @purchase, @product].each(&:reload) subscription_mobile_json_data = @subscription.subscription_mobile_json_data.to_json expected_subscription_data = @product.as_json(mobile: true) subscription_data = { subscribed_at: @subscription.created_at, external_id: @subscription.external_id, recurring_amount: @subscription.original_purchase.formatted_display_price } expected_subscription_data[:subscription_data] = subscription_data expected_subscription_data[:purchase_id] = @purchase.external_id expected_subscription_data[:purchased_at] = @purchase.created_at expected_subscription_data[:user_id] = @purchase.purchaser.external_id expected_subscription_data[:can_contact] = @purchase.can_contact expected_subscription_data[:updates_data] = @subscription.updates_mobile_json_data expect(@subscription.subscription_mobile_json_data[:updates_data].length).to eq 4 expected_updates_data = [ @workflow_installment.installment_mobile_json_data(purchase: @purchase, subscription: @subscription), @very_old_installment.installment_mobile_json_data(purchase: @purchase, subscription: @subscription), @old_installment.installment_mobile_json_data(purchase: @purchase, subscription: @subscription), @new_installment.installment_mobile_json_data(purchase: @purchase, subscription: @subscription) ] expect(@subscription.subscription_mobile_json_data[:updates_data].sort_by { |h| h[:name] }.to_json).to eq expected_updates_data.sort_by { |h| h[:name] }.to_json expect(subscription_mobile_json_data).to eq expected_subscription_data.to_json end it "includes the first installment for new subscribers if the creator set should_include_last_post to true" do product = create(:membership_product) product.should_include_last_post = true product.save! user = create(:user) installment = create(:installment, link: product, published_at: 1.day.ago) subscription = create(:subscription, link: product, user:) purchase = create(:purchase, is_original_subscription_purchase: true, link: product, subscription:, purchaser: user) create(:creator_contacting_customers_email_info, purchase:, installment:) expect(subscription.updates_mobile_json_data.length).to eq 1 expect(subscription.updates_mobile_json_data.first[:external_id]).to eq installment.external_id end end describe "#credit_card_to_charge" do context "when test subscription" do it "returns nil" do user = create(:user, credit_card: create(:credit_card)) product = create(:subscription_product, user:) subscription = create(:subscription, link: product, user:, is_test_subscription: true) expect(subscription.credit_card_to_charge).to be_nil end end context "when guest subscription purchase" do it "returns the credit card used with the original purchase" do user = create(:user) product = create(:subscription_product, user:) original_purchase_card = create(:credit_card) subscription = create(:subscription, link: product, user: nil, credit_card: original_purchase_card) expect(subscription.credit_card_to_charge).to eq(original_purchase_card) end end context "when user has a card saved on file and doesn't have a card in the purchase" do it "returns the card saved on file, not the card used during purchase" do buyers_card = create(:credit_card) user = create(:user, credit_card: buyers_card) product = create(:subscription_product, user:) subscription = create(:subscription, link: product, user:) expect(subscription.credit_card_to_charge).to eq(buyers_card) end end context "when user has a card associated to the subscription" do it "returns the subscription's card" do buyers_card = create(:credit_card) subscription_card = create(:credit_card) user = create(:user, credit_card: buyers_card) product = create(:subscription_product, user:) subscription = create(:subscription, link: product, user:, credit_card: subscription_card) expect(subscription.credit_card_to_charge).to eq(subscription_card) end end end describe "#installments" do before do @product = create(:subscription_product, user: create(:user)) @user = create(:user, credit_card: create(:credit_card)) @subscription = create(:subscription, link: @product, user: @user, created_at: 3.days.ago) @purchase = create(:purchase, is_original_subscription_purchase: true, link: @product, subscription: @subscription, purchaser: @user) @very_old_installment = create(:installment, link: @product, created_at: 5.months.ago, published_at: 5.months.ago) @old_installment = create(:installment, link: @product, created_at: 4.months.ago, published_at: 4.months.ago) @new_installment = create(:installment, link: @product, published_at: Time.current) @unpublished_installment = create(:installment, link: @product, published_at: nil) end it "returns the installments made after subscription created, plus the last one made before the subscription if link option is set" do @product.update_attribute(:should_include_last_post, true) expect(@subscription.installments).to eq [@old_installment, @new_installment] end it "returns the installments made after subscription created, plus the last one made before the subscription if link option is set, ordered with published_at date" do @product.update_attribute(:should_include_last_post, true) old_installment1 = create(:installment, link: @product, published_at: 4.days.ago) create(:installment, link: @product, published_at: 5.days.ago) expect(@subscription.installments).to eq [old_installment1, @new_installment] end it "returns the installments made after subscription created without the last one made before the subscription if link option is not set" do expect(@subscription.installments).to eq [@new_installment] end it "does not include unpublished installments" do expect(@subscription.installments).to_not include @unpublished_installment end it "does not include any installment older than the last installment before the creation of the subscription" do expect(@subscription.installments).to_not include @very_old_installment end describe "cancelled subscriptions" do before do @product = create(:subscription_product, user: create(:user), is_recurring_billing: true) @user = create(:user, credit_card: create(:credit_card)) @subscription = create(:subscription, link: @product, user: @user, created_at: 5.months.ago, cancelled_at: 3.months.ago) @purchase = create(:purchase, is_original_subscription_purchase: true, link: @product, subscription: @subscription, purchaser: @user) @very_old_installment = create(:installment, link: @product, created_at: 7.months.ago, published_at: 7.months.ago) @old_installment = create(:installment, link: @product, created_at: 6.months.ago, published_at: 6.months.ago) @correct_installment = create(:installment, link: @product, created_at: 4.months.ago, published_at: 4.months.ago) @current_installment = create(:installment, link: @product, created_at: Time.current, published_at: Time.current) end it "returns installment created while subscription active, plus the last installment before the subscription was created" do expect(@subscription.installments).to eq [@correct_installment] end it "does not include any installment older than the last installment before the creation of the subscription if link option is set" do @product.update_attribute(:should_include_last_post, true) expect(@subscription.installments).to_not include @very_old_installment expect(@subscription.installments).to include @old_installment end it "does not include any past installments if link option is not set" do expect(@subscription.installments).to_not include @old_installment end it "does not return installments created after subscription cancelled" do expect(@subscription.installments).to_not include @current_installment end end describe "failed subscriptions" do before do @product = create(:subscription_product, user: create(:user), is_recurring_billing: true) @user = create(:user, credit_card: create(:credit_card)) @subscription = create(:subscription, link: @product, user: @user, created_at: 5.months.ago, failed_at: 3.months.ago) @purchase = create(:purchase, is_original_subscription_purchase: true, link: @product, subscription: @subscription, purchaser: @user) @old_installment = create(:installment, link: @product, created_at: 6.months.ago, published_at: 6.months.ago) @very_old_installment = create(:installment, link: @product, created_at: 7.months.ago, published_at: 7.months.ago) @correct_installment = create(:installment, link: @product, created_at: 4.months.ago, published_at: 4.months.ago) @end_of_month_failed = create(:installment, link: @product, created_at: 3.months.ago.at_end_of_month, published_at: 3.months.ago.at_end_of_month) @current_installment = create(:installment, link: @product, created_at: Time.current, published_at: Time.current) end it "returns installment created while subscription active, plus the last installment before the subscription was created if link option is set" do @product.update_attribute(:should_include_last_post, true) expect(@subscription.installments).to eq [@old_installment, @correct_installment] end it "returns only the installment created while subscription active if link option is not set" do expect(@subscription.installments).to eq [@correct_installment] end it "does not include any installment older than the last installment before the creation of the subscription" do expect(@subscription.installments).to_not include @very_old_installment end it "does not return installment created in the month that subscription failed" do expect(@subscription.installments).to_not include @end_of_month_cancelled end it "does not return installments created after subscription failed" do expect(@subscription.installments).to_not include @current_installment end end describe "workflow installments" do before do @product = create(:subscription_product, user: create(:user), is_recurring_billing: true) @user = create(:user, credit_card: create(:credit_card)) @workflow = create(:workflow, seller: @product.user, link: @product, published_at: 1.week.ago) @workflow_installment = create(:installment, link: @product, workflow: @workflow, published_at: Time.current) @workflow_installment_rule = create(:installment_rule, installment: @workflow_installment, delayed_delivery_time: 1.day) @subscription = create(:subscription, link: @product, user: @user, created_at: 5.months.ago, failed_at: 3.months.ago) @purchase = create(:purchase, is_original_subscription_purchase: true, link: @product, subscription: @subscription, purchaser: @user) end it "does not include any workflow installment" do expect(@subscription.installments.length).to eq 0 end end end describe "#charge!" do before do @subscription.user.update!(credit_card: create(:credit_card)) end it "creates a new purchase row", :vcr do expect do @subscription.charge! end.to change { Purchase.count }.by(1) end it "gives new purchase right attributes", :vcr do @new_purchase = @subscription.charge! expect(@new_purchase.purchase_state).to eq "successful" expect(@new_purchase.subscription).to eq @subscription expect(@new_purchase.link).to eq @product expect(@new_purchase.email).to eq @purchase.email expect(@new_purchase.full_name).to eq @purchase.full_name expect(@new_purchase.ip_address).to eq @purchase.ip_address expect(@new_purchase.ip_country).to eq @purchase.ip_country expect(@new_purchase.ip_state).to eq @purchase.ip_state expect(@new_purchase.referrer).to eq @purchase.referrer expect(@new_purchase.browser_guid).to eq @purchase.browser_guid expect(@new_purchase.is_original_subscription_purchase).to be(false) expect(@new_purchase.price_cents).to eq @product.price_cents end it "charges stripe", :vcr do @subscription.charge! end it "creates a purchase event", :vcr do create(:event, purchase_id: @purchase.id, email: @purchase.email) recurring_purchase = @subscription.charge! purchase_event = Event.last expect(purchase_event.is_recurring_subscription_charge).to be(true) expect(purchase_event.purchase_id).to eq recurring_purchase.id expect(purchase_event.email).to eq @purchase.email end it "uses the previously saved payment instrument to charge an unregistered user's subscription" do discover_cc = CreditCard.create(build(:chargeable, card: StripePaymentMethodHelper.success_discover)) subscription = nil travel_to(1.month.ago) do subscription = create(:subscription, user: nil, link: @product, credit_card: discover_cc) create(:purchase, is_original_subscription_purchase: true, link: @product, subscription:, credit_card: discover_cc) end expect { subscription.charge! }.to change { Purchase.count }.by(1) subscription.reload latest_purchase = Purchase.last expect(latest_purchase.purchase_state).to eq "successful" expect(latest_purchase.card_visual).to eq "**** **** **** 9424" expect(subscription.credit_card).to eq(discover_cc) expect(subscription.credit_card).to eq(latest_purchase.credit_card) end it "uses the previously saved payment instrument to charge a registered user's subscription", :vcr do user = create(:user) discover_cc = CreditCard.create(build(:chargeable, card: StripePaymentMethodHelper.success_discover)) user.credit_card = discover_cc user.save! subscription = nil travel_to(1.month.ago) do subscription = create(:subscription, user:, link: @product, credit_card: discover_cc) create(:purchase, is_original_subscription_purchase: true, link: @product, subscription:, credit_card: discover_cc) end expect { subscription.charge! }.to change { Purchase.count }.by(1) subscription.reload latest_purchase = Purchase.last expect(latest_purchase.purchase_state).to eq "successful" expect(latest_purchase.card_visual).to eq "**** **** **** 9424" expect(subscription.credit_card).to eq(discover_cc) expect(subscription.credit_card).to eq(latest_purchase.credit_card) end it "uses the payment instrument attached to the subscription in case the purchaser account does not have a saved payment instrument", :vcr do user = create(:user) discover_cc = CreditCard.create(build(:chargeable, card: StripePaymentMethodHelper.success_discover), nil, user) subscription = nil travel_to(1.month.ago) do subscription = create(:subscription, user:, link: @product, credit_card: discover_cc) create(:purchase, is_original_subscription_purchase: true, link: @product, subscription:, credit_card: discover_cc) end expect { subscription.charge! }.to change { Purchase.count }.by(1) subscription.reload latest_purchase = Purchase.last expect(latest_purchase.purchase_state).to eq "successful" expect(latest_purchase.card_visual).to eq "**** **** **** 9424" expect(subscription.credit_card).to eq(discover_cc) expect(subscription.credit_card).to eq(latest_purchase.credit_card) end context "with an Indian credit card", :vcr do let(:buyer) { create(:user) } let(:indian_cc) do chargeable = build(:chargeable, card:) card = CreditCard.create(chargeable, nil, buyer) card.update!(card_params) card end let(:product) do create(:membership_product_with_preset_tiered_pricing, recurrence_price_values: [ { "monthly": { enabled: true, price: 5 } }, { "monthly": { enabled: true, price: 8 } } ]) end let(:subscription) { create(:subscription, link: product, user: buyer, credit_card: indian_cc) } before do create(:membership_purchase, is_original_subscription_purchase: true, link: product, variant_attributes: [product.default_tier], price_cents: 5_00, subscription:, purchaser: buyer, credit_card: indian_cc) end context "with a successful mandate" do let(:card) { StripePaymentMethodHelper.success_indian_card_mandate } let(:card_params) do { json_data: { stripe_payment_intent_id: "pi_3SOdR0IBOqvOFDrf1MBxDys4" }, processor_payment_method_id: "pm_1SOdQxIBOqvOFDrfANv6cZO4", stripe_customer_id: "cus_TLK5KncEpdGdIH", } end it "uses the mandate associated with the saved credit card to successfully charge" do expect { subscription.charge! }.to change { Purchase.count }.by(1) subscription.reload latest_purchase = Purchase.last expect(latest_purchase.purchase_state).to eq "in_progress" expect(subscription.credit_card).to eq(indian_cc) expect(subscription.credit_card).to eq(latest_purchase.credit_card) end end context "with a cancelled mandate" do let(:card) { StripePaymentMethodHelper.cancelled_indian_card_mandate } let(:card_params) do { json_data: { stripe_payment_intent_id: "pi_3SOdsrIBOqvOFDrf1VLLMqSi" }, processor_payment_method_id: "pm_1SOdsoIBOqvOFDrfq67sVBc6", stripe_customer_id: "cus_TLKXDRZTbaggkA", } end it "uses the mandate associated with the saved credit card and fails" do expect { subscription.charge! }.to change { Purchase.count }.by(1) subscription.reload latest_purchase = Purchase.last expect(latest_purchase.purchase_state).to eq "failed" expect(latest_purchase.stripe_error_code).to eq "india_recurring_payment_mandate_canceled" expect(subscription.credit_card).to eq(indian_cc) expect(subscription.credit_card).to eq(latest_purchase.credit_card) end end end it "uses the payment instrument attached to the subscription in case the purchaser account's saved payment instrument is not supported by this creator", :vcr do user = create(:user) native_paypal_card = CreditCard.create(build(:native_paypal_chargeable), nil, user) user.credit_card = native_paypal_card user.save! discover_cc = CreditCard.create(build(:chargeable, card: StripePaymentMethodHelper.success_discover), nil, user) subscription = nil travel_to(1.month.ago) do subscription = create(:subscription, user:, link: @product, credit_card: discover_cc) create(:purchase, is_original_subscription_purchase: true, link: @product, subscription:, credit_card: discover_cc) end expect { subscription.charge! }.to change { Purchase.count }.by(1) subscription.reload expect(subscription.purchases.count).to eq 2 latest_purchase = subscription.purchases.last expect(latest_purchase.purchase_state).to eq "successful" expect(latest_purchase.card_visual).to eq "**** **** **** 9424" expect(subscription.credit_card).to eq(discover_cc) expect(subscription.credit_card).to eq(latest_purchase.credit_card) travel_to(1.month.from_now) do # Creator adds support for native paypal payments create(:merchant_account_paypal, user: @product.user, charge_processor_merchant_id: "CJS32DZ7NDN5L", currency: "gbp") expect { subscription.charge! }.to change { Purchase.count }.by(1) subscription.reload expect(subscription.purchases.count).to eq 3 latest_purchase = subscription.purchases.last expect(latest_purchase.purchase_state).to eq "successful" expect(latest_purchase.credit_card).to eq(discover_cc) end end it "transfers VAT ID and elected tax country from the original purchase to recurring charge" do create(:zip_tax_rate, country: "IT", zip_code: nil, state: nil, combined_rate: 0.22, is_seller_responsible: false) subscription = create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: @product) original_purchase = build(:purchase, is_original_subscription_purchase: true, link: @product, subscription:, chargeable: build(:chargeable), purchase_state: "in_progress", full_name: "gum stein", ip_address: "2.47.255.255", country: "Italy", created_at: 2.days.ago) original_purchase.business_vat_id = "IE6388047V" original_purchase.process! expect(original_purchase.reload.gumroad_tax_cents).to eq 0 subscription.charge! charge_purchase = subscription.reload.purchases.last expect(charge_purchase.purchase_state).to eq "successful"
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/ecuador_bank_account_spec.rb
spec/models/ecuador_bank_account_spec.rb
# frozen_string_literal: true describe EcuadorBankAccount do describe "#bank_account_type" do it "returns EC" do expect(create(:ecuador_bank_account).bank_account_type).to eq("EC") end end describe "#country" do it "returns EC" do expect(create(:ecuador_bank_account).country).to eq("EC") end end describe "#currency" do it "returns usd" do expect(create(:ecuador_bank_account).currency).to eq("usd") end end describe "#routing_number" do it "returns valid for 8 to 11 characters" do expect(create(:ecuador_bank_account, bank_code: "AAAAECE1")).to be_valid expect(create(:ecuador_bank_account, bank_code: "AAAAECE1X")).to be_valid expect(create(:ecuador_bank_account, bank_code: "AAAAECE1XX")).to be_valid expect(create(:ecuador_bank_account, bank_code: "AAAAECE1XXX")).to be_valid end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:ecuador_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:ecuador_bank_account)).to be_valid expect(build(:ecuador_bank_account, account_number: "000123456789")).to be_valid expect(build(:ecuador_bank_account, account_number: "00012")).to be_valid expect(build(:ecuador_bank_account, account_number: "000123456789101112")).to be_valid ec_bank_account = build(:ecuador_bank_account, account_number: "EC12345") expect(ec_bank_account).to_not be_valid expect(ec_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ec_bank_account = build(:ecuador_bank_account, account_number: "EC61109010140000071219812874") expect(ec_bank_account).to_not be_valid expect(ec_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ec_bank_account = build(:ecuador_bank_account, account_number: "8937040044053201300") expect(ec_bank_account).to_not be_valid expect(ec_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") ec_bank_account = build(:ecuador_bank_account, account_number: "CRABCDE") expect(ec_bank_account).to_not be_valid expect(ec_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/service_charge_spec.rb
spec/models/service_charge_spec.rb
# frozen_string_literal: true require "spec_helper" describe ServiceCharge, :vcr do describe "scopes" do describe "successful" do before do @successful_service_charge = create(:service_charge, state: "successful") @failed_service_charge = create(:service_charge, state: "failed") end it "returns successful service_charges" do expect(ServiceCharge.successful).to include @successful_service_charge end it "does not return failed service_charges" do expect(ServiceCharge.successful).to_not include @failed_service_charge end end describe "failed" do before do @successful_service_charge = create(:service_charge, state: "successful") @failed_service_charge = create(:service_charge, state: "failed") end it "does not returns successful service_charges" do expect(ServiceCharge.failed).to_not include @successful_service_charge end it "does return failed service_charges" do expect(ServiceCharge.failed).to include @failed_service_charge end end describe "refunded" do before do @refunded_service_charge = create(:service_charge, charge_processor_refunded: true) @non_refunded_service_charge = create(:service_charge) end it "returns refunded service_charges" do expect(ServiceCharge.refunded).to include @refunded_service_charge end it "does not return non-refunded service_charges" do expect(ServiceCharge.refunded).to_not include @non_refunded_service_charge end end describe "not_refunded" do before do @refunded_service_charge = create(:service_charge, charge_processor_refunded: true) @non_refunded_service_charge = create(:service_charge) end it "returns non-refunded service_charges" do expect(ServiceCharge.not_refunded).to include @non_refunded_service_charge end it "does not return refunded service_charges" do expect(ServiceCharge.not_refunded).to_not include @refunded_service_charge end end describe "not_chargedback" do before do @chargebacked_service_charge = create(:service_charge, chargeback_date: Date.yesterday) @reversed_chargebacked_service_charge = create(:service_charge, chargeback_date: Date.yesterday, chargeback_reversed: true) @non_chargebacked_service_charge = create(:service_charge) end it "does not return chargebacked service_charge" do expect(ServiceCharge.not_chargedback).to_not include @chargebacked_service_charge expect(ServiceCharge.not_chargedback).to_not include @reversed_chargebacked_service_charge end it "returns non-chargebacked service_charge" do expect(ServiceCharge.not_chargedback).to include @non_chargebacked_service_charge expect(ServiceCharge.not_chargedback).to_not include @reversed_chargebacked_service_charge end end end describe "mongoable" do it "puts service_charge in mongo on creation" do @service_charge = build(:service_charge) @service_charge.save expect(SaveToMongoWorker).to have_enqueued_sidekiq_job("ServiceCharge", anything) end end describe "#mark_successful" do it "marks the service_charge as successful" do travel_to(Time.current) do service_charge = create(:service_charge, state: "in_progress") service_charge.mark_successful expect(service_charge.state).to eq("successful") expect(service_charge.succeeded_at.to_s).to eq(Time.current.to_s) end end end describe "mark_failed" do it "marks the service_charge as failed" do service_charge = create(:service_charge, state: "in_progress") service_charge.mark_failed expect(service_charge.state).to eq("failed") end end describe "email" do it "gets email from user" do user = create(:user) service_charge = create(:service_charge, user:) expect(service_charge.email).to eq user.email end end describe "as_json method" do before do @user = create(:user) @service_charge = create(:service_charge, chargeback_date: 1.minute.ago, user: @user) end it "has the right keys" do %i[charge_cents formatted_charge timestamp user_id chargedback].each do |key| expect(@service_charge.as_json.key?(key)).to be(true) end end end describe "#discount_amount" do before do @user = create(:user) @black_recurring_service = create(:black_recurring_service, user: @user) @service_charge = create(:free_service_charge, user: @user, recurring_service: @black_recurring_service, discount_code: DiscountCode::INVITE_CREDIT_DISCOUNT_CODE) end it "returns the right amount for invite discount" do expect(@service_charge.discount_amount).to eq("$10") end end describe "#upload_invoice_pdf" do before(:each) do @s3_object = Aws::S3::Resource.new.bucket("gumroad-specs").object("specs/service_charge-invoice-spec-#{SecureRandom.hex(18)}") s3_bucket_double = double allow(Aws::S3::Resource).to receive_message_chain(:new, :bucket).with(INVOICES_S3_BUCKET).and_return(s3_bucket_double) expect(s3_bucket_double).to receive_message_chain(:object).and_return(@s3_object) end it "writes the passed file to S3 and returns the S3 object" do service_charge = create(:service_charge) file = File.open(Rails.root.join("spec", "support", "fixtures", "smaller.png")) result = service_charge.upload_invoice_pdf(file) expect(result).to be(@s3_object) expect(result.content_length).to eq(file.size) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/payment_option_spec.rb
spec/models/payment_option_spec.rb
# frozen_string_literal: true require "spec_helper" describe PaymentOption do describe "validation" do it "considers a PaymentOption to be invalid unless all required information is provided" do payment_option = PaymentOption.new expect(payment_option.valid?).to eq false product = create(:subscription_product) subscription = create(:subscription, link: product) payment_option.subscription = subscription expect(payment_option.valid?).to eq false payment_option.price = product.prices.last expect(payment_option.valid?).to eq true end it "requires installment_plan when subscription is an installment plan" do subscription = create(:subscription, is_installment_plan: false) payment_option = build(:payment_option, subscription:, installment_plan: nil) expect(payment_option.valid?).to eq true subscription.update!(is_installment_plan: true) expect(payment_option.valid?).to eq false installment_plan = build(:product_installment_plan) payment_option.installment_plan = installment_plan expect(payment_option.valid?).to eq true end end describe "#update_subscription_last_payment_option" do it "sets correct payment_option on creation and destruction" do subscription = create(:subscription) payment_option_1 = create(:payment_option, subscription:) expect(subscription.reload.last_payment_option).to eq(payment_option_1) payment_option_2 = create(:payment_option, subscription:) payment_option_3 = create(:payment_option, subscription:) expect(subscription.reload.last_payment_option).to eq(payment_option_3) payment_option_3.destroy expect(subscription.reload.last_payment_option).to eq(payment_option_2) payment_option_2.mark_deleted! expect(subscription.reload.last_payment_option).to eq(payment_option_1) payment_option_2.mark_undeleted! expect(subscription.reload.last_payment_option).to eq(payment_option_2) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/call_availability_spec.rb
spec/models/call_availability_spec.rb
# frozen_string_literal: true describe CallAvailability do describe "normalizations" do it "drops sub-minute precision from start_time and end_time when assigning" do call_availability = build( :call_availability, start_time: DateTime.parse("May 1 2024 10:28:01.123456 UTC"), end_time: DateTime.parse("May 1 2024 11:29:59.923456 UTC") ) expect(call_availability.start_time).to eq(DateTime.parse("May 1 2024 10:28:00 UTC")) expect(call_availability.end_time).to eq(DateTime.parse("May 1 2024 11:29:00 UTC")) end it "drops sub-minute precision from start_time and end_time when querying" do call_availability = create( :call_availability, start_time: DateTime.parse("May 1 2024 10:28:01.123456 UTC"), end_time: DateTime.parse("May 1 2024 11:29:59.923456 UTC") ) expect(CallAvailability.find_by(start_time: call_availability.start_time.change(sec: 2))).to eq(call_availability) expect(CallAvailability.find_by(end_time: call_availability.end_time.change(sec: 58))).to eq(call_availability) end end describe "validations" do let!(:call_availability) { build(:call_availability) } context "end time is before start time" do it "adds an error" do call_availability.end_time = call_availability.start_time - 1.hour expect(call_availability).not_to be_valid expect(call_availability.errors.full_messages).to eq(["Start time must be before end time."]) end end end describe "scopes", :freeze_time do let!(:not_started) { create(:call_availability, start_time: 1.day.from_now, end_time: 2.days.from_now) } let!(:started_but_not_ended) { create(:call_availability, start_time: 2.days.ago, end_time: 2.day.from_now) } let!(:ended) { create(:call_availability, start_time: 2.days.ago, end_time: 1.day.ago) } describe ".upcoming" do it "returns call availabilities that hasn't ended" do expect(CallAvailability.upcoming).to contain_exactly(started_but_not_ended, not_started) end end describe ".ordered_chronologically" do it "orders by start time and end time" do expect(CallAvailability.ordered_chronologically.pluck(:id)).to eq( [ended.id, started_but_not_ended.id, not_started.id] ) end end describe ".containing" do it "returns call availabilities that strictly contain the given time range" do expect(CallAvailability.containing(not_started.start_time, not_started.end_time)) .to contain_exactly(not_started, started_but_not_ended) expect(CallAvailability.containing(not_started.start_time - 1.second, not_started.end_time)) .to contain_exactly(started_but_not_ended) expect(CallAvailability.containing(not_started.start_time, not_started.end_time + 1.second)) .to be_empty end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/product_installment_plan_spec.rb
spec/models/product_installment_plan_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe ProductInstallmentPlan do subject(:product_installment_plan) { build(:product_installment_plan) } describe "validations" do it { is_expected.to validate_presence_of(:number_of_installments) } it { is_expected.to validate_numericality_of(:number_of_installments).only_integer.is_greater_than(1) } end describe "product eligibility" do context "with a recurring billing product" do let(:product) { create(:subscription_product) } let(:installment_plan) { build(:product_installment_plan, link: product) } it "is not eligible" do expect(described_class.eligible_for_product?(product)).to be false expect(described_class.eligibility_erorr_message_for_product(product)) .to eq("Installment plans are not available for membership products") expect(installment_plan.valid?).to be false expect(installment_plan.errors[:base]) .to include("Installment plans are not available for membership products") end end context "with a tiered membership product" do let(:product) { create(:membership_product) } let(:installment_plan) { build(:product_installment_plan, link: product) } it "is not eligible" do expect(described_class.eligible_for_product?(product)).to be false expect(described_class.eligibility_erorr_message_for_product(product)) .to eq("Installment plans are not available for membership products") expect(installment_plan.valid?).to be false expect(installment_plan.errors[:base]) .to include("Installment plans are not available for membership products") end end context "with a preorder product" do let(:product) { create(:product, is_in_preorder_state: true) } let(:installment_plan) { build(:product_installment_plan, link: product) } it "is not eligible" do expect(described_class.eligible_for_product?(product)).to be false expect(described_class.eligibility_erorr_message_for_product(product)) .to eq("Installment plans are not available for pre-order products") expect(installment_plan.valid?).to be false expect(installment_plan.errors[:base]) .to include("Installment plans are not available for pre-order products") end end context "with a physical product" do let(:product) { create(:physical_product) } let(:installment_plan) { build(:product_installment_plan, link: product) } it "is not eligible" do expect(described_class.eligible_for_product?(product)).to be false expect(described_class.eligibility_erorr_message_for_product(product)) .to eq("Installment plans are not available for this product type") expect(installment_plan.valid?).to be false expect(installment_plan.errors[:base]) .to include("Installment plans are not available for this product type") end end context "with a bundle product" do let(:seller) { create(:user, :eligible_for_service_products) } let(:bundle) { create(:product, :bundle, user: seller, price_cents: 1000) } let(:course_product) { create(:product, native_type: Link::NATIVE_TYPE_COURSE, user: seller) } let(:physical_product) { create(:product, native_type: Link::NATIVE_TYPE_PHYSICAL, user: seller) } let(:installment_plan) { build(:product_installment_plan, link: bundle) } context "when all products in the bundle are eligible" do before do bundle.bundle_products << build(:bundle_product, bundle: bundle, product: course_product) end it "is valid" do expect(installment_plan.valid?).to be true end end context "when some products in the bundle are not eligible" do before do bundle.bundle_products << build(:bundle_product, bundle: bundle, product: course_product) bundle.bundle_products << build(:bundle_product, bundle: bundle, product: physical_product) end it "is not valid" do expect(installment_plan.valid?).to be false expect(installment_plan.errors[:base]) .to include("Installment plan is not available for the bundled product: #{physical_product.name}") end end context "when the bundle has no products" do it "is valid" do expect(installment_plan.valid?).to be true end end end context "with eligible product types" do let(:digital_product) { create(:product, native_type: Link::NATIVE_TYPE_DIGITAL, price_cents: 1000) } let(:course_product) { create(:product, native_type: Link::NATIVE_TYPE_COURSE, price_cents: 1000) } let(:ebook_product) { create(:product, native_type: Link::NATIVE_TYPE_EBOOK, price_cents: 1000) } let(:call_product) { create(:call_product, price_cents: 1000) } [ :digital_product, :course_product, :ebook_product, :call_product, ].each do |product_name| context "with #{product_name}" do let(:product) { public_send(product_name) } let(:installment_plan) { build(:product_installment_plan, link: product) } it "is eligible" do expect(described_class.eligible_for_product?(product)).to be true expect(described_class.eligibility_erorr_message_for_product(product)).to be_nil expect(installment_plan.valid?).to be true end end end end end describe "installment payment price" do let(:product) { create(:product, price_cents: 99 * 2, price_currency_type: "usd") } let(:installment_plan) { build(:product_installment_plan, link: product, number_of_installments: 2) } it "must be at least the minimum price for each installment" do installment_plan.number_of_installments = 2 expect(installment_plan).to be_valid installment_plan.number_of_installments = 0 expect(installment_plan).not_to be_valid installment_plan.number_of_installments = 3 expect(installment_plan).not_to be_valid expect(installment_plan.errors[:base]) .to include("The minimum price for each installment must be at least 0.99 USD.") end it "cannot be pwyw" do product.update!(customizable_price: true) expect(installment_plan).not_to be_valid expect(installment_plan.errors[:base]) .to include('Installment plans are not available for "pay what you want" pricing') end end describe "#calculate_installment_payment_price_cents" do let(:installment_plan) { build(:product_installment_plan, number_of_installments: 3) } it "splits price evenly when divisible by number of installments" do result = installment_plan.calculate_installment_payment_price_cents(3000) expect(result).to eq([1000, 1000, 1000]) end it "adds remainder to first installment when price not evenly divisible" do result = installment_plan.calculate_installment_payment_price_cents(3002) expect(result).to eq([1002, 1000, 1000]) end end describe "#destroy_if_no_payment_options!" do let(:product) { create(:product, price_cents: 99 * 2, price_currency_type: "usd") } let(:installment_plan) { build(:product_installment_plan, link: product, number_of_installments: 2) } context "with no payment options" do it "destroys the installment plan" do installment_plan.destroy_if_no_payment_options! expect { installment_plan.reload }.to raise_error(ActiveRecord::RecordNotFound) end end context "with existing payment options" do before do create(:payment_option, installment_plan:) end it "soft deletes the installment plan even if product is no longer eligible for installment plans" do product.update_column(:price_cents, 0) expect { installment_plan.destroy_if_no_payment_options! } .to change(installment_plan, :deleted_at).from(nil) end it "cannot be destroyed" do expect { installment_plan.destroy }.to raise_error(ActiveRecord::DeleteRestrictionError) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/resend_event_info_spec.rb
spec/models/resend_event_info_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe ResendEventInfo do before do Feature.activate(:resend) Feature.activate(:force_resend) end let(:email) { "to@example.com" } let(:resend_header_names) { MailerInfo::FIELD_NAMES.map { MailerInfo.header_name(_1) } } let(:mailer_headers) do mailer.message.header .filter_map { |f| f if f.name.in?(resend_header_names) } .map { |f| { "name" => f.name, "value" => f.value } } end def expect_headers_presence(*headers) expect(headers.map { MailerInfo.header_name(_1) }.sort).to eq(mailer_headers.map { _1["name"] }.sort) end describe ".from_event_json" do let(:event_json) do { "created_at" => "2025-01-02T00:14:12.391Z", "data" => { "created_at" => "2025-01-02 00:14:11.140106+00", "email_id" => "7409b6f1-56f1-4ba5-89f0-4364a08b246e", "from" => "\"Seller\" <noreply@staging.customers.gumroad.com>", "to" => [email], "headers" => mailer_headers, "subject" => "Test email" }, "type" => "email.delivered" } end RSpec.shared_examples "with different event types" do it "handles bounce events" do event_json["type"] = "email.bounced" event_info = described_class.from_event_json(event_json) expect(event_info.type).to eq(:bounced) end it "handles spam complaint events" do event_json["type"] = "email.complained" event_info = described_class.from_event_json(event_json) expect(event_info.type).to eq(:complained) end it "handles opened events" do event_json["type"] = "email.opened" event_info = described_class.from_event_json(event_json) expect(event_info.type).to eq(:opened) end it "handles click events" do event_json["type"] = "email.clicked" event_json["data"]["click"] = { "link" => "https://example.com/product" } event_info = described_class.from_event_json(event_json) expect(event_info.type).to eq(:clicked) expect(event_info.click_url).to eq("https://example.com/product") end end context "with receipt email" do context "with purchase" do let(:purchase) { create(:purchase) } let(:mailer) { CustomerMailer.receipt(purchase.id) } it "includes purchase id and marks as receipt email" do event_info = described_class.from_event_json(event_json) expect_headers_presence( MailerInfo::FIELD_EMAIL_PROVIDER, MailerInfo::FIELD_ENVIRONMENT, MailerInfo::FIELD_CATEGORY, MailerInfo::FIELD_MAILER_CLASS, MailerInfo::FIELD_MAILER_METHOD, MailerInfo::FIELD_MAILER_ARGS, MailerInfo::FIELD_PURCHASE_ID, ) expect(event_info.purchase_id).to eq(purchase.id.to_s) expect(event_info.mailer_class_and_method).to eq("CustomerMailer.receipt") expect(event_info.mailer_args).to eq("[#{purchase.id}]") expect(event_info).to be_for_receipt_email expect(event_info).not_to be_for_abandoned_cart_email expect(event_info).not_to be_for_installment_email end it_behaves_like "with different event types" context "with charge" do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller, name: "Product One") } let(:purchase_one) { create(:purchase, link: product, seller: seller) } let(:product_two) { create(:product, user: seller, name: "Product Two") } let(:purchase_two) { create(:purchase, link: product_two, seller: seller) } let(:charge) { create(:charge, purchases: [purchase_one, purchase_two], seller: seller) } let(:order) { charge.order } before do charge.order.purchases << purchase_one charge.order.purchases << purchase_two end let(:mailer) { CustomerMailer.receipt(nil, charge.id) } it "includes charge id and marks as receipt email" do event_info = described_class.from_event_json(event_json) expect_headers_presence( MailerInfo::FIELD_EMAIL_PROVIDER, MailerInfo::FIELD_ENVIRONMENT, MailerInfo::FIELD_CATEGORY, MailerInfo::FIELD_MAILER_CLASS, MailerInfo::FIELD_MAILER_METHOD, MailerInfo::FIELD_MAILER_ARGS, MailerInfo::FIELD_CHARGE_ID, ) expect(event_info.charge_id).to eq(charge.id.to_s) expect(event_info.mailer_class_and_method).to eq("CustomerMailer.receipt") expect(event_info.mailer_args).to eq("[nil, #{charge.id}]") expect(event_info).to be_for_receipt_email expect(event_info).not_to be_for_abandoned_cart_email expect(event_info).not_to be_for_installment_email end it_behaves_like "with different event types" end end end context "with preorder receipt email", :vcr do let(:preorder) do product = create(:product, price_cents: 600, is_in_preorder_state: false) preorder_product = create(:preorder_product_with_content, link: product) preorder_product.update(release_at: Time.current) # bypassed the creation validation authorization_purchase = build(:purchase, link: product, chargeable: build(:chargeable), purchase_state: "in_progress", is_preorder_authorization: true) preorder = preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful preorder end let(:mailer) { CustomerMailer.preorder_receipt(preorder.id) } it "marks as receipt email" do event_info = described_class.from_event_json(event_json) expect_headers_presence( MailerInfo::FIELD_EMAIL_PROVIDER, MailerInfo::FIELD_ENVIRONMENT, MailerInfo::FIELD_CATEGORY, MailerInfo::FIELD_MAILER_CLASS, MailerInfo::FIELD_MAILER_METHOD, MailerInfo::FIELD_MAILER_ARGS, MailerInfo::FIELD_PURCHASE_ID, ) expect(event_info.purchase_id).to eq(preorder.authorization_purchase.id.to_s) expect(event_info.mailer_class_and_method).to eq("CustomerMailer.preorder_receipt") expect(event_info.mailer_args).to eq("[#{preorder.id}]") expect(event_info).to be_for_receipt_email expect(event_info).not_to be_for_abandoned_cart_email expect(event_info).not_to be_for_installment_email end it_behaves_like "with different event types" end context "with abandoned cart email" do let(:cart) { create(:cart, user: nil, email: "guest@example.com") } let(:seller) { create(:user, name: "John Doe", username: "johndoe") } let!(:seller_workflow) { create(:abandoned_cart_workflow, seller: seller, published_at: 1.day.ago) } let!(:seller_products) { create_list(:product, 4, user: seller) { |product, i| product.update!(name: "S1 Product #{i + 1}") } } let(:mailer_args) { { seller_workflow.id => [seller.products.first.id] }.stringify_keys } let(:mailer) { CustomerMailer.abandoned_cart(cart.id, mailer_args) } let!(:cart_product) { create(:cart_product, cart: cart, product: seller.products.first) } before do cart.update!(updated_at: 2.days.ago) end it "includes workflow ids and marks as abandoned cart email" do event_info = described_class.from_event_json(event_json) expect_headers_presence( MailerInfo::FIELD_EMAIL_PROVIDER, MailerInfo::FIELD_ENVIRONMENT, MailerInfo::FIELD_CATEGORY, MailerInfo::FIELD_MAILER_CLASS, MailerInfo::FIELD_MAILER_METHOD, MailerInfo::FIELD_MAILER_ARGS, MailerInfo::FIELD_WORKFLOW_IDS, ) expect(event_info.workflow_ids).to eq([seller_workflow.id.to_s]) expect(event_info.mailer_class_and_method).to eq("CustomerMailer.abandoned_cart") expect(event_info.mailer_args).to eq("[#{cart.id}, {\"#{seller_workflow.id}\" => [#{seller.products.first.id}]}]") expect(event_info).to be_for_abandoned_cart_email expect(event_info).not_to be_for_receipt_email expect(event_info).not_to be_for_installment_email end it_behaves_like "with different event types" end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/license_spec.rb
spec/models/license_spec.rb
# frozen_string_literal: true require "spec_helper" require "digest" describe License do describe "validations" do it "does not allow users to unset token" do license = create(:license) license.serial = nil expect(license).to_not be_valid end it "populates serial correctly on new licenses" do link = create(:product) license = create(:license, link:) expect(license.serial).to match(/\A.{8}-.{8}-.{8}-.{8}\z/) end end describe "#disabled?" do let(:license) { create(:license) } context "when disabled" do it "returns true" do license.disabled_at = Date.current expect(license.disabled?).to eq true end end context "when enabled" do it "returns false" do expect(license.disabled?).to eq false end end end describe "#disable!" do let(:license) { create(:license) } it "disables the license" do current_time = Time.current.change(usec: 0) travel_to(current_time) do expect(license.disable!).to be(true) expect(license.reload.disabled_at).to eq current_time end end it "raises an exception on error" do license.serial = nil expect { license.disable! }.to raise_error(ActiveRecord::RecordInvalid) end end describe "#enable!" do let(:license) { create(:license, disabled_at: Time.current) } it "enables the license" do expect(license.enable!).to be(true) expect(license.reload.disabled_at).to eq nil end it "raises an exception on error" do license.serial = nil expect { license.enable! }.to raise_error(ActiveRecord::RecordInvalid) end end describe "#rotate!" do let(:license) { create(:license) } it "generates a new serial key" do old_serial = license.serial expect(license.rotate!).to be(true) expect(license.reload.serial).not_to eq old_serial expect(license.serial).to match(/\A.{8}-.{8}-.{8}-.{8}\z/) end end describe "paper_trail versioning" do with_versioning do let(:license) { create(:license) } it "tracks changes to disabled_at when disabling" do expect { license.disable! }.to change { license.versions.count }.by(1) expect(license.versions.last.changeset).to have_key("disabled_at") end it "tracks changes to disabled_at when enabling" do license.disable! expect { license.enable! }.to change { license.versions.count }.by(1) expect(license.versions.last.changeset).to have_key("disabled_at") end it "tracks changes to serial when rotating" do expect { license.rotate! }.to change { license.versions.count }.by(1) expect(license.versions.last.changeset).to have_key("serial") end it "does not track changes to uses" do expect { license.increment!(:uses) }.not_to change { license.versions.count } end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/north_macedonia_bank_account_spec.rb
spec/models/north_macedonia_bank_account_spec.rb
# frozen_string_literal: true describe NorthMacedoniaBankAccount do describe "#bank_account_type" do it "returns Macedonia" do expect(create(:north_macedonia_bank_account).bank_account_type).to eq("MK") end end describe "#country" do it "returns MK" do expect(create(:north_macedonia_bank_account).country).to eq("MK") end end describe "#currency" do it "returns mkd" do expect(create(:north_macedonia_bank_account).currency).to eq("mkd") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:north_macedonia_bank_account, account_number_last_four: "2345").account_number_visual).to eq("MK******2345") end end describe "#validate_bank_code" do it "allows records that match the required bank code format" do expect(build(:north_macedonia_bank_account, bank_code: "AAAAMK2XXXX")).to be_valid expect(build(:north_macedonia_bank_account, bank_code: "AAAAMK2X")).to be_valid mk_bank_account = build(:north_macedonia_bank_account, bank_code: "AAAAMK2XXXXX") expect(mk_bank_account).not_to be_valid expect(mk_bank_account.errors[:base]).to include("The bank code is invalid.") mk_bank_account = build(:north_macedonia_bank_account, bank_code: "AAAA2MK") expect(mk_bank_account).not_to be_valid expect(mk_bank_account.errors[:base]).to include("The bank code is invalid.") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:north_macedonia_bank_account)).to be_valid expect(build(:north_macedonia_bank_account, account_number: "MK07250120000058984")).to be_valid expect(build(:north_macedonia_bank_account, account_number: "ABC7250120000058984")).to be_valid expect(build(:north_macedonia_bank_account, account_number: "0007250120000058984")).to be_valid expect(build(:north_macedonia_bank_account, account_number: "ABCDEFGHIJKLMNOPQRS")).to be_valid mk_bank_account = build(:north_macedonia_bank_account, account_number: "MK0725012000005898") expect(mk_bank_account).to_not be_valid expect(mk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") mk_bank_account = build(:north_macedonia_bank_account, account_number: "MK072501200000589845") expect(mk_bank_account).to_not be_valid expect(mk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") mk_bank_account = build(:north_macedonia_bank_account, account_number: "00072501200000589845") expect(mk_bank_account).to_not be_valid expect(mk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") mk_bank_account = build(:north_macedonia_bank_account, account_number: "ABCDEFGHIJKLMNOPQR") expect(mk_bank_account).to_not be_valid expect(mk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end describe "#routing_number" do it "returns the bank code" do bank_account = create(:north_macedonia_bank_account, bank_code: "AAAAMK2XXXX") expect(bank_account.routing_number).to eq("AAAAMK2XXXX") end end describe "#to_hash" do it "returns hash with bank account details" do bank_account = create(:north_macedonia_bank_account, bank_code: "AAAAMK2XXXX", account_number_last_four: "8907" ) expect(bank_account.to_hash).to eq( routing_number: "AAAAMK2XXXX", account_number: "MK******8907", bank_account_type: "MK" ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false