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/media_location_spec.rb | spec/models/media_location_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe MediaLocation do
describe "#create" do
before do
@url_redirect = create(:readable_url_redirect)
@product = @url_redirect.referenced_link
end
it "raises error if platform is invalid" do
media_location = build(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id,
product_file_id: @product.product_files.first.id,
product_id: @product.id, location: 1)
media_location.platform = "invalid_platform"
media_location.validate
expect(media_location.errors.full_messages).to include("Platform is not included in the list")
end
it "raises error if product file is not consumable" do
non_consumable_file = create(:non_readable_document, link: @product)
media_location = build(:media_location, product_file_id: non_consumable_file.id, product_id: @product.id,
url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id,
location: 1)
media_location.validate
expect(media_location.errors[:base]).to include("File should be consumable")
end
context "inferring units from file type" do
it "infers correct units for readable" do
media_location = build(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id,
product_file_id: @product.product_files.first.id,
product_id: @product.id, location: 1)
media_location.save
expect(media_location.unit).to eq MediaLocation::Unit::PAGE_NUMBER
end
it "infers correct units for streamable" do
streamable = create(:streamable_video, link: @product)
media_location = build(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id,
product_file_id: streamable.id,
product_id: @product.id, location: 1)
media_location.save
expect(media_location.unit).to eq MediaLocation::Unit::SECONDS
end
it "infers correct units for listenable" do
listenable = create(:listenable_audio, link: @product)
media_location = build(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id,
product_file_id: listenable.id,
product_id: @product.id, location: 1)
media_location.save
expect(media_location.unit).to eq MediaLocation::Unit::SECONDS
end
end
end
describe ".max_consumed_at_by_file" do
it "returns the records with the largest consumed_at value for each product_file" do
product = create(:product)
purchase = create(:purchase, link: product)
product_files = create_list(:product_file, 2, link: product)
expected = []
expected << create(:media_location, purchase:, product_file: product_files[0], consumed_at: 3.days.ago) # most recent for file
create(:media_location, purchase:, product_file: product_files[0], consumed_at: 7.days.ago)
create(:media_location, purchase:, product_file: product_files[1], consumed_at: 5.days.ago)
expected << create(:media_location, purchase:, product_file: product_files[1], consumed_at: 2.days.ago) # most recent for file
create(:media_location, product_file: product_files[0], consumed_at: 1.day.ago) # different purchase
expect(MediaLocation.max_consumed_at_by_file(purchase_id: purchase.id)).to match_array(expected)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/taxonomy_spec.rb | spec/models/taxonomy_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Taxonomy do
describe "validations" do
describe "slug presence validation" do
context "when slug is present" do
subject { build(:taxonomy, slug: "example") }
it { is_expected.to be_valid }
end
context "when slug is not present" do
subject { build(:taxonomy, slug: nil) }
it "is not valid" do
expect(subject).not_to be_valid
expect(subject.errors.full_messages).to include("Slug can't be blank")
end
end
end
describe "slug uniqueness validation" do
subject { build(:taxonomy, slug: "example", parent:) }
context "when parent_id is nil" do
let(:parent) { nil }
context "when child taxonomy with slug doesn't exist" do
it { is_expected.to be_valid }
end
context "when child taxonomy with slug already exists" do
let!(:existing_taxonomy) { create(:taxonomy, slug: "example", parent:) }
it "is not valid" do
expect(subject).not_to be_valid
expect(subject.errors.full_messages).to include("Slug has already been taken")
end
end
end
context "when parent_id is not nil" do
let(:parent) { Taxonomy.find_by(slug: "design") }
context "when child taxonomy with slug doesn't exist" do
it { is_expected.to be_valid }
end
context "when child taxonomy with slug already exists" do
let!(:existing_taxonomy) { create(:taxonomy, slug: "example", parent:) }
it "is not valid" do
expect(subject).not_to be_valid
expect(subject.errors.full_messages).to include("Slug has already been taken")
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/community_chat_recap_spec.rb | spec/models/community_chat_recap_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe CommunityChatRecap do
subject(:chat_recap) { build(:community_chat_recap) }
describe "associations" do
it { is_expected.to belong_to(:community_chat_recap_run) }
it { is_expected.to belong_to(:community).optional }
it { is_expected.to belong_to(:seller).class_name("User").optional }
end
describe "validations" do
it { is_expected.to validate_presence_of(:summarized_message_count) }
it { is_expected.to validate_numericality_of(:summarized_message_count).is_greater_than_or_equal_to(0) }
it { is_expected.to validate_presence_of(:input_token_count) }
it { is_expected.to validate_numericality_of(:input_token_count).is_greater_than_or_equal_to(0) }
it { is_expected.to validate_presence_of(:output_token_count) }
it { is_expected.to validate_numericality_of(:output_token_count).is_greater_than_or_equal_to(0) }
describe "seller presence" do
context "when status is finished" do
before do
subject.status = "finished"
end
it { is_expected.to validate_presence_of(:seller) }
end
context "when status is not finished" do
it { is_expected.not_to validate_presence_of(:seller) }
end
end
it { is_expected.to define_enum_for(:status)
.with_values(pending: "pending", finished: "finished", failed: "failed")
.backed_by_column_of_type(:string)
.with_prefix(:status) }
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_purchase_spec.rb | spec/models/bundle_product_purchase_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BundleProductPurchase do
describe "validations" do
let(:bundle_product_purchase) { create(:bundle_product_purchase) }
context "bundle product purchase is valid" do
it "doesn't add an error" do
expect(bundle_product_purchase).to be_valid
end
end
context "bundle purchase and product purchase have different sellers" do
before do
product = create(:product)
bundle_product_purchase.product_purchase.update!(seller: product.user, link: product)
end
it "adds an error" do
expect(bundle_product_purchase).to_not be_valid
expect(bundle_product_purchase.errors.full_messages.first).to eq("Seller must be the same for bundle and product purchases")
end
end
context "product purchase is bundle purchase" do
before do
bundle_product_purchase.product_purchase.update!(link: create(:product, :bundle, user: bundle_product_purchase.product_purchase.seller))
end
it "adds an error" do
expect(bundle_product_purchase).to_not be_valid
expect(bundle_product_purchase.errors.full_messages.first).to eq("Product purchase cannot be a bundle purchase")
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/audience_member_spec.rb | spec/models/audience_member_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe AudienceMember, :freeze_time do
describe "validations" do
it "validates json schema" do
member = build(:audience_member, details: { "foo" => "bar" })
expect(member).to be_invalid
expect(member.errors[:details]).to be_present
member = build(:audience_member, details: { "follower" => { "id" => 1 } })
expect(member).to be_invalid
expect(member.errors[:details]).to include(/The property '#\/follower' did not contain a required property of 'created_at'/)
end
it "validates email" do
member = build(:audience_member, email: "invalid-email")
expect(member).to be_invalid
expect(member.errors[:email]).to be_present
member = build(:audience_member, email: nil)
expect(member).to be_invalid
expect(member.errors[:email]).to be_present
end
end
describe "callbacks" do
it "saving assigns derived columns" do
member = create(:audience_member, details: { "follower" => { "id" => 1, "created_at" => 7.days.ago.iso8601 } })
expect(member.attributes).to include(
"customer" => false,
"follower" => true,
"affiliate" => false,
"min_paid_cents" => nil,
"max_paid_cents" => nil,
"min_purchase_created_at" => nil,
"max_purchase_created_at" => nil,
"min_created_at" => 7.days.ago,
"max_created_at" => 7.days.ago,
"follower_created_at" => 7.days.ago,
"min_affiliate_created_at" => nil,
"max_affiliate_created_at" => nil,
)
member.details["purchases"] = [
{ "id" => 1, "product_id" => 1, "price_cents" => 100, "created_at" => 3.days.ago.iso8601 },
{ "id" => 2, "product_id" => 1, "variant_ids" => [1, 2], "price_cents" => 200, "created_at" => 2.day.ago.iso8601 },
{ "id" => 3, "product_id" => 1, "variant_ids" => [1, 3], "price_cents" => 300, "created_at" => 1.day.ago.iso8601 },
]
member.save!
expect(member.attributes).to include(
"customer" => true,
"follower" => true,
"affiliate" => false,
"min_paid_cents" => 100,
"max_paid_cents" => 300,
"min_purchase_created_at" => 3.days.ago,
"max_purchase_created_at" => 1.day.ago,
"min_created_at" => 7.days.ago,
"max_created_at" => 1.day.ago,
"follower_created_at" => 7.days.ago,
"min_affiliate_created_at" => nil,
"max_affiliate_created_at" => nil,
)
member.details["affiliates"] = [
{ "id" => 1, "product_id" => 1, "created_at" => 30.minutes.ago.iso8601 },
{ "id" => 2, "product_id" => 1, "created_at" => 20.minutes.ago.iso8601 },
]
member.save!
expect(member.attributes).to include(
"customer" => true,
"follower" => true,
"affiliate" => true,
"min_paid_cents" => 100,
"max_paid_cents" => 300,
"min_purchase_created_at" => 3.days.ago,
"max_purchase_created_at" => 1.day.ago,
"min_created_at" => 7.days.ago,
"max_created_at" => 20.minutes.ago,
"follower_created_at" => 7.days.ago,
"min_affiliate_created_at" => 30.minutes.ago,
"max_affiliate_created_at" => 20.minutes.ago,
)
end
end
describe ".filter" do
let(:seller) { create(:user) }
let(:seller_id) { seller.id }
it "works with no params" do
member = create_member(follower: {})
expect(filtered).to eq([member])
end
it "filters by type" do
customer = create_member(purchases: [{}])
follower = create_member(follower: {})
affiliate = create_member(affiliates: [{}])
all_types = create_member(purchases: [{}], follower: {}, affiliates: [{}])
expect(filtered(type: "customer")).to eq([customer, all_types])
expect(filtered(type: "follower")).to eq([follower, all_types])
expect(filtered(type: "affiliate")).to eq([affiliate, all_types])
end
it "raises error for invalid type" do
expect { filtered(type: "invalid_type") }.to raise_error(ArgumentError, /Invalid type: invalid_type/)
expect { filtered(type: "'; DROP TABLE audience_members; --") }.to raise_error(ArgumentError, /Invalid type/)
end
it "filters by purchased and not-purchased products and variants" do
member1 = create_member(purchases: [{ "product_id" => 1 }])
member2 = create_member(purchases: [{ "product_id" => 2 }])
member3 = create_member(purchases: [{ "product_id" => 2, "variant_ids" => [1] }])
member4 = create_member(purchases: [{ "product_id" => 2, "variant_ids" => [2] }])
member5 = create_member(purchases: [{ "product_id" => 1 }, { "product_id" => 2, "variant_ids" => [1] }])
member6 = create_member(purchases: [{ "product_id" => 1 }, { "product_id" => 2, "variant_ids" => [1, 2] }])
expect(filtered(bought_product_ids: [1])).to eq([member1, member5, member6])
expect(filtered(bought_product_ids: [2])).to eq([member2, member3, member4, member5, member6])
expect(filtered(bought_product_ids: [1, 2])).to eq([member1, member2, member3, member4, member5, member6])
expect(filtered(bought_variant_ids: [1])).to eq([member3, member5, member6])
expect(filtered(bought_variant_ids: [2])).to eq([member4, member6])
expect(filtered(bought_product_ids: [1], bought_variant_ids: [1])).to eq([member1, member3, member5, member6])
expect(filtered(bought_product_ids: [2], bought_variant_ids: [2])).to eq([member2, member3, member4, member5, member6])
expect(filtered(not_bought_product_ids: [1])).to eq([member2, member3, member4])
expect(filtered(not_bought_product_ids: [1, 2])).to eq([])
expect(filtered(not_bought_variant_ids: [1])).to eq([member1, member2, member4])
expect(filtered(not_bought_variant_ids: [1, 2])).to eq([member1, member2])
expect(filtered(not_bought_product_ids: [1], not_bought_variant_ids: [1])).to eq([member2, member4])
expect(filtered(bought_product_ids: [2], not_bought_variant_ids: [1])).to eq([member2, member4])
end
it "filters by prices" do
member1 = create_member(purchases: [{ "price_cents" => 0 }])
member2 = create_member(purchases: [{ "price_cents" => 100 }])
member3 = create_member(purchases: [{ "price_cents" => 200 }])
member4 = create_member(purchases: [
{ "product_id" => 7, "variant_ids" => [1], "price_cents" => 0 },
{ "product_id" => 8, "variant_ids" => [2], "price_cents" => 200 },
{ "product_id" => 9, "variant_ids" => [3], "price_cents" => 200 },
])
expect(filtered(paid_more_than_cents: 0)).to eq([member2, member3, member4])
expect(filtered(paid_more_than_cents: 50)).to eq([member2, member3, member4])
expect(filtered(paid_more_than_cents: 100)).to eq([member3, member4])
expect(filtered(paid_more_than_cents: 250)).to eq([])
expect(filtered(paid_less_than_cents: 250)).to eq([member1, member2, member3, member4])
expect(filtered(paid_less_than_cents: 200)).to eq([member1, member2, member4])
expect(filtered(paid_less_than_cents: 100)).to eq([member1, member4])
expect(filtered(paid_less_than_cents: 0)).to eq([])
expect(filtered(paid_more_than_cents: 50, paid_less_than_cents: 150)).to eq([member2])
expect(filtered(paid_more_than_cents: 0, bought_product_ids: [7])).to eq([])
expect(filtered(paid_more_than_cents: 0, bought_variant_ids: [1])).to eq([])
expect(filtered(paid_more_than_cents: 0, bought_product_ids: [7, 8])).to eq([member4])
expect(filtered(paid_more_than_cents: 0, bought_variant_ids: [1, 2])).to eq([member4])
end
it "deduplicates rows joined by json_table" do
member = create_member(purchases: [
{ "price_cents" => 100 },
{ "price_cents" => 200 },
])
expect(filtered(paid_more_than_cents: 0, paid_less_than_cents: 300)).to eq([member])
expect(filtered_with_ids(paid_more_than_cents: 0, paid_less_than_cents: 300)).to eq([member])
end
it "filters by creation dates" do
member1 = create_member(follower: { "created_at" => 5.days.ago.iso8601 })
member2 = create_member(follower: { "created_at" => 4.days.ago.iso8601 })
member3 = create_member(
follower: { "created_at" => 3.days.ago.iso8601 },
purchases: [{ "product_id" => 6, "created_at" => 2.days.ago.iso8601 }]
)
member4 = create_member(purchases: [
{ "product_id" => 7, "variant_ids" => [1], "created_at" => 5.days.ago.iso8601 },
{ "product_id" => 8, "variant_ids" => [2], "created_at" => 1.day.ago.iso8601 }
])
expect(filtered(created_after: 4.days.ago.iso8601)).to eq([member3, member4])
expect(filtered(created_before: 2.days.ago.iso8601)).to eq([member1, member2, member3, member4])
expect(filtered(created_after: 4.days.ago.iso8601, created_before: 2.days.ago.iso8601)).to eq([member3])
expect(filtered(created_after: 4.days.ago.iso8601, created_before: 2.days.ago.iso8601, bought_product_ids: [6])).to eq([])
expect(filtered(created_after: 4.days.ago.iso8601, created_before: 1.days.ago.iso8601, bought_product_ids: [6])).to eq([member3])
end
it "filters by country" do
member1 = create_member(purchases: [{ "product_id" => 1, "country" => "United States" }])
member2 = create_member(purchases: [{ "product_id" => 1, "country" => "Canada" }])
member3 = create_member(purchases: [
{ "product_id" => 1, "country" => "United States" },
{ "product_id" => 2, "country" => "Canada" }
])
expect(filtered(bought_from: "United States")).to eq([member1, member3])
expect(filtered(bought_from: "Canada")).to eq([member2, member3])
expect(filtered(bought_from: "Canada", bought_product_ids: [1, 3])).to eq([member2])
expect(filtered(bought_from: "Mexico")).to eq([])
end
it "filters by affiliate products" do
member1 = create_member(affiliates: [{ "product_id" => 1 }])
member2 = create_member(affiliates: [{ "product_id" => 2 }])
member3 = create_member(affiliates: [
{ "product_id" => 1, "created_at" => 3.day.ago.iso8601 },
{ "product_id" => 2, "created_at" => 2.day.ago.iso8601 },
{ "product_id" => 3, "created_at" => 1.day.ago.iso8601 },
])
expect(filtered(affiliate_product_ids: [1])).to eq([member1, member3])
expect(filtered(affiliate_product_ids: [2])).to eq([member2, member3])
expect(filtered(affiliate_product_ids: [1, 2])).to eq([member1, member2, member3])
expect(filtered(affiliate_product_ids: [1, 2], created_after: 2.day.ago)).to eq([])
expect(filtered(affiliate_product_ids: [1, 2], created_after: 3.day.ago)).to eq([member3])
end
context "with_ids" do
it "returns the members, including the last record id matching the filters" do
member_1 = create_member(
purchases: [
{ "id" => 1, "price_cents" => 100 },
{ "id" => 2, "price_cents" => 90 },
{ "id" => 3, "price_cents" => 120 },
{ "id" => 4, "price_cents" => 70 },
],
affiliates: [
{ "id" => 1, "created_at" => 7.days.ago.iso8601 },
{ "id" => 2, "created_at" => 4.days.ago.iso8601 },
]
)
member_2 = create_member(
purchases: [
{ "id" => 5, "price_cents" => 100 },
{ "id" => 6, "price_cents" => 90 },
{ "id" => 7, "price_cents" => 120 },
{ "id" => 8, "price_cents" => 70 },
],
follower: { "id" => 1, "created_at" => 5.days.ago.iso8601 }
)
member_3 = create_member(
purchases: [
{ "id" => 9, "price_cents" => 200 },
]
)
results = filtered_with_ids
expect(results.size).to eq(3)
expect(results[0]).to eq(member_1)
expect(results[0].purchase_id).to eq(4)
expect(results[0].follower_id).to eq(nil)
expect(results[0].affiliate_id).to eq(2)
expect(results[1]).to eq(member_2)
expect(results[1].purchase_id).to eq(8)
expect(results[1].follower_id).to eq(1)
expect(results[1].affiliate_id).to eq(nil)
expect(results[2]).to eq(member_3)
expect(results[2].purchase_id).to eq(9)
expect(results[2].follower_id).to eq(nil)
expect(results[2].affiliate_id).to eq(nil)
results = filtered_with_ids(paid_more_than_cents: 75, paid_less_than_cents: 110)
expect(results.size).to eq(2)
expect(results[0]).to eq(member_1)
expect(results[0].purchase_id).to eq(2)
expect(results[0].follower_id).to eq(nil)
expect(results[0].affiliate_id).to eq(nil)
expect(results[1]).to eq(member_2)
expect(results[1].purchase_id).to eq(6)
expect(results[1].follower_id).to eq(nil)
expect(results[1].affiliate_id).to eq(nil)
results = filtered_with_ids(type: "follower", created_after: 6.days.ago.iso8601)
expect(results.size).to eq(1)
expect(results[0]).to eq(member_2)
expect(results[0].purchase_id).to eq(nil)
expect(results[0].follower_id).to eq(1)
expect(results[0].affiliate_id).to eq(nil)
end
end
end
describe ".refresh_all! and #refresh!" do
let(:seller) { create(:user) }
it "creates / updates / deletes members" do
outdated_follower = create(:active_follower, user: seller)
outdated_follower.update_column(:confirmed_at, nil) # simulate deleted follower outside of callbacks
missing_purchase = create(:purchase, :from_seller, seller:)
seller.audience_members.find_by(email: missing_purchase.email).delete # simulate missing purchase outside of callbacks
normal_purchase = create(:purchase, :from_seller, seller:)
refunded_purchase = create(:purchase, :from_seller, seller:, email: normal_purchase.email)
refunded_purchase.update_column(:stripe_refunded, true) # simulate refunded purchase outside of callbacks
affiliate = create(:direct_affiliate, seller:)
affiliate.products << create(:product, user: seller)
affiliate.products << create(:product, user: seller)
affiliate.products << create(:product, user: seller)
ProductAffiliate.find_by(affiliate:, product: affiliate.products[1]).delete # simulate product affiliation removed outside of callbacks
# check that the outdated data, generated by callbacks, looks like what we expect
expect(seller.audience_members.count).to eq(3)
expect(seller.audience_members.where(email: outdated_follower.email, follower: true)).to be_present
expect(seller.audience_members.where(email: missing_purchase.email, customer: true)).to be_blank
member_with_several_purchases = seller.audience_members.find_by(email: normal_purchase.email, customer: true)
expect(member_with_several_purchases).to be_present
expect(member_with_several_purchases.details["purchases"].size).to eq(2)
member_with_several_affiliate_products = seller.audience_members.find_by(email: affiliate.affiliate_user.email, affiliate: true)
expect(member_with_several_affiliate_products).to be_present
expect(member_with_several_affiliate_products.details["affiliates"].size).to eq(3)
described_class.refresh_all!(seller:)
expect(seller.audience_members.count).to eq(3)
expect(seller.audience_members.where(email: outdated_follower.email, follower: true)).to be_blank
expect(seller.audience_members.where(email: missing_purchase.email, customer: true)).to be_present
member_with_several_purchases = seller.audience_members.find_by(email: normal_purchase.email, customer: true)
expect(member_with_several_purchases).to be_present
expect(member_with_several_purchases.details["purchases"].size).to eq(1)
expect(member_with_several_purchases.details["purchases"].first["id"]).to eq(normal_purchase.id)
member_with_several_affiliate_products = seller.audience_members.find_by(email: affiliate.affiliate_user.email, affiliate: true)
expect(member_with_several_affiliate_products).to be_present
expect(member_with_several_affiliate_products.details["affiliates"].size).to eq(2)
expect(member_with_several_affiliate_products.details["affiliates"].select { _1["product_id"] == affiliate.products[1].id }).to be_blank
end
end
def filtered(params = {})
described_class.filter(seller_id:, params:).order(:id).to_a
end
def filtered_with_ids(params = {})
described_class.filter(seller_id:, params:, with_ids: true).order(:id).to_a
end
def create_member(details = {})
create(:audience_member, seller:, **details.with_indifferent_access.slice(:purchases, :follower, :affiliates))
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/price_spec.rb | spec/models/price_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Price do
it "belongs to a link" do
price = create(:price)
expect(price.link).to be_a Link
end
it "validates presence of the link" do
invalid_price = create(:price)
invalid_price.link = nil
expect(invalid_price).not_to be_valid
expect(invalid_price.errors.full_messages).to include "Link can't be blank"
end
describe "recurrence validation" do
context "for a product without recurring billing" do
it "does not require recurrence to be set" do
product = create(:product)
price = build(:price, link: product, recurrence: nil)
expect(price).to be_valid
end
end
context "for a product with recurring billing " do
before :each do
@product = create(:subscription_product)
end
it "must set recurrence" do
price = build(:price, link: @product, recurrence: nil)
expect(price).not_to be_valid
end
it "must be one of the permitted recurrences" do
BasePrice::Recurrence.all.each do |recurrence|
price = build(:price, link: @product, recurrence:)
expect(price).to be_valid
end
invalid_price = build(:price, link: @product, recurrence: "whenever")
expect(invalid_price).not_to be_valid
expect(invalid_price.errors.full_messages).to include "Invalid recurrence"
end
end
end
describe ".alive" do
it "excludes deleted prices" do
product = create(:product)
live_price = product.default_price
create(:price, link: product, deleted_at: Time.current)
expect(Price.alive).to match_array([live_price])
end
end
describe "#alive?" do
it "returns true if not deleted" do
price = create(:price)
expect(price.alive?).to eq true
end
it "returns false if price is deleted" do
price = create(:price, deleted_at: Time.current)
expect(price.alive?).to eq false
end
end
describe "as_json" do
before do
@product = create(:subscription_product, price_cents: 10_00)
@price_monthly = @product.default_price
end
it "has the proper json" do
expect(@price_monthly.as_json).to eq(id: @price_monthly.external_id,
price_cents: 10_00,
recurrence: "monthly",
recurrence_formatted: " a month")
end
it "includes product duration if it exists" do
@product.update_attribute(:duration_in_months, 6)
expect(@price_monthly.as_json).to eq(id: @price_monthly.external_id,
price_cents: 10_00,
recurrence: "monthly",
recurrence_formatted: " a month x 6")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/global_affiliate_spec.rb | spec/models/global_affiliate_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GlobalAffiliate do
describe "validations" do
describe "affiliate_basis_points" do
it "requires affiliate_basis_points to be present" do
affiliate = create(:user).global_affiliate # sets affiliate basis points in pre-validation hook on creation
affiliate.affiliate_basis_points = nil
expect(affiliate).not_to be_valid
expect(affiliate.errors.full_messages).to include "Affiliate basis points can't be blank"
end
end
describe "affiliate_user_id" do
let(:user) { create(:user) }
let!(:global_affiliate) { user.global_affiliate }
it "requires affiliate_user_id to be unique" do
duplicate_affiliate = described_class.new(affiliate_user: user)
expect(duplicate_affiliate).not_to be_valid
expect(duplicate_affiliate.errors.full_messages).to include "Affiliate user has already been taken"
end
it "allows multiple direct affiliates for that user" do
create_list(:direct_affiliate, 2, affiliate_user: user).each do |affiliate|
expect(affiliate).to be_valid
end
end
end
describe "eligible_for_stripe_payments" do
let(:affiliate_user) do
user = build(:user)
user.save(validate: false)
user
end
let(:global_affiliate) { affiliate_user.global_affiliate }
context "when affiliate user has a Brazilian Stripe Connect account" do
before do
allow_any_instance_of(User).to receive(:has_brazilian_stripe_connect_account?).and_return(true)
allow(affiliate_user).to receive(:has_brazilian_stripe_connect_account?).and_return(true)
end
it "is invalid" do
expect(global_affiliate).not_to be_valid
expect(global_affiliate.errors[:base]).to include(
"This user cannot be added as an affiliate because they use a Brazilian Stripe account."
)
end
end
context "when the affiliate user does not have a Brazilian Stripe Connect account" do
before do
allow(affiliate_user).to receive(:has_brazilian_stripe_connect_account?).and_return(false)
end
it "is valid" do
expect(global_affiliate).to be_valid
end
end
end
end
describe "lifecycle hooks" do
describe "before_validation :set_affiliate_basis_points" do
it "sets affiliate basis points to the default for a new record" do
affiliate = described_class.new(affiliate_basis_points: nil)
affiliate.valid?
expect(affiliate.affiliate_basis_points).to eq GlobalAffiliate::AFFILIATE_BASIS_POINTS
end
it "does not overwrite affiliate basis points for an existing record" do
affiliate = create(:user).global_affiliate
affiliate.affiliate_basis_points = 5000
expect { affiliate.valid? }.not_to change { affiliate.affiliate_basis_points }
end
end
end
describe ".cookie_lifetime" do
it "returns 7 days" do
expect(described_class.cookie_lifetime).to eq 7.days
end
end
describe "#final_destination_url" do
let(:affiliate) { create(:user).global_affiliate }
context "when product is provided" do
it "returns the product URL" do
product = create(:product)
expect(affiliate.final_destination_url(product:)).to eq product.long_url
end
end
context "when product is not provided" do
it "returns the discover URL with the affiliate ID param" do
expect(affiliate.final_destination_url).to eq "#{UrlService.discover_domain_with_protocol}/discover?a=#{affiliate.external_id_numeric}"
end
end
end
describe "#eligible_for_purchase_credit?" do
let(:affiliate) { create(:user).global_affiliate }
let(:product) { create(:product, :recommendable) }
it "returns true if the product is eligible for the global affiliate program, even if the purchase came through Discover" do
expect(affiliate.eligible_for_purchase_credit?(product:, was_recommended: false)).to eq true
expect(affiliate.eligible_for_purchase_credit?(product:, was_recommended: true)).to eq true
end
it "returns true if the product is eligible and the purchaser email is different from that of the affiliate" do
expect(affiliate.eligible_for_purchase_credit?(product:, purchaser_email: "not_affiliate@example.com")).to eq true
end
it "returns true if the product is eligible and adult" do
nsfw_product = create(:product, :recommendable, is_adult: true)
expect(affiliate.eligible_for_purchase_credit?(product: nsfw_product)).to eq true
end
it "returns false for an ineligible product" do
product = create(:product)
expect(affiliate.eligible_for_purchase_credit?(product:)).to eq false
end
it "returns false if the affiliate is deleted" do
affiliate.update!(deleted_at: Time.current)
expect(affiliate.eligible_for_purchase_credit?(product:)).to eq false
end
it "returns false if the purchaser is the same as the affiliate (based on email exact match)" do
expect(affiliate.eligible_for_purchase_credit?(product:, purchaser_email: affiliate.affiliate_user.email)).to eq false
end
it "returns false if the affiliate is suspended" do
user = affiliate.affiliate_user
admin = create(:admin_user)
user.flag_for_fraud!(author_id: admin.id)
user.suspend_for_fraud!(author_id: admin.id)
affiliate.reload
expect(affiliate.eligible_for_purchase_credit?(product:)).to eq false
end
it "returns false if the seller has disabled global affiliates" do
product = create(:product, :recommendable)
product.user.update!(disable_global_affiliate: true)
expect(affiliate.eligible_for_purchase_credit?(product:)).to eq 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.affiliate_user, country: "BR")
affiliate.affiliate_user.update!(check_merchant_account_is_linked: true)
expect(affiliate.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/egypt_bank_account_spec.rb | spec/models/egypt_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe KenyaBankAccount do
describe "#bank_account_type" do
it "returns EG" do
expect(create(:egypt_bank_account).bank_account_type).to eq("EG")
end
end
describe "#country" do
it "returns EG" do
expect(create(:egypt_bank_account).country).to eq("EG")
end
end
describe "#currency" do
it "returns egp" do
expect(create(:egypt_bank_account).currency).to eq("egp")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:egypt_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("NBEGEGCX331")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:egypt_bank_account, account_number_last_four: "0002").account_number_visual).to eq("******0002")
end
end
describe "#validate_bank_code" do
it "allows 8 to 11 characters only" do
expect(build(:egypt_bank_account, bank_code: "NBEGEGCX")).to be_valid
expect(build(:egypt_bank_account, bank_code: "NBEGEGCX331")).to be_valid
expect(build(:egypt_bank_account, bank_code: "NBEGEGC")).not_to be_valid
expect(build(:egypt_bank_account, bank_code: "NBEGEGCX3311")).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/niger_bank_account_spec.rb | spec/models/niger_bank_account_spec.rb | # frozen_string_literal: true
describe NigerBankAccount do
describe "#bank_account_type" do
it "returns NE" do
expect(create(:niger_bank_account).bank_account_type).to eq("NE")
end
end
describe "#country" do
it "returns NE" do
expect(create(:niger_bank_account).country).to eq("NE")
end
end
describe "#currency" do
it "returns xof" do
expect(create(:niger_bank_account).currency).to eq("xof")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:niger_bank_account, account_number_last_four: "0268").account_number_visual).to eq("NE******0268")
end
end
describe "#routing_number" do
it "returns nil" do
expect(create(:niger_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/hungary_bank_account_spec.rb | spec/models/hungary_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe HungaryBankAccount do
describe "#bank_account_type" do
it "returns hungary" do
expect(create(:hungary_bank_account).bank_account_type).to eq("HU")
end
end
describe "#country" do
it "returns HU" do
expect(create(:hungary_bank_account).country).to eq("HU")
end
end
describe "#currency" do
it "returns huf" do
expect(create(:hungary_bank_account).currency).to eq("huf")
end
end
describe "#routing_number" do
it "returns nil" do
expect(create(:hungary_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(:hungary_bank_account, account_number_last_four: "2874").account_number_visual).to eq("HU******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(:hungary_bank_account)).to be_valid
expect(build(:hungary_bank_account, account_number: "HU42 1177 3016 1111 1018 0000 0000")).to be_valid
hu_bank_account = build(:hungary_bank_account, account_number: "HU12345")
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(:hungary_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(:hungary_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(:hungary_bank_account, account_number: "HUABCDE")
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/self_service_affiliate_product_spec.rb | spec/models/self_service_affiliate_product_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SelfServiceAffiliateProduct do
let(:creator) { create(:user) }
describe "validations" do
let(:product) { create(:product, user: creator) }
subject(:self_service_affiliate_product) { build(:self_service_affiliate_product, product:, seller: creator) }
it "validates without any error" do
expect(self_service_affiliate_product).to be_valid
end
describe "presence" do
subject(:self_service_affiliate_product) { described_class.new }
it "validates presence of attributes" do
expect(self_service_affiliate_product).to be_invalid
expect(self_service_affiliate_product.errors.messages).to eq(
seller: ["can't be blank"],
product: ["can't be blank"],
)
end
context "when enabled is set to true" do
it "validates presence of affiliate_basis_points" do
self_service_affiliate_product.enabled = true
expect(self_service_affiliate_product).to be_invalid
expect(self_service_affiliate_product.errors.messages).to eq(
seller: ["can't be blank"],
product: ["can't be blank"],
affiliate_basis_points: ["can't be blank"]
)
end
end
end
describe "affiliate_basis_points_must_fall_in_an_acceptable_range" do
it "validates affiliate_basis_points is in valid range" do
self_service_affiliate_product.enabled = true
self_service_affiliate_product.affiliate_basis_points = 76
expect(self_service_affiliate_product).to be_invalid
expect(self_service_affiliate_product.errors.full_messages.first).to eq("Affiliate commission must be between 1% and 75%.")
end
end
describe "destination_url_validation" do
it "validates destination url format" do
self_service_affiliate_product.destination_url = "invalid-url"
expect(self_service_affiliate_product).to be_invalid
expect(self_service_affiliate_product.errors.full_messages.first).to eq("The destination url you entered is invalid.")
end
end
describe "product_is_not_a_collab" do
let(:product) { create(:product, :is_collab, user: creator) }
it "validates that the product is not a collab when enabled" do
self_service_affiliate_product.enabled = true
expect(self_service_affiliate_product).to be_invalid
expect(self_service_affiliate_product.errors.full_messages).to match_array(["Collab products cannot have affiliates"])
end
it "does not validate that the product is not a collab when disabled" do
self_service_affiliate_product.enabled = false
expect(self_service_affiliate_product).to be_valid
end
end
describe "product_user_and_seller_is_same" do
let(:product) { create(:product) }
it "validates that the product's creator is same as the seller" do
expect(self_service_affiliate_product).to be_invalid
expect(self_service_affiliate_product.errors.full_messages).to match_array(["The product '#{product.name}' does not belong to you (#{creator.email})."])
end
end
end
describe ".bulk_upsert!" do
let(:published_product_one) { create(:product, user: creator) }
let(:published_product_two) { create(:product, user: creator) }
let!(:published_product_three) { create(:product, user: creator) }
let!(:published_product_four) { create(:product, user: creator) }
let!(:enabled_self_service_affiliate_product_for_published_product_one) { create(:self_service_affiliate_product, enabled: true, seller: creator, product: published_product_one, affiliate_basis_points: 1000) }
let!(:enabled_self_service_affiliate_product_for_published_product_two) { create(:self_service_affiliate_product, enabled: true, seller: creator, product: published_product_two, destination_url: "https://example.com") }
let(:products_with_details) do [
{ id: published_product_one.external_id_numeric, enabled: false, name: published_product_one.name, fee_percent: 10, destination_url: nil },
{ id: published_product_two.external_id_numeric, enabled: false, fee_percent: 5, destination_url: "https://example.com" },
{ id: published_product_three.external_id_numeric, enabled: false, name: published_product_three.name, fee_percent: nil, destination_url: nil },
{ id: published_product_four.external_id_numeric, enabled: true, name: published_product_four.name, fee_percent: 25, destination_url: "https://example.com/test" }
] end
it "upserts the given products" do
described_class.bulk_upsert!(products_with_details, creator.id)
expect(enabled_self_service_affiliate_product_for_published_product_one.reload.enabled).to eq(false)
expect(enabled_self_service_affiliate_product_for_published_product_two.reload.enabled).to eq(false)
expect(enabled_self_service_affiliate_product_for_published_product_two.destination_url).to eq("https://example.com")
expect(creator.self_service_affiliate_products.last.slice(:enabled, :product_id, :affiliate_basis_points, :destination_url)).to eq(
"enabled" => true,
"product_id" => published_product_four.id,
"affiliate_basis_points" => 2500,
"destination_url" => "https://example.com/test"
)
end
it "raises an error with invalid params" do
collab_product = create(:product, :is_collab, user: creator)
products_with_details << {
id: collab_product.external_id_numeric,
enabled: true,
name: collab_product.name,
fee_percent: 10,
destination_url: nil,
}
expect do
described_class.bulk_upsert!(products_with_details, creator.id)
end.to raise_error(ActiveRecord::RecordInvalid, "Validation failed: Collab products cannot have affiliates")
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_profile_wishlists_section_spec.rb | spec/models/seller_profile_wishlists_section_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SellerProfileWishlistsSection do
describe "validations" do
it "validates json_data with the correct schema" do
section = build(:seller_profile_wishlists_section, shown_wishlists: [create(:wishlist).id])
section.json_data["garbage"] = "should not be here"
schema = JSON.parse(File.read(Rails.root.join("lib", "json_schemas", "seller_profile_wishlists_section.json").to_s))
expect(JSON::Validator).to receive(:new).with(schema, insert_defaults: true, record_errors: true).and_wrap_original do |original, *args|
validator = original.call(*args)
expect(validator).to receive(:validate).twice.with(section.json_data).and_call_original
validator
end
section.validate
expect(section.errors.full_messages.to_sentence).to eq("The property '#/' contains additional properties [\"garbage\"] outside of the schema when none are allowed")
section.json_data.delete("garbage")
expect(section).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/sri_lanka_bank_account_spec.rb | spec/models/sri_lanka_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SriLankaBankAccount do
describe "#bank_account_type" do
it "returns LK" do
expect(create(:sri_lanka_bank_account).bank_account_type).to eq("LK")
end
end
describe "#country" do
it "returns LK" do
expect(create(:sri_lanka_bank_account).country).to eq("LK")
end
end
describe "#currency" do
it "returns lkr" do
expect(create(:sri_lanka_bank_account).currency).to eq("lkr")
end
end
describe "#routing_number" do
it "returns valid for 8 to 11 characters" do
ba = create(:sri_lanka_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAALKLXXXX-7010999")
end
end
describe "#branch_code" do
it "returns the branch code" do
bank_account = create(:sri_lanka_bank_account, branch_code: "7010999")
expect(bank_account.branch_code).to eq("7010999")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:sri_lanka_bank_account, account_number_last_four: "2345").account_number_visual).to eq("******2345")
end
end
describe "#validate_branch_code" do
it "allows exactly 7 digits" do
expect(build(:sri_lanka_bank_account, branch_code: "7010999")).to be_valid
expect(build(:sri_lanka_bank_account, branch_code: "701099")).not_to be_valid
expect(build(:sri_lanka_bank_account, branch_code: "70109990")).not_to be_valid
end
end
describe "#validate_bank_code" do
it "allows 11 characters only" do
expect(build(:sri_lanka_bank_account, bank_code: "AAAALKLXXXX")).to be_valid
expect(build(:sri_lanka_bank_account, bank_code: "AAAALKLXXXXX")).not_to be_valid
expect(build(:sri_lanka_bank_account, bank_code: "AAAALKLXXX")).not_to be_valid
end
end
describe "#validate_account_number" do
it "allows 10 to 18 digits only" do
expect(build(:sri_lanka_bank_account, account_number: "0000012345")).to be_valid
expect(build(:sri_lanka_bank_account, account_number: "000001234567890123")).to be_valid
expect(build(:sri_lanka_bank_account, account_number: "000001234")).not_to be_valid
expect(build(:sri_lanka_bank_account, account_number: "0000012345678901234")).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/nigeria_bank_account_spec.rb | spec/models/nigeria_bank_account_spec.rb | # frozen_string_literal: true
describe NigeriaBankAccount do
describe "#bank_account_type" do
it "returns NG" do
expect(create(:nigeria_bank_account).bank_account_type).to eq("NG")
end
end
describe "#country" do
it "returns NG" do
expect(create(:nigeria_bank_account).country).to eq("NG")
end
end
describe "#currency" do
it "returns ngn" do
expect(create(:nigeria_bank_account).currency).to eq("ngn")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:nigeria_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAANGLAXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:nigeria_bank_account, account_number_last_four: "1112").account_number_visual).to eq("NG******1112")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/sales_export_spec.rb | spec/models/sales_export_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe SalesExport do
describe "#destroy" do
it "deletes chunks" do
export = create(:sales_export)
create(:sales_export_chunk, export:)
expect(SalesExportChunk.count).to eq(1)
export.destroy!
expect(SalesExportChunk.count).to eq(0)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/sent_post_email_spec.rb | spec/models/sent_post_email_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SentPostEmail do
let(:post) { create(:post) }
describe "creation" do
it "downcases email" do
record = create(:sent_post_email, email: "FOO")
expect(record.reload.email).to eq("foo")
end
it "ensures emails are unique for each post" do
create(:sent_post_email, post:, email: "foo")
create(:sent_post_email, email: "foo") # belongs to another post, so the record above is still unique
expect do
create(:sent_post_email, post:, email: "FOO")
end.to raise_error(ActiveRecord::RecordNotUnique)
end
end
describe ".missing_emails" do
it "returns array of emails currently not stored" do
create(:sent_post_email, post:, email: "foo")
create(:sent_post_email, post:, email: "bar")
create(:sent_post_email, email: "missing1") # belongs to another post, so it's missing for `post`
result = described_class.missing_emails(post:, emails: ["foo", "missing1", "bar", "missing2"])
expect(result).to match_array(["missing1", "missing2"])
end
end
describe ".ensure_uniqueness" do
it "runs block if we successfully created a unique record for that post and email" do
create(:sent_post_email, email: "foo") # belongs to another post, so it should not interact with the checks below
counter = 0
described_class.ensure_uniqueness(post:, email: "foo") { counter += 1 }
expect(counter).to eq(1)
described_class.ensure_uniqueness(post:, email: "FOO") { counter += 1 }
expect(counter).to eq(1)
described_class.ensure_uniqueness(post:, email: "bar") { counter += 1 }
expect(counter).to eq(2)
end
it "does not raise error if email is blank" do
counter = 0
described_class.ensure_uniqueness(post:, email: "") { counter += 1 }
expect(counter).to eq(0)
described_class.ensure_uniqueness(post:, email: nil) { counter += 1 }
expect(counter).to eq(0)
end
end
describe ".insert_all_emails" do
it "inserts all emails, even if some already exist, and returns newly inserted" do
create(:sent_post_email, post:, email: "foo")
create(:sent_post_email, email: "bar") # belongs to another post, so it should not interact with the checks below
expect(described_class.insert_all_emails(post:, emails: ["foo", "bar", "baz"])).to eq(["bar", "baz"])
expect(described_class.where(post:, email: ["foo", "bar", "baz"]).count).to eq(3)
# also works if all emails already exist
expect(described_class.insert_all_emails(post:, emails: ["foo", "bar", "baz"])).to eq([])
expect(described_class.where(post:, email: ["foo", "bar", "baz"]).count).to eq(3)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/bahrain_bank_account_spec.rb | spec/models/bahrain_bank_account_spec.rb | # frozen_string_literal: true
describe BahrainBankAccount do
describe "#bank_account_type" do
it "returns BH" do
expect(create(:bahrain_bank_account).bank_account_type).to eq("BH")
end
end
describe "#country" do
it "returns BH" do
expect(create(:bahrain_bank_account).country).to eq("BH")
end
end
describe "#currency" do
it "returns bhd" do
expect(create(:bahrain_bank_account).currency).to eq("bhd")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:bahrain_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAABHBMXYZ")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:bahrain_bank_account, account_number_last_four: "BH00").account_number_visual).to eq("BH******BH00")
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_custom_field_spec.rb | spec/models/purchase_custom_field_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PurchaseCustomField do
describe "validations" do
it "validates field type is a custom field type" do
purchase_custom_field = described_class.new(field_type: "invalid")
expect(purchase_custom_field).not_to be_valid
expect(purchase_custom_field.errors.full_messages).to include("Field type is not included in the list")
end
it "validates name is present" do
purchase_custom_field = described_class.new
expect(purchase_custom_field).not_to be_valid
expect(purchase_custom_field.errors.full_messages).to include("Name can't be blank")
end
end
describe "normalization" do
it "normalizes value" do
purchase_custom_field = described_class.new(value: " test value ")
expect(purchase_custom_field.value).to eq("test value")
end
it "converts nil to false for boolean fields" do
putchase_custom_field = described_class.create(field_type: CustomField::TYPE_CHECKBOX, value: nil)
expect(putchase_custom_field.value).to eq(false)
end
end
describe "#value_valid_for_custom_field" do
let(:custom_field) { create(:custom_field) }
let(:purchase) { create(:purchase) }
[CustomField::TYPE_TEXT, CustomField::TYPE_LONG_TEXT].each do |type|
it "requires value for #{type} custom field if required is true" do
custom_field.update!(type:, required: true)
purchase_custom_field = described_class.build_from_custom_field(custom_field:, value: "")
purchase.purchase_custom_fields << purchase_custom_field
expect(purchase_custom_field).not_to be_valid
expect(purchase_custom_field.errors.full_messages).to include("Value can't be blank")
purchase_custom_field.value = "value"
expect(purchase_custom_field).to be_valid
end
it "allows blank for an optional #{type} custom field" do
custom_field.update!(type:, required: false)
purchase_custom_field = described_class.build_from_custom_field(custom_field:, value: "")
purchase.purchase_custom_fields << purchase_custom_field
expect(purchase_custom_field).to be_valid
end
end
it "requires value for checkbox custom field if required is true" do
custom_field.update!(type: CustomField::TYPE_CHECKBOX, required: true)
purchase_custom_field = described_class.build_from_custom_field(custom_field:, value: false)
purchase.purchase_custom_fields << purchase_custom_field
expect(purchase_custom_field).not_to be_valid
expect(purchase_custom_field.errors.full_messages).to include("Value can't be blank")
purchase_custom_field.value = true
expect(purchase_custom_field).to be_valid
end
it "allows false for an optional checkbox custom field" do
custom_field.update!(type: CustomField::TYPE_CHECKBOX, required: false)
purchase_custom_field = described_class.build_from_custom_field(custom_field:, value: false)
purchase.purchase_custom_fields << purchase_custom_field
expect(purchase_custom_field).to be_valid
end
it "requires value for terms custom field to be true" do
custom_field.update!(name: "https://test", type: CustomField::TYPE_TERMS, required: true)
purchase_custom_field = described_class.build_from_custom_field(custom_field:, value: false)
purchase.purchase_custom_fields << purchase_custom_field
expect(purchase_custom_field).not_to be_valid
expect(purchase_custom_field.errors.full_messages).to include("Value can't be blank")
purchase_custom_field.value = true
expect(purchase_custom_field).to be_valid
end
it "requires file for file custom field if required is true" do
custom_field.update!(type: CustomField::TYPE_FILE, required: true)
purchase_custom_field = described_class.build_from_custom_field(custom_field:, value: nil)
purchase.purchase_custom_fields << purchase_custom_field
expect(purchase_custom_field).not_to be_valid
expect(purchase_custom_field.errors.full_messages).to include("Value can't be blank")
blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "smilie.png")
purchase_custom_field.files.attach(blob)
expect(purchase_custom_field).to be_valid
end
it "allows blank for an optional file custom field" do
custom_field.update!(type: CustomField::TYPE_FILE, required: false)
purchase_custom_field = described_class.build_from_custom_field(custom_field:, value: nil)
purchase.purchase_custom_fields << purchase_custom_field
expect(purchase_custom_field).to be_valid
end
it "requires value for file custom field to be nil" do
custom_field.update!(type: CustomField::TYPE_FILE, required: true)
purchase_custom_field = described_class.build_from_custom_field(custom_field:, value: "value")
blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "smilie.png")
purchase_custom_field.files.attach(blob)
purchase.purchase_custom_fields << purchase_custom_field
expect(purchase_custom_field).not_to be_valid
expect(purchase_custom_field.errors.full_messages).to include("Value cannot be set for file custom field")
purchase_custom_field.value = nil
expect(purchase_custom_field).to be_valid
end
end
describe ".build_from_custom_field" do
it "assigns attributes correctly" do
custom_field = create(:custom_field)
purchase_custom_field = described_class.build_from_custom_field(custom_field:, value: "test")
expect(purchase_custom_field).to have_attributes(
custom_field:,
name: custom_field.name,
field_type: custom_field.type,
value: "test"
)
end
end
describe "#value" do
it "returns the value cast to boolean if the field type is a boolean type" do
purchase_custom_field = described_class.new(field_type: CustomField::TYPE_CHECKBOX, value: "false")
expect(purchase_custom_field.value).to eq(false)
purchase_custom_field = described_class.new(field_type: CustomField::TYPE_TERMS, value: "yes")
expect(purchase_custom_field.value).to eq(true)
end
it "returns the value as is if the field type is not a boolean type" do
purchase_custom_field = described_class.new(field_type: CustomField::TYPE_TEXT, value: "value")
expect(purchase_custom_field.value).to eq("value")
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_purchase_spec.rb | spec/models/upsell_purchase_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UpsellPurchase do
describe "validations" do
context "when the upsell doesn't belong to the purchase's product" do
let(:upsell_purchase) { build(:upsell_purchase, selected_product: create(:product), purchase: create(:purchase, link: create(:product))) }
it "adds an error" do
expect(upsell_purchase.valid?).to eq(false)
expect(upsell_purchase.errors.full_messages.first).to eq("The upsell must belong to the product being purchased.")
end
end
context "when the upsell belongs to the purchase's product" do
let(:upsell_purchase) { build(:upsell_purchase) }
it "doesn't add an error" do
expect(upsell_purchase.valid?).to eq(true)
end
end
context "when the upsell purchase doesn't have an upsell variant for its upsell" do
let(:upsell_purchase) { build(:upsell_purchase, upsell: create(:upsell)) }
it "adds an error" do
expect(upsell_purchase.valid?).to eq(false)
expect(upsell_purchase.errors.full_messages.first).to eq("The upsell purchase must have an associated upsell variant.")
end
end
context "when the upsell purchase has an upsell variant for its upsell" do
let(:seller) { build(:named_seller) }
let(:product) { build(:product_with_digital_versions, user: seller) }
let(:upsell) { build(:upsell, seller:, product:) }
let(:upsell_variant) { build(:upsell_variant, upsell:, selected_variant: product.alive_variants.first, offered_variant: product.alive_variants.second) }
let(:upsell_purchase) { build(:upsell_purchase, upsell:, upsell_variant:, selected_product: product) }
it "doesn't add an error" do
expect(upsell_purchase.valid?).to eq(true)
end
end
end
describe "#as_json" do
let(:seller) { create(:named_seller) }
let(:product1) { create(:product_with_digital_versions, name: "Product 1", user: seller, price_cents: 1000) }
let(:product2) { create(:product_with_digital_versions, name: "Product 2", user: seller, price_cents: 500) }
context "for an upsell" do
let(:upsell) { create(:upsell, product: product2, name: "Upsell 2", seller:) }
let(:upsell_variant) { create(:upsell_variant, upsell:, selected_variant: product2.alive_variants.first, offered_variant: product2.alive_variants.second) }
let(:upsell_purchase) { create(:upsell_purchase, upsell:, upsell_variant:, selected_product: product2) }
it "returns the upsell purchase encoded in an object" do
expect(upsell_purchase.as_json).to eq(
{
name: "Upsell 2",
discount: nil,
selected_product: product2.name,
selected_version: product2.alive_variants.first.name,
}
)
end
end
context "for a cross-sell" do
let(:cross_sell) { create(:upsell, selected_products: [product2], product: product1, variant: product1.alive_variants.second, name: "Upsell 1", seller:, offer_code: create(:offer_code, products: [product1], user: seller), cross_sell: true) }
let(:upsell_purchase) { create(:upsell_purchase, upsell: cross_sell, selected_product: product2) }
before do
upsell_purchase.purchase.create_purchase_offer_code_discount!(offer_code: cross_sell.offer_code, offer_code_amount: 100, pre_discount_minimum_price_cents: 100)
cross_sell.offer_code.update!(amount_cents: 200)
end
it "returns the upsell purchase encoded in an object" do
expect(upsell_purchase.as_json).to eq(
{
name: "Upsell 1",
discount: "$1",
selected_product: product2.name,
selected_version: nil,
}
)
end
context "when the upsell is a content upsell" do
let(:seller) { create(:named_seller) }
let(:purchase) { create(:purchase, link: product1) }
let(:content_upsell) do
create(
:upsell,
name: "Content Upsell",
product: product1,
seller: seller,
is_content_upsell: true,
cross_sell: true
)
end
let(:upsell_purchase) do
create(
:upsell_purchase,
upsell: content_upsell,
purchase: purchase,
selected_product: nil
)
end
it "returns nil for selected_product" do
expect(upsell_purchase.as_json).to match(
name: "Content Upsell",
discount: "$1",
selected_product: nil,
selected_version: nil,
)
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/denmark_bank_account_spec.rb | spec/models/denmark_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DenmarkBankAccount do
describe "#bank_account_type" do
it "returns denmark" do
expect(create(:denmark_bank_account).bank_account_type).to eq("DK")
end
end
describe "#country" do
it "returns DK" do
expect(create(:denmark_bank_account).country).to eq("DK")
end
end
describe "#currency" do
it "returns dkn" do
expect(create(:denmark_bank_account).currency).to eq("dkk")
end
end
describe "#routing_number" do
it "returns nil" do
expect(create(:denmark_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(:denmark_bank_account, account_number_last_four: "2874").account_number_visual).to eq("DK******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(:denmark_bank_account)).to be_valid
expect(build(:denmark_bank_account, account_number: "DK 5000 4004 4011 6243")).to be_valid
dk_bank_account = build(:denmark_bank_account, account_number: "DK12345")
expect(dk_bank_account).to_not be_valid
expect(dk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
dk_bank_account = build(:denmark_bank_account, account_number: "DE61109010140000071219812874")
expect(dk_bank_account).to_not be_valid
expect(dk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
dk_bank_account = build(:denmark_bank_account, account_number: "8937040044053201300000")
expect(dk_bank_account).to_not be_valid
expect(dk_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
dk_bank_account = build(:denmark_bank_account, account_number: "DKABCDE")
expect(dk_bank_account).to_not be_valid
expect(dk_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/laos_bank_account_spec.rb | spec/models/laos_bank_account_spec.rb | # frozen_string_literal: true
describe LaosBankAccount do
describe "#bank_account_type" do
it "returns LA" do
expect(create(:laos_bank_account).bank_account_type).to eq("LA")
end
end
describe "#country" do
it "returns LA" do
expect(create(:laos_bank_account).country).to eq("LA")
end
end
describe "#currency" do
it "returns lak" do
expect(create(:laos_bank_account).currency).to eq("lak")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:laos_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAALALAXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:laos_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
expect(build(:laos_bank_account)).to be_valid
expect(build(:laos_bank_account, account_number: "000123456789")).to be_valid
expect(build(:laos_bank_account, account_number: "0")).to be_valid
expect(build(:laos_bank_account, account_number: "000012345678910111")).to be_valid
la_bank_account = build(:laos_bank_account, account_number: "0000123456789101111")
expect(la_bank_account).to_not be_valid
expect(la_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/poland_bank_account_spec.rb | spec/models/poland_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PolandBankAccount do
describe "#bank_account_type" do
it "returns poland" do
expect(create(:poland_bank_account).bank_account_type).to eq("PL")
end
end
describe "#country" do
it "returns PL" do
expect(create(:poland_bank_account).country).to eq("PL")
end
end
describe "#currency" do
it "returns pln" do
expect(create(:poland_bank_account).currency).to eq("pln")
end
end
describe "#routing_number" do
it "returns nil" do
expect(create(:poland_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(:poland_bank_account, account_number_last_four: "2874").account_number_visual).to eq("PL******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(:poland_bank_account)).to be_valid
expect(build(:poland_bank_account, account_number: "PL61 1090 1014 0000 0712 1981 2874")).to be_valid
pl_bank_account = build(:poland_bank_account, account_number: "PL12345")
expect(pl_bank_account).to_not be_valid
expect(pl_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
pl_bank_account = build(:poland_bank_account, account_number: "DE61109010140000071219812874")
expect(pl_bank_account).to_not be_valid
expect(pl_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
pl_bank_account = build(:poland_bank_account, account_number: "8937040044053201300000")
expect(pl_bank_account).to_not be_valid
expect(pl_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
pl_bank_account = build(:poland_bank_account, account_number: "PLABCDE")
expect(pl_bank_account).to_not be_valid
expect(pl_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/direct_affiliate_spec.rb | spec/models/direct_affiliate_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DirectAffiliate do
let(:product) { create(:product, price_cents: 10_00, unique_permalink: "p") }
let(:seller) { product.user }
let(:affiliate_user) { create(:affiliate_user) }
let(:direct_affiliate) { create(:direct_affiliate, affiliate_user:, seller:, affiliate_basis_points: 1000, products: [product]) }
describe "associations" do
it { is_expected.to belong_to(:seller).class_name("User") }
end
describe "validations" do
it { is_expected.to validate_presence_of(:affiliate_basis_points) }
describe "eligible_for_stripe_payments" do
let(:seller) { create(:user) }
let(:affiliate_user) { create(:user) }
let(:direct_affiliate) { build(:direct_affiliate, seller:, affiliate_user:) }
context "when affiliate user has a Brazilian Stripe Connect account" do
before do
allow(affiliate_user).to receive(:has_brazilian_stripe_connect_account?).and_return(true)
allow(seller).to receive(:has_brazilian_stripe_connect_account?).and_return(false)
end
it "is invalid" do
expect(direct_affiliate).not_to be_valid
expect(direct_affiliate.errors[:base]).to include(
"This user cannot be added as an affiliate because they use a Brazilian Stripe account."
)
end
end
context "when seller has a Brazilian Stripe Connect account" do
before do
allow(affiliate_user).to receive(:has_brazilian_stripe_connect_account?).and_return(false)
allow(seller).to receive(:has_brazilian_stripe_connect_account?).and_return(true)
end
it "is invalid" do
expect(direct_affiliate).not_to be_valid
expect(direct_affiliate.errors[:base]).to include(
"You cannot add an affiliate because you are using a Brazilian Stripe account."
)
end
end
context "when neither user has a Brazilian Stripe Connect account" do
before do
allow(seller).to receive(:has_brazilian_stripe_connect_account?).and_return(false)
allow(affiliate_user).to receive(:has_brazilian_stripe_connect_account?).and_return(false)
end
it "is valid" do
expect(direct_affiliate).to be_valid
end
end
end
end
describe "flags" do
it "has a `apply_to_all_products` flag" do
flag_on = create(:direct_affiliate, apply_to_all_products: true)
flag_off = create(:direct_affiliate, apply_to_all_products: false)
expect(flag_on.apply_to_all_products).to be true
expect(flag_off.apply_to_all_products).to be false
end
it "has a `send_posts` flag" do
flag_on = create(:direct_affiliate, send_posts: true)
flag_off = create(:direct_affiliate, send_posts: false)
expect(flag_on.send_posts).to be true
expect(flag_off.send_posts).to be false
end
end
describe "destination_url validation" do
let(:affiliate) { build(:direct_affiliate) }
it "does not allow invalid destination urls" do
affiliate.destination_url = "saywhat"
expect(affiliate.valid?).to be(false)
affiliate.destination_url = "saywhat.com"
expect(affiliate.valid?).to be(false)
affiliate.destination_url = "httpsaywhat.com"
expect(affiliate.valid?).to be(false)
affiliate.destination_url = "ftp://saywhat.com"
expect(affiliate.valid?).to be(false)
end
it "allows valid destination urls" do
affiliate.destination_url = "http://saywhat.com/something?this=that"
expect(affiliate.valid?).to be(true)
affiliate.destination_url = "https://saywhat.com"
expect(affiliate.valid?).to be(true)
end
end
describe ".cookie_lifetime" do
it "returns 30 days" do
expect(described_class.cookie_lifetime).to eq 30.days
end
end
describe "#final_destination_url", :elasticsearch_wait_for_refresh do
let(:affiliate) { create(:direct_affiliate, destination_url:) }
let(:seller) { affiliate.seller }
context "when destination URL is set" do
let(:destination_url) { "https://gumroad.com/foo" }
context "when apply_to_all_products is false" do
it "returns the seller subdomain" do
expect(affiliate.final_destination_url).to eq seller.subdomain_with_protocol
end
end
context "when apply_to_all_products is true" do
it "returns the destination URL" do
affiliate.update!(apply_to_all_products: true)
expect(affiliate.final_destination_url(product:)).to eq destination_url
end
end
end
context "when destination URL is not set" do
let(:destination_url) { nil }
context "but product is provided" do
let(:product) { create(:product, user: affiliate.seller) }
it "returns the product destination URL if it exists" do
create(:product_affiliate, affiliate:, product:, destination_url: "https://gumroad.com/bar")
expect(affiliate.final_destination_url(product:)).to eq "https://gumroad.com/bar"
end
it "returns the product URL if they're an affiliate for that product" do
affiliate.products << product
expect(affiliate.final_destination_url(product:)).to eq product.long_url
end
context "but is not affiliated" do
it "returns the sole affiliated product's URL if they are affiliated for a single product" do
affiliated_product = create(:product, user: seller)
affiliate.products << affiliated_product
expect(affiliate.final_destination_url(product:)).to eq affiliated_product.long_url
end
it "returns the seller subdomain if they are an affiliate for all products" do
affiliate.update!(apply_to_all_products: true)
affiliate.products << create(:product, user: seller)
affiliate.products << create(:product, user: seller)
expect(affiliate.final_destination_url(product:)).to eq seller.subdomain_with_protocol
end
it "falls back to the seller subdomain if it exists" do
expect(affiliate.final_destination_url(product:)).to eq seller.subdomain_with_protocol
end
end
end
context "and product is not provided" do
context "and they are affiliated for a single product" do
it "returns the affiliated product's URL" do
affiliated_product = create(:product, user: seller)
affiliate.products << affiliated_product
expect(affiliate.final_destination_url).to eq affiliated_product.long_url
end
it "returns the product's destination URL if it is set" do
create(:product_affiliate, affiliate:, product: create(:product, user: seller), destination_url: "https://gumroad.com/bar")
expect(affiliate.final_destination_url).to eq "https://gumroad.com/bar"
end
end
it "returns the seller subdomain if they are an affiliate for all products" do
affiliate.update!(apply_to_all_products: true)
affiliated_product = create(:product, user: seller)
affiliate.products << affiliated_product
expect(affiliate.final_destination_url).to eq seller.subdomain_with_protocol
end
it "falls back to the seller subdomain" do
expect(affiliate.final_destination_url).to eq seller.subdomain_with_protocol
end
end
context "when seller username is set" do
before do
seller.update!(username: "barnabas")
end
context "when apply_to_all_products is false" do
it "returns the last product url when destination URL is set on the affiliate" do
direct_affiliate.destination_url = "https://saywhat.com"
expect(direct_affiliate.final_destination_url).to eq(product.long_url)
end
it "falls back to user profile page url if the affiliate is associated with multiple products" do
direct_affiliate.products << create(:product)
expect(direct_affiliate.final_destination_url).to eq(seller.subdomain_with_protocol)
end
end
context "when apply_to_all_products is true" do
it "falls back to the user profile page even if only 1 affiliated product" do
direct_affiliate.apply_to_all_products = true
direct_affiliate.save!
expect(direct_affiliate.final_destination_url).to eq(seller.subdomain_with_protocol)
end
end
end
end
end
describe "schedule_workflow_jobs" do
let!(:affiliate_workflow) do
workflow = create(:workflow, seller:, link: nil, workflow_type: Workflow::AFFILIATE_TYPE, published_at: 1.week.ago)
create_list(:installment, 2, workflow:).each do |post|
create(:installment_rule, installment: post, delayed_delivery_time: 3.days)
end
workflow
end
let!(:seller_workflow) do
workflow = create(:workflow, seller:, link: nil, workflow_type: Workflow::SELLER_TYPE, published_at: 1.week.ago)
create(:installment_rule, delayed_delivery_time: 1.day, installment: create(:installment, workflow:))
workflow
end
it "enqueues 2 installment jobs when an affiliate is created" do
direct_affiliate.schedule_workflow_jobs
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(2)
end
it "does not enqueue installment jobs when the workflow is marked as member_cancellation and an affiliate is created" do
affiliate_workflow.update!(workflow_trigger: "member_cancellation")
direct_affiliate.schedule_workflow_jobs
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(0)
end
end
describe "#send_invitation_email after_commit callback" do
context "when prevent_sending_invitation_email is set to true" do
it "does not send invitation email" do
expect do
create(:direct_affiliate, prevent_sending_invitation_email: true)
end.to_not have_enqueued_mail(AffiliateMailer, :direct_affiliate_invitation)
end
end
context "when prevent_sending_invitation_email is not set" do
it "sends invitation email" do
expect do
create(:direct_affiliate)
end.to have_enqueued_mail(AffiliateMailer, :direct_affiliate_invitation)
end
end
context "when prevent_sending_invitation_email_to_seller is set" do
it "enqueues the invitation mail with prevent_sending_invitation_email_to_seller set to true" do
expect do
create(:direct_affiliate, prevent_sending_invitation_email_to_seller: true)
end.to have_enqueued_mail(AffiliateMailer, :direct_affiliate_invitation).with(anything, true)
end
end
end
describe "#update_posts_subscription" do
it "updates affiliate user's all affiliate records for the creator as per send_posts parameter" do
direct_affiliate_2 = create(:direct_affiliate, affiliate_user:, seller:, deleted_at: Time.current)
direct_affiliate.update_posts_subscription(send_posts: false)
expect(direct_affiliate.reload.send_posts).to be false
expect(direct_affiliate_2.reload.send_posts).to be false
direct_affiliate.update_posts_subscription(send_posts: true)
expect(direct_affiliate.reload.send_posts).to be true
expect(direct_affiliate_2.reload.send_posts).to be true
end
end
describe "#eligible_for_purchase_credit?" do
let(:affiliate) { create(:direct_affiliate) }
let(:product) { create(:product, user: affiliate.seller) }
context "when affiliated with the product" do
before do
affiliate.products << product
end
it "returns true if the purchase did not come through Discover" do
expect(affiliate.eligible_for_purchase_credit?(product:, was_recommended: false)).to eq true
end
it "returns false if the purchase came through Discover" do
expect(affiliate.eligible_for_purchase_credit?(product:, was_recommended: true)).to eq false
end
it "returns false if the affiliate is suspended" do
user = affiliate.affiliate_user
admin = create(:admin_user)
user.flag_for_fraud!(author_id: admin.id)
user.suspend_for_fraud!(author_id: admin.id)
expect(affiliate.eligible_for_purchase_credit?(product:)).to eq false
end
end
it "returns false if the affiliate is not affiliated for the product" do
expect(affiliate.eligible_for_purchase_credit?(product:)).to eq false
end
it "returns false if the affiliate is deleted" do
affiliate = create(:direct_affiliate, deleted_at: 1.day.ago, products: [product])
expect(affiliate.eligible_for_purchase_credit?(product:)).to eq 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.affiliate_user, country: "BR")
affiliate.affiliate_user.update!(check_merchant_account_is_linked: true)
expect(affiliate.affiliate_user.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq brazilian_stripe_account
expect(affiliate.eligible_for_credit?).to be false
end
end
describe "#basis_points" do
let(:affiliate) { create(:direct_affiliate, apply_to_all_products:, affiliate_basis_points: 10_00) }
let(:product_affiliate) { create(:product_affiliate, affiliate:, affiliate_basis_points: product_affiliate_basis_points) }
context "when no product_id is provided" do
let(:product_affiliate_basis_points) { nil }
context "when the affiliate applies to all products" do
let(:apply_to_all_products) { true }
it "returns the affiliate's basis points" do
expect(affiliate.basis_points).to eq 10_00
end
end
context "when the affiliate does not apply to all products" do
let(:apply_to_all_products) { false }
it "returns the affiliate's basis points" do
expect(affiliate.basis_points).to eq 10_00
end
end
end
context "when product_id is provided" do
context "when the affiliate applies to all products" do
let(:apply_to_all_products) { true }
let(:product_affiliate_basis_points) { 20_00 }
it "returns the affiliate's basis points" do
expect(affiliate.basis_points(product_id: product_affiliate.link_id)).to eq 10_00
end
end
context "when affiliate does not apply to all products" do
let(:apply_to_all_products) { false }
context "and product affiliate commission is set" do
let(:product_affiliate_basis_points) { 20_00 }
it "returns the product affiliate's basis points" do
expect(affiliate.basis_points(product_id: product_affiliate.link_id)).to eq 20_00
end
end
context "and product affiliate commission is not set" do
let(:product_affiliate_basis_points) { nil }
it "returns the affiliate's basis points" do
expect(affiliate.basis_points(product_id: product_affiliate.link_id)).to eq 10_00
end
end
end
end
end
context "AudienceMember" do
let(:affiliate) { create(:direct_affiliate) }
describe "#should_be_audience_member?" do
it "only returns true for expected cases" do
affiliate = create(:direct_affiliate)
expect(affiliate.should_be_audience_member?).to eq(true)
affiliate = create(:direct_affiliate, send_posts: false)
expect(affiliate.should_be_audience_member?).to eq(false)
affiliate = create(:direct_affiliate, deleted_at: Time.current)
expect(affiliate.should_be_audience_member?).to eq(false)
affiliate = create(:direct_affiliate, deleted_at: Time.current)
expect(affiliate.should_be_audience_member?).to eq(false)
affiliate = create(:direct_affiliate)
affiliate.affiliate_user.update_column(:email, nil)
expect(affiliate.should_be_audience_member?).to eq(false)
affiliate.affiliate_user.update_column(:email, "some-invalid-email")
expect(affiliate.should_be_audience_member?).to eq(false)
end
end
it "adds member when product is added" do
member_relation = AudienceMember.where(seller: affiliate.seller, email: affiliate.affiliate_user.email)
expect(member_relation.exists?).to eq(false)
affiliate.products << create(:product, user: affiliate.seller)
affiliate.products << create(:product, user: affiliate.seller)
expect(member_relation.count).to eq(1)
create(:product_affiliate, affiliate:, product: create(:product, user: affiliate.seller))
member = member_relation.first
expect(member.details["affiliates"].size).to eq(3)
expect(member.details["affiliates"].map { _1["product_id"] }).to match_array(affiliate.products.map(&:id))
end
it "removes member when product affiliation is removed" do
member_relation = AudienceMember.where(seller: affiliate.seller, email: affiliate.affiliate_user.email)
affiliate.products << create(:product, user: affiliate.seller)
affiliate.products << create(:product, user: affiliate.seller)
products = affiliate.products.to_a
member = member_relation.first
ProductAffiliate.find_by(affiliate:, product: products.first).destroy!
member.reload
expect(member.details["affiliates"].size).to eq(1)
expect(member.details["affiliates"].map { _1["product_id"] }).to match_array([products.second.id])
affiliate.products.delete(products.second)
expect do
member.reload
end.to raise_error(ActiveRecord::RecordNotFound)
end
it "removes the member when the affiliate user unsubscribes from a seller post" do
affiliate = create(:direct_affiliate)
product = create(:product, user: affiliate.seller)
affiliate.products << product
member_relation = AudienceMember.where(seller: affiliate.seller, email: affiliate.affiliate_user.email)
expect(member_relation.exists?).to eq(true)
affiliate.update(send_posts: false)
expect(member_relation.exists?).to eq(false)
end
end
describe "#product_sales_info" do
let(:affiliate) { create(:direct_affiliate) }
let(:product) { create(:product, user: affiliate.seller, name: "Product") }
let(:archived_product) { create(:product, user: affiliate.seller, name: "Archived", archived: true) }
let(:deleted_product) { create(:product, user: affiliate.seller, name: "Deleted", deleted_at: 2.days.ago) }
let!(:product_without_affiliate_sales) { create(:product, user: affiliate.seller, archived: true) }
before do
create(:product_affiliate, affiliate:, product:, affiliate_basis_points: 40_00, destination_url: "https://example.com")
create(:product_affiliate, affiliate:, product: archived_product, affiliate_basis_points: 40_00, destination_url: "https://example.com")
create(:product_affiliate, affiliate:, product: deleted_product, affiliate_basis_points: 20_00, destination_url: "https://example.com")
create(:purchase_with_balance, link: deleted_product, affiliate_credit_cents: 100, affiliate:)
create(:purchase_with_balance, link: product, affiliate_credit_cents: 100, affiliate:)
create_list(:purchase_with_balance, 2, link: archived_product, affiliate_credit_cents: 100, affiliate:)
end
it "returns sales data for products with affiliate sales" do
expect(affiliate.product_sales_info).to eq(
product.external_id_numeric => { volume_cents: 100, sales_count: 1 },
archived_product.external_id_numeric => { volume_cents: 200, sales_count: 2 },
deleted_product.external_id_numeric => { volume_cents: 100, sales_count: 1 }
)
end
end
describe "#as_json" do
let(:affiliate_user) { create(:affiliate_user, username: "creator") }
let(:affiliate) { create(:direct_affiliate, affiliate_user:, apply_to_all_products: true) }
let!(:product) { create(:product, name: "Gumbot bits", user: affiliate.seller) }
before do
create(:product_affiliate, affiliate:, product:, affiliate_basis_points: affiliate.affiliate_basis_points, destination_url: "https://example.com")
end
it "returns a hash of custom attributes" do
create(:product, name: "Unaffiliated product we ignore", user: affiliate.seller)
create(:product, name: "Unaffiliated product we ignore 2", user: affiliate.seller)
expect(affiliate.as_json).to eq(
{
email: affiliate_user.email,
destination_url: affiliate.destination_url,
affiliate_user_name: "creator",
fee_percent: 3,
id: affiliate.external_id,
apply_to_all_products: false,
products: [
{
id: product.external_id_numeric,
name: "Gumbot bits",
fee_percent: 3,
referral_url: affiliate.referral_url_for_product(product),
destination_url: "https://example.com",
}
],
product_referral_url: affiliate.referral_url_for_product(product),
}
)
end
context "when affiliate has multiple products with the same commission percentage" do
let(:product2) { create(:product, name: "ChatGPT4 prompts", user: affiliate.seller, archived: true) }
let(:product3) { create(:product, name: "Beautiful banner", user: affiliate.seller) }
before do
create(:product_affiliate, affiliate:, product: product2, affiliate_basis_points: affiliate.affiliate_basis_points)
create(:product_affiliate, affiliate:, product: product3, affiliate_basis_points: affiliate.affiliate_basis_points)
end
it "returns a hash of custom attributes with apply_to_all_products set to true" do
expect(affiliate.as_json).to eq(
{
email: affiliate_user.email,
destination_url: affiliate.destination_url,
affiliate_user_name: "creator",
fee_percent: 3,
id: affiliate.external_id,
apply_to_all_products: true,
products: [
{
id: product.external_id_numeric,
name: "Gumbot bits",
fee_percent: 3,
referral_url: affiliate.referral_url_for_product(product),
destination_url: "https://example.com",
},
{
id: product2.external_id_numeric,
name: "ChatGPT4 prompts",
fee_percent: 3,
referral_url: affiliate.referral_url_for_product(product2),
destination_url: nil,
},
{
id: product3.external_id_numeric,
name: "Beautiful banner",
fee_percent: 3,
referral_url: affiliate.referral_url_for_product(product3),
destination_url: nil,
}
],
product_referral_url: affiliate.referral_url,
}
)
end
end
context "when affiliate has multiple products with product-specific commission percentages" do
let(:product_2) { create(:product, name: "ChatGPT4 prompts", user: affiliate.seller) }
let(:product_3) { create(:product, name: "Beautiful banner", user: affiliate.seller) }
before do
create(:product_affiliate, affiliate:, product: product_2, affiliate_basis_points: 45_00)
create(:product_affiliate, affiliate:, product: product_3, affiliate_basis_points: 23_00)
end
it "returns a hash of custom attributes with apply_to_all_products set to false" do
expect(affiliate.as_json).to eq(
{
email: affiliate_user.email,
destination_url: affiliate.destination_url,
affiliate_user_name: "creator",
fee_percent: 3,
id: affiliate.external_id,
apply_to_all_products: false,
products: [
{
id: product.external_id_numeric,
name: "Gumbot bits",
fee_percent: 3,
referral_url: affiliate.referral_url_for_product(product),
destination_url: "https://example.com",
},
{
id: product_2.external_id_numeric,
name: "ChatGPT4 prompts",
fee_percent: 45,
referral_url: affiliate.referral_url_for_product(product_2),
destination_url: nil,
},
{
id: product_3.external_id_numeric,
name: "Beautiful banner",
fee_percent: 23,
referral_url: affiliate.referral_url_for_product(product_3),
destination_url: nil,
}
],
product_referral_url: affiliate.referral_url,
}
)
end
end
end
describe "#products_data" do
let(:affiliate) { create(:direct_affiliate) }
let(:product) { create(:product, user: affiliate.seller, name: "Product") }
let!(:unaffiliated_product) { create(:product, user: affiliate.seller, name: "Unaffiliated Product") }
let(:archived_product) { create(:product, user: affiliate.seller, name: "Archived", archived: true) }
let!(:other_archived_product) { create(:product, user: affiliate.seller, archived: true) }
let!(:ineligible_product) { create(:product, :is_collab, user: affiliate.seller, name: "Ineligible Product") }
before do
create(:product_affiliate, affiliate:, product:, affiliate_basis_points: 40_00, destination_url: "https://example.com")
create(:product_affiliate, affiliate:, product: archived_product, affiliate_basis_points: 40_00, destination_url: "https://example.com")
end
it "returns data for all products" do
expect(affiliate.products_data).to eq(
[
{
destination_url: "https://example.com",
enabled: true,
fee_percent: 40,
id: product.external_id_numeric,
name: "Product",
referral_url: affiliate.referral_url_for_product(product),
sales_count: 0,
volume_cents: 0
},
{
destination_url: "https://example.com",
enabled: true,
fee_percent: 40,
id: archived_product.external_id_numeric,
name: "Archived",
referral_url: affiliate.referral_url_for_product(archived_product),
sales_count: 0,
volume_cents: 0
},
{
destination_url: nil,
enabled: false,
fee_percent: 3,
id: unaffiliated_product.external_id_numeric,
name: "Unaffiliated Product",
referral_url: affiliate.referral_url_for_product(unaffiliated_product),
sales_count: 0,
volume_cents: 0
}
])
end
context "when affiliate has credits" do
before do
create_list(:purchase_with_balance, 2, affiliate_credit_cents: 100, affiliate:, link: product)
create(:purchase_with_balance, affiliate_credit_cents: 100, affiliate:, link: archived_product)
end
it "returns the correct data" do
expect(affiliate.products_data).to eq(
[
{
destination_url: "https://example.com",
enabled: true,
fee_percent: 40,
id: product.external_id_numeric,
name: "Product",
referral_url: affiliate.referral_url_for_product(product),
sales_count: 2,
volume_cents: 200
},
{
destination_url: "https://example.com",
enabled: true,
fee_percent: 40,
id: archived_product.external_id_numeric,
name: "Archived",
referral_url: affiliate.referral_url_for_product(archived_product),
sales_count: 1,
volume_cents: 100
},
{
destination_url: nil,
enabled: false,
fee_percent: 3,
id: unaffiliated_product.external_id_numeric,
name: "Unaffiliated Product",
referral_url: affiliate.referral_url_for_product(unaffiliated_product),
sales_count: 0,
volume_cents: 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/rich_content_spec.rb | spec/models/rich_content_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RichContent do
describe "validations" do
describe "description" do
context "invalid descriptions" do
let(:invalid_descriptions) { ["not valid", ["also not valid"], [{ "type" => 2 }]] }
it "adds error when the description is invalid" do
invalid_descriptions.each do |invalid_description|
rich_content = build(:product_rich_content, description: invalid_description)
expect(rich_content).to be_invalid
expect(rich_content.errors.full_messages).to eq(["Content is invalid"])
end
end
end
context "valid descriptions" do
let(:valid_descriptions) { [[], [{ "type": "text", "text": "Trace" }], [{ "type": "text", "text": "Trace" }, { "type": "text", "marks": [{ "type": "italic" }], "text": "Q" }]] }
it "does not add errors for valid descriptions" do
valid_descriptions.each do |valid_description|
rich_content = build(:product_rich_content, description: valid_description)
expect(rich_content).to be_valid
end
end
end
end
end
describe "#embedded_product_file_ids_in_order" do
let(:product) { create(:product) }
let(:rich_content) { create(:product_rich_content, entity: product) }
it "returns the ids of the embedded product files in order" do
file1 = create(:listenable_audio, link: product, position: 0)
file2 = create(:product_file, link: product, position: 1, created_at: 2.days.ago)
file3 = create(:readable_document, link: product, position: 2)
file4 = create(:streamable_video, link: product, position: 3, created_at: 1.day.ago)
file5 = create(:listenable_audio, link: product, position: 4, created_at: 3.days.ago)
rich_content.update!(description: [
{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Hello" }] },
{ "type" => "image", "attrs" => { "src" => "https://example.com/album.jpg", "link" => nil } },
{ "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } },
{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "World" }] },
{ "type" => "blockquote", "content" => [
{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Inside blockquote" }] },
{ "type" => "fileEmbed", "attrs" => { "id" => file5.external_id, "uid" => SecureRandom.uuid } },
] },
{ "type" => "orderedList", "content" => [
{ "type" => "listItem", "content" => [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Ordered list item 1" }] }] },
{ "type" => "listItem", "content" => [
{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Ordered list item 2" }] },
{ "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } },
] },
{ "type" => "listItem", "content" => [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Ordered list item 3" }] }] },
] },
{ "type" => "bulletList", "content" => [
{ "type" => "listItem", "content" => [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Bullet list item 1" }] }] },
{ "type" => "listItem", "content" => [
{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Bullet list item 2" }] },
{ "type" => "fileEmbed", "attrs" => { "id" => file4.external_id, "uid" => SecureRandom.uuid } },
] },
{ "type" => "listItem", "content" => [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Bullet list item 3" }] }] },
] },
{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Lorem ipsum" }] },
{ "type" => "fileEmbed", "attrs" => { "id" => file3.external_id, "uid" => SecureRandom.uuid } },
])
expect(rich_content.embedded_product_file_ids_in_order).to eq([file2.id, file5.id, file1.id, file4.id, file3.id])
end
end
describe "#has_license_key?" do
let(:product) { create(:product) }
it "returns false if it does not contain license key" do
rich_content = create(:rich_content, entity: product, description: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Hello" }] }])
expect(rich_content.has_license_key?).to be(false)
end
it "returns true if it contains license key" do
rich_content = create(:rich_content, entity: product, description: [{ "type" => "licenseKey" }])
expect(rich_content.has_license_key?).to be(true)
end
it "returns true if it contains license key nested inside a list item" do
rich_content = create(:rich_content, entity: product, description: [{ "type" => "orderedList", "content" => [{ "type" => "listItem", "content" => [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Ordered list item 2" }] }, { "type" => "licenseKey" }] }] }])
expect(rich_content.has_license_key?).to be(true)
end
it "returns true if it contains license key nested inside a blockquote" do
rich_content = create(:rich_content, entity: product, description: [{ "type" => "blockquote", "content" => [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Inside blockquote" }] }, { "type" => "licenseKey" }] }])
expect(rich_content.has_license_key?).to be(true)
end
end
describe "#has_posts?" do
let(:product) { create(:product) }
it "returns false if it does not contain posts" do
rich_content = create(:rich_content, entity: product, description: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Hello" }] }])
expect(rich_content.has_posts?).to be(false)
end
it "returns true if it contains posts" do
rich_content = create(:rich_content, entity: product, description: [{ "type" => "posts" }])
expect(rich_content.has_posts?).to be(true)
end
it "returns true if it contains posts nested inside a list item" do
rich_content = create(:rich_content, entity: product, description: [{ "type" => "orderedList", "content" => [{ "type" => "listItem", "content" => [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Ordered list item 2" }] }, { "type" => "posts" }] }] }])
expect(rich_content.has_posts?).to be(true)
end
it "returns true if it contains posts nested inside a blockquote" do
rich_content = create(:rich_content, entity: product, description: [{ "type" => "blockquote", "content" => [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Inside blockquote" }] }, { "type" => "posts" }] }])
expect(rich_content.has_posts?).to be(true)
end
end
describe "#custom_field_nodes" do
let(:product) { create(:product) }
let(:paragraph_node) do
{
"type" => "paragraph",
"content" => [{ "type" => "text", "text" => "Item 1" }]
}
end
let(:short_answer_node_1) do
{
"type" => "shortAnswer",
"attrs" => {
"id" => "short-answer-id",
"label" => "Short answer field",
}
}
end
let(:short_answer_node_2) do
{
"type" => "shortAnswer",
"attrs" => {
"id" => "short-answer-id-2",
"label" => "Short answer field 2",
}
}
end
let(:long_answer_node_1) do
{
"type" => "longAnswer",
"attrs" => {
"id" => "long-answer-id",
"label" => "Long answer field",
}
}
end
let(:file_upload_node) do
{
"type" => "fileUpload",
"attrs" => {
"id" => "file-upload-id",
}
}
end
it "parses out deeply nested custom field nodes in order" do
description = [
{
"type" => "orderedList",
"attrs" => { "start" => 1 },
"content" => [
{
"type" => "listItem",
"content" => [
paragraph_node,
short_answer_node_1,
]
},
]
},
{
"type" => "bulletList",
"content" => [
{
"type" => "listItem",
"content" => [
paragraph_node,
long_answer_node_1,
]
},
]
},
{
"type" => "blockquote",
"content" => [
paragraph_node,
short_answer_node_2,
]
},
paragraph_node,
file_upload_node,
]
rich_content = create(:rich_content, entity: product, description:)
expect(rich_content.custom_field_nodes).to eq(
[
short_answer_node_1,
long_answer_node_1,
short_answer_node_2,
file_upload_node,
]
)
end
end
describe "callbacks" do
describe "#reset_moderated_by_iffy_flag" do
let(:product) { create(:product, moderated_by_iffy: true) }
let(:rich_content) { create(:rich_content, entity: product) }
context "when description is changed" do
it "resets moderated_by_iffy flag on the associated product" do
expect do
rich_content.update!(description: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Updated content" }] }])
end.to change { product.reload.moderated_by_iffy }.from(true).to(false)
end
end
context "when description is not changed" do
it "does not reset moderated_by_iffy flag on the associated product" do
expect do
rich_content.update!(updated_at: Time.current)
end.not_to change { product.reload.moderated_by_iffy }
end
end
context "when rich_content is not alive" do
it "does not reset moderated_by_iffy flag on the associated product" do
rich_content.update!(deleted_at: Time.current)
expect do
rich_content.update!(description: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Updated content" }] }])
end.not_to change { product.reload.moderated_by_iffy }
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/jamaica_bank_account_spec.rb | spec/models/jamaica_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe JamaicaBankAccount do
describe "#bank_account_type" do
it "returns JM" do
expect(create(:jamaica_bank_account).bank_account_type).to eq("JM")
end
end
describe "#country" do
it "returns JM" do
expect(create(:jamaica_bank_account).country).to eq("JM")
end
end
describe "#currency" do
it "returns jmd" do
expect(create(:jamaica_bank_account).currency).to eq("jmd")
end
end
describe "#bank_code" do
it "is an alias for bank_number" do
ba = create(:jamaica_bank_account, bank_number: "123")
expect(ba.bank_code).to eq("123")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:jamaica_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789")
end
end
describe "#validate_bank_code" do
it "allows 3 digits only" do
expect(build(:jamaica_bank_account, bank_number: "123")).to be_valid
expect(build(:jamaica_bank_account, bank_number: "12")).not_to be_valid
expect(build(:jamaica_bank_account, bank_number: "1234")).not_to be_valid
expect(build(:jamaica_bank_account, bank_number: "abc")).not_to be_valid
end
end
describe "#validate_branch_code" do
it "allows 5 digits only" do
expect(build(:jamaica_bank_account, branch_code: "12345")).to be_valid
expect(build(:jamaica_bank_account, branch_code: "1234")).not_to be_valid
expect(build(:jamaica_bank_account, branch_code: "123456")).not_to be_valid
expect(build(:jamaica_bank_account, branch_code: "abcde")).not_to be_valid
end
end
describe "#validate_account_number" do
it "allows 1 to 18 digits" do
expect(build(:jamaica_bank_account, account_number: "1")).to be_valid
expect(build(:jamaica_bank_account, account_number: "123456789012345678")).to be_valid
expect(build(:jamaica_bank_account, account_number: "1234567890123456789")).not_to be_valid
expect(build(:jamaica_bank_account, account_number: "abc")).not_to be_valid
end
end
describe "#to_hash" do
it "returns the correct hash representation" do
ba = create(:jamaica_bank_account, bank_number: "123", branch_code: "12345", account_number_last_four: "5678")
hash = ba.to_hash
expect(hash[:routing_number]).to eq("123-12345")
expect(hash[:account_number]).to eq("******5678")
expect(hash[:bank_account_type]).to eq("JM")
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_info_charge.rb | spec/models/email_info_charge.rb | # frozen_string_literal: true
require "spec_helper"
describe EmailInfoCharge do
describe "validations" do
it "requires charge_id and email_info_id" do
email_info_charge = EmailInfoCharge.new
expect(email_info_charge).to_not be_valid
expect(email_info_charge.errors.full_messages).to include("Charge must exist")
expect(email_info_charge.errors.full_messages).to include("Email info must exist")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/guatemala_bank_account_spec.rb | spec/models/guatemala_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GuatemalaBankAccount do
describe "#bank_account_type" do
it "returns GT" do
expect(create(:guatemala_bank_account).bank_account_type).to eq("GT")
end
end
describe "#country" do
it "returns GT" do
expect(create(:guatemala_bank_account).country).to eq("GT")
end
end
describe "#currency" do
it "returns gtq" do
expect(create(:guatemala_bank_account).currency).to eq("gtq")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:guatemala_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAAGTGCXYZ")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:guatemala_bank_account, account_number_last_four: "7890").account_number_visual).to eq("******7890")
end
end
describe "#validate_bank_code" do
it "allows 8 to 11 characters only" do
expect(build(:guatemala_bank_account, bank_code: "AAAAGTGCXYZ")).to be_valid
expect(build(:guatemala_bank_account, bank_code: "AAAAGTGC")).to be_valid
expect(build(:guatemala_bank_account, bank_code: "AAAAGTG")).not_to be_valid
expect(build(:guatemala_bank_account, bank_code: "AAAAGTGCXYZZ")).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/australian_bank_account_spec.rb | spec/models/australian_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe AustralianBankAccount do
describe "bsb_number" do
describe "is 6 digits" do
let(:australian_bank_account) { build(:australian_bank_account, bsb_number: "062111") }
it "is valid" do
expect(australian_bank_account).to be_valid
end
end
describe "nil" do
let(:australian_bank_account) { build(:australian_bank_account, bsb_number: nil) }
it "is not valid" do
expect(australian_bank_account).not_to be_valid
end
end
describe "is 5 digits" do
let(:australian_bank_account) { build(:australian_bank_account, bsb_number: "12345") }
it "is not valid" do
expect(australian_bank_account).not_to be_valid
end
end
describe "is 7 digits" do
let(:australian_bank_account) { build(:australian_bank_account, bsb_number: "1234567") }
it "is not valid" do
expect(australian_bank_account).not_to be_valid
end
end
describe "contains alpha characters" do
let(:australian_bank_account) { build(:australian_bank_account, bsb_number: "12345a") }
it "is not valid" do
expect(australian_bank_account).not_to be_valid
end
end
end
describe "routing_number" do
let(:australian_bank_account) { build(:australian_bank_account, bsb_number: "453780") }
it "is a concat of institution_number, hyphen and bsb_number" do
expect(australian_bank_account.routing_number).to eq("453780")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/singaporean_bank_account_spec.rb | spec/models/singaporean_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SingaporeanBankAccount do
describe "#bank_account_type" do
it "returns singapore" do
expect(create(:singaporean_bank_account).bank_account_type).to eq("SG")
end
end
describe "#country" do
it "returns SG" do
expect(create(:singaporean_bank_account).country).to eq("SG")
end
end
describe "#currency" do
it "returns sgd" do
expect(create(:singaporean_bank_account).currency).to eq("sgd")
end
end
describe "#routing_number" do
it "returns valid for 7 digits with hyphen after 4" do
ba = create(:singaporean_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("1100-000")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:singaporean_bank_account, account_number_last_four: "3456").account_number_visual).to eq("******3456")
end
end
describe "#validate_bank_code" do
it "allows 4 digits only" do
expect(build(:singaporean_bank_account, bank_code: "1100")).to be_valid
expect(build(:singaporean_bank_account, bank_code: "1234")).to be_valid
expect(build(:singaporean_bank_account, bank_code: "110")).not_to be_valid
expect(build(:singaporean_bank_account, bank_code: "ABCD")).not_to be_valid
end
end
describe "#validate_branch_code" do
it "allows 3 digits only" do
expect(build(:singaporean_bank_account, branch_code: "110")).to be_valid
expect(build(:singaporean_bank_account, branch_code: "123")).to be_valid
expect(build(:singaporean_bank_account, branch_code: "1100")).not_to be_valid
expect(build(:singaporean_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(:singaporean_bank_account, account_number: "000123456")).to be_valid
expect(build(:singaporean_bank_account, account_number: "1234567890")).to be_valid
sg_bank_account = build(:singaporean_bank_account, account_number: "ABCDEFGHI")
expect(sg_bank_account).to_not be_valid
expect(sg_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
sg_bank_account = build(:singaporean_bank_account, account_number: "8937040044053201300000")
expect(sg_bank_account).to_not be_valid
expect(sg_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
sg_bank_account = build(:singaporean_bank_account, account_number: "CHABCDE")
expect(sg_bank_account).to_not be_valid
expect(sg_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/saudi_arabia_bank_account_spec.rb | spec/models/saudi_arabia_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SaudiArabiaBankAccount do
describe "#bank_account_type" do
it "returns SA" do
expect(create(:saudi_arabia_bank_account).bank_account_type).to eq("SA")
end
end
describe "#country" do
it "returns SA" do
expect(create(:saudi_arabia_bank_account).country).to eq("SA")
end
end
describe "#currency" do
it "returns sar" do
expect(create(:saudi_arabia_bank_account).currency).to eq("sar")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:saudi_arabia_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("RIBLSARIXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:saudi_arabia_bank_account, account_number_last_four: "7519").account_number_visual).to eq("******7519")
end
end
describe "#validate_bank_code" do
it "allows 8 to 11 characters only" do
expect(build(:saudi_arabia_bank_account, bank_code: "RIBLSARIXXX")).to be_valid
expect(build(:saudi_arabia_bank_account, bank_code: "RIBLSARI")).to be_valid
expect(build(:saudi_arabia_bank_account, bank_code: "RIBLSAR")).not_to be_valid
expect(build(:saudi_arabia_bank_account, bank_code: "RIBLSARIXXXX")).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/installment_plan_snapshot_spec.rb | spec/models/installment_plan_snapshot_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe InstallmentPlanSnapshot do
let(:subscription) { create(:subscription) }
let(:payment_option) { create(:payment_option, subscription: subscription) }
describe "associations" do
it "belongs to payment_option" do
snapshot = build(:installment_plan_snapshot, payment_option: payment_option)
expect(snapshot.payment_option).to eq(payment_option)
end
end
describe "validations" do
context "number_of_installments" do
it "requires presence" do
snapshot = build(:installment_plan_snapshot, payment_option: payment_option, number_of_installments: nil)
expect(snapshot).not_to be_valid
expect(snapshot.errors[:number_of_installments]).to include("can't be blank")
end
it "must be greater than 0" do
snapshot = build(:installment_plan_snapshot, payment_option: payment_option, number_of_installments: 0)
expect(snapshot).not_to be_valid
expect(snapshot.errors[:number_of_installments]).to include("must be greater than 0")
end
it "must be an integer" do
snapshot = build(:installment_plan_snapshot, payment_option: payment_option, number_of_installments: 3.5)
expect(snapshot).not_to be_valid
expect(snapshot.errors[:number_of_installments]).to include("must be an integer")
end
end
context "recurrence" do
it "requires presence" do
snapshot = build(:installment_plan_snapshot, payment_option: payment_option, recurrence: nil)
expect(snapshot).not_to be_valid
expect(snapshot.errors[:recurrence]).to include("can't be blank")
end
end
context "total_price_cents" do
it "requires presence" do
snapshot = build(:installment_plan_snapshot, payment_option: payment_option, total_price_cents: nil)
expect(snapshot).not_to be_valid
expect(snapshot.errors[:total_price_cents]).to include("can't be blank")
end
it "must be greater than 0" do
snapshot = build(:installment_plan_snapshot, payment_option: payment_option, total_price_cents: 0)
expect(snapshot).not_to be_valid
expect(snapshot.errors[:total_price_cents]).to include("must be greater than 0")
end
it "must be an integer" do
snapshot = build(:installment_plan_snapshot, payment_option: payment_option, total_price_cents: 100.5)
expect(snapshot).not_to be_valid
expect(snapshot.errors[:total_price_cents]).to include("must be an integer")
end
end
context "payment_option uniqueness" do
it "allows only one snapshot per payment_option" do
create(:installment_plan_snapshot, payment_option: payment_option)
duplicate = build(:installment_plan_snapshot, payment_option: payment_option)
expect(duplicate).not_to be_valid
expect(duplicate.errors[:payment_option]).to include("has already been taken")
end
end
context "valid snapshot" do
it "is valid with all required attributes" do
snapshot = build(:installment_plan_snapshot, payment_option: payment_option)
expect(snapshot).to be_valid
end
end
end
describe "#calculate_installment_payment_price_cents" do
context "when total divides evenly" do
it "returns equal payments" do
snapshot = create(:installment_plan_snapshot,
payment_option: payment_option,
number_of_installments: 3,
total_price_cents: 15000)
payments = snapshot.calculate_installment_payment_price_cents
expect(payments).to eq([5000, 5000, 5000])
expect(payments.sum).to eq(15000)
end
end
context "when total has remainder" do
it "adds remainder to first payment" do
snapshot = create(:installment_plan_snapshot,
payment_option: payment_option,
number_of_installments: 3,
total_price_cents: 10000)
payments = snapshot.calculate_installment_payment_price_cents
expect(payments).to eq([3334, 3333, 3333])
expect(payments.sum).to eq(10000)
end
it "handles larger remainders correctly" do
snapshot = create(:installment_plan_snapshot,
payment_option: payment_option,
number_of_installments: 3,
total_price_cents: 14700)
payments = snapshot.calculate_installment_payment_price_cents
expect(payments).to eq([4900, 4900, 4900])
expect(payments.sum).to eq(14700)
end
end
context "single installment" do
it "returns full amount" do
snapshot = create(:installment_plan_snapshot,
payment_option: payment_option,
number_of_installments: 1,
total_price_cents: 10000)
payments = snapshot.calculate_installment_payment_price_cents
expect(payments).to eq([10000])
end
end
context "many installments" do
it "handles 12 installments correctly" do
snapshot = create(:installment_plan_snapshot,
payment_option: payment_option,
number_of_installments: 12,
total_price_cents: 12000)
payments = snapshot.calculate_installment_payment_price_cents
expect(payments).to eq([1000] * 12)
expect(payments.sum).to eq(12000)
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/consumption_event_spec.rb | spec/models/consumption_event_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ConsumptionEvent do
describe ".create_event!" do
let(:url_redirect) { create(:url_redirect) }
let(:purchase) { url_redirect.purchase }
let(:product) { purchase.link }
let(:product_file) { create(:product_file) }
let(:product_folder) { create(:product_folder) }
let(:required_params) do
{
event_type: ConsumptionEvent::EVENT_TYPE_DOWNLOAD,
platform: Platform::WEB,
url_redirect_id: url_redirect.id,
ip_address: "0.0.0.0"
}
end
it "creates an event with required parameters" do
expect { described_class.create_event!(**required_params) }.to change(ConsumptionEvent, :count).by(1)
event = ConsumptionEvent.last
expect(event.event_type).to eq(ConsumptionEvent::EVENT_TYPE_DOWNLOAD)
expect(event.platform).to eq(Platform::WEB)
expect(event.url_redirect_id).to eq(url_redirect.id)
expect(event.ip_address).to eq("0.0.0.0")
end
it "raises an error if a required parameter is missing" do
required_params.each_key do |key|
expect { described_class.create_event!(**required_params.except(key)) }.to raise_error(KeyError)
end
end
it "assigns default values to optional parameters if they are not provided" do
event = described_class.create_event!(**required_params)
expect(event.product_file_id).to be_nil
expect(event.purchase_id).to be_nil
expect(event.link_id).to be_nil
expect(event.folder_id).to be_nil
expect(event.consumed_at).to be_within(1.minute).of(Time.current)
end
it "uses provided values for optional parameters when available" do
other_params = {
product_file_id: product_file.id,
purchase_id: purchase.id,
product_id: product.id,
folder_id: product_folder.id,
consumed_at: 2.days.ago
}
event = described_class.create_event!(**required_params.merge(other_params))
expect(event.product_file_id).to eq(product_file.id)
expect(event.purchase_id).to eq(purchase.id)
expect(event.link_id).to eq(product.id)
expect(event.folder_id).to eq(product_folder.id)
expect(event.consumed_at).to be_within(1.minute).of(2.days.ago)
end
end
describe "#create" do
before do
@purchased_link = create(:product)
@product_file = create(:product_file, link: @purchased_link)
@purchase = create(:purchase, link: @purchased_link, purchase_state: :successful)
@url_redirect = create(:url_redirect, purchase: @purchase)
end
it "raises error if event_type is invalid" do
consumption_event = ConsumptionEvent.new(product_file_id: @product_file.id,
url_redirect_id: @url_redirect.id, purchase_id: @purchase.id,
platform: "web", consumed_at: "2015-09-09T17:26:50PDT")
consumption_event.event_type = "invalid_event"
consumption_event.validate
expect(consumption_event.errors.full_messages).to include("Event type is not included in the list")
end
it "raises error if platform is invalid" do
consumption_event = ConsumptionEvent.new(product_file_id: @product_file.id,
url_redirect_id: @url_redirect.id, purchase_id: @purchase.id,
platform: "invalid_platform", consumed_at: "2015-09-09T17:26:50PDT")
consumption_event.event_type = "read"
consumption_event.validate
expect(consumption_event.errors.full_messages).to include("Platform is not included in the list")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/wishlist_spec.rb | spec/models/wishlist_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Wishlist do
describe "#find_by_url_slug" do
let(:wishlist) { create(:wishlist) }
it "finds a wishlist" do
expect(Wishlist.find_by_url_slug(wishlist.url_slug)).to eq(wishlist)
end
it "returns nil when the wishlist does not exist" do
expect(Wishlist.find_by_url_slug("foo")).to be_nil
end
end
describe "#url_slug" do
let(:wishlist) { create(:wishlist, name: "My Wishlist") }
it "returns a readable URL path plus the ID" do
expect(wishlist.url_slug).to eq("my-wishlist-#{wishlist.external_id_numeric}")
end
end
describe "#followed_by?" do
let(:wishlist) { create(:wishlist) }
let(:user) { create(:user) }
context "when the user is following the wishlist" do
before do
create(:wishlist_follower, wishlist: wishlist, follower_user: user)
end
it "returns true" do
expect(wishlist.followed_by?(user)).to eq(true)
end
end
context "when the user has unfollowed the wishlist" do
before do
create(:wishlist_follower, wishlist: wishlist, follower_user: user, deleted_at: Time.current)
end
it "returns false" do
expect(wishlist.followed_by?(user)).to eq(false)
end
end
context "when the user is not following the wishlist" do
it "returns false" do
expect(wishlist.followed_by?(user)).to eq(false)
end
end
end
describe "#wishlist_products_for_email" do
let(:wishlist) { create(:wishlist) }
let(:old_product) { create(:wishlist_product, wishlist: wishlist, created_at: 1.day.ago) }
let(:new_product) { create(:wishlist_product, wishlist: wishlist, created_at: 1.hour.ago) }
let(:deleted_product) { create(:wishlist_product, wishlist: wishlist, deleted_at: Time.current) }
context "when no email has been sent yet" do
it "returns alive products" do
expect(wishlist.wishlist_products_for_email).to match_array([old_product, new_product])
end
end
context "when an email has been sent" do
before { wishlist.update!(followers_last_contacted_at: 12.hours.ago) }
it "returns alive products added after the last email" do
expect(wishlist.wishlist_products_for_email).to eq([new_product])
end
end
end
describe "#update_recommendable" do
let(:wishlist) { create(:wishlist, name: "My Wishlist") }
before do
create(:wishlist_product, wishlist:)
end
context "when there are alive wishlist products" do
it "sets recommendable to true" do
wishlist.update_recommendable
expect(wishlist.recommendable).to be true
end
end
context "when there are no alive wishlist products" do
before { wishlist.wishlist_products.each(&:mark_deleted!) }
it "sets recommendable to false" do
wishlist.update_recommendable
expect(wishlist.recommendable).to be false
end
end
context "when name is adult" do
before do
allow(AdultKeywordDetector).to receive(:adult?).with(wishlist.name).and_return(true)
allow(AdultKeywordDetector).to receive(:adult?).with(wishlist.description).and_return(false)
end
it "sets recommendable to false" do
wishlist.update_recommendable
expect(wishlist.recommendable).to be false
end
end
context "when description is adult" do
before do
allow(AdultKeywordDetector).to receive(:adult?).with(wishlist.name).and_return(false)
allow(AdultKeywordDetector).to receive(:adult?).with(wishlist.description).and_return(true)
end
it "sets recommendable to false" do
wishlist.update_recommendable
expect(wishlist.recommendable).to be false
end
end
context "when discover is opted out" do
before { wishlist.discover_opted_out = true }
it "sets recommendable to false" do
wishlist.update_recommendable
expect(wishlist.recommendable).to be false
end
end
context "when name is a default auto-generated one" do
before { wishlist.name = "Wishlist 1" }
it "sets recommendable to false" do
wishlist.update_recommendable
expect(wishlist.recommendable).to be false
end
end
context "when save is true" do
before { wishlist.discover_opted_out = true }
it "saves the record" do
wishlist.update_recommendable(save: true)
expect(wishlist.reload.recommendable).to be false
end
end
context "when save is false" do
before { wishlist.discover_opted_out = true }
it "does not save the record" do
wishlist.update_recommendable(save: false)
expect(wishlist.recommendable).to be false
expect(wishlist.reload.recommendable).to be true
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/charge_purchase_spec.rb | spec/models/charge_purchase_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ChargePurchase do
describe "validations" do
it "validates presence of required attributes" do
charge_purchase = described_class.new
expect(charge_purchase).to be_invalid
expect(charge_purchase.errors.messages).to eq(charge: ["must exist"], purchase: ["must exist"])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/wishlist_follower_spec.rb | spec/models/wishlist_follower_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe WishlistFollower do
describe "validations" do
it "validates uniqueness of follower" do
wishlist = create(:wishlist)
user = create(:buyer_user)
first_follower = create(:wishlist_follower, wishlist:, follower_user: user)
second_follower = build(:wishlist_follower, wishlist:, follower_user: user)
expect(second_follower).not_to be_valid
expect(second_follower.errors.full_messages.sole).to eq("Follower user is already following this wishlist.")
second_follower.wishlist = create(:wishlist)
expect(second_follower).to be_valid
second_follower.wishlist = wishlist
first_follower.mark_deleted!
expect(second_follower).to be_valid
end
it "prevents a user from following their own wishlist" do
wishlist = create(:wishlist)
wishlist_follower = build(:wishlist_follower, wishlist:, follower_user: wishlist.user)
expect(wishlist_follower).not_to be_valid
expect(wishlist_follower.errors.full_messages.sole).to eq("You cannot follow your own wishlist.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/morocco_bank_account_spec.rb | spec/models/morocco_bank_account_spec.rb | # frozen_string_literal: true
describe MoroccoBankAccount do
describe "#bank_account_type" do
it "returns Morocco" do
expect(create(:morocco_bank_account).bank_account_type).to eq("MA")
end
end
describe "#country" do
it "returns MA" do
expect(create(:morocco_bank_account).country).to eq("MA")
end
end
describe "#currency" do
it "returns mad" do
expect(create(:morocco_bank_account).currency).to eq("mad")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:morocco_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAAMAMAXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:morocco_bank_account, account_number_last_four: "9123").account_number_visual).to eq("MA******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(:morocco_bank_account)).to be_valid
expect(build(:morocco_bank_account, account_number: "MA64011519000001205000534921")).to be_valid
expect(build(:morocco_bank_account, account_number: "MA62370400440532013001")).to be_valid
ma_bank_account = build(:morocco_bank_account, account_number: "MA12345")
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(:morocco_bank_account, account_number: "DE61109010140000071219812874")
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(:morocco_bank_account, account_number: "8937040044053201300000")
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(:morocco_bank_account, account_number: "CRABCDE")
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/shipment_spec.rb | spec/models/shipment_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Shipment do
describe "#shipped?" do
it "returns false is shipped_at is nil" do
expect(create(:shipment).shipped?).to be(false)
end
it "returns true is shipped_at is present" do
expect(create(:shipment, shipped_at: 1.day.ago).shipped?).to be(true)
end
end
describe "#mark_as_shipped" do
it "marks a shipment as shipped" do
shipment = create(:shipment)
shipment.mark_shipped
expect(shipment.shipped?).to be(true)
end
end
describe "notify_sender_of_sale" do
before do
user = create(:user)
link = create(:physical_product, user:)
purchase = create(:physical_purchase, link:)
@shipment = create(:shipment, purchase:)
end
it "sends sender email of receiver sale" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(CustomerLowPriorityMailer).to receive(:order_shipped).and_return(mail_double)
@shipment.mark_shipped
end
end
describe "#calculated_tracking_url" do
before do
user = create(:user)
link = create(:physical_product, user:)
purchase = create(:physical_purchase, link:)
@shipment = create(:shipment, purchase:, tracking_number: "1234567890", carrier: "USPS")
end
it "returns the tracking_url if present" do
@shipment.update(tracking_url: "https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=1234567890")
expect(@shipment.calculated_tracking_url).to eq("https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=1234567890")
end
it "returns the right url based on carrier and tracking_number when tracking_url is not present" do
@shipment.update(carrier: "USPS", tracking_number: "1234567890")
expect(@shipment.calculated_tracking_url).to eq("https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=1234567890")
@shipment.update(carrier: "UPS")
expect(@shipment.calculated_tracking_url).to eq("http://wwwapps.ups.com/WebTracking/processInputRequest?TypeOfInquiryNumber=T&InquiryNumber1=1234567890")
@shipment.update(carrier: "FedEx")
expect(@shipment.calculated_tracking_url).to eq("http://www.fedex.com/Tracking?language=english&cntry_code=us&tracknumbers=1234567890")
@shipment.update(carrier: "DHL")
expect(@shipment.calculated_tracking_url).to eq("http://www.dhl.com/content/g0/en/express/tracking.shtml?brand=DHL&AWB=1234567890")
@shipment.update(carrier: "OnTrac")
expect(@shipment.calculated_tracking_url).to eq("http://www.ontrac.com/trackres.asp?tracking_number=1234567890")
@shipment.update(carrier: "Canada Post")
expect(@shipment.calculated_tracking_url).to eq("https://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?LOCALE=en&trackingNumber=1234567890")
end
it "does not return anything if no tracking_url and no carrier" do
@shipment.update(carrier: nil)
expect(@shipment.calculated_tracking_url).to eq(nil)
end
it "does not return anything if no tracking_url and no tracking number" do
@shipment.update(tracking_number: nil)
expect(@shipment.calculated_tracking_url).to eq(nil)
end
it "does not return anything if no tracking_url and unrecognized carrier" do
@shipment.update(carrier: "AnishOnTime")
expect(@shipment.calculated_tracking_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/cached_sales_related_products_info_spec.rb | spec/models/cached_sales_related_products_info_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CachedSalesRelatedProductsInfo do
describe "validations" do
it "validates counts column format" do
record = build(:cached_sales_related_products_info, counts: { "123" => "bar" })
expect(record).to be_invalid
expect(record.errors[:counts]).to be_present
record = build(:cached_sales_related_products_info, counts: { "foo" => 1 })
expect(record).to be_invalid
expect(record.errors[:counts]).to be_present
record = build(:cached_sales_related_products_info, counts: { "123" => 456 })
expect(record).to be_valid
end
end
describe "#normalized_counts" do
it "converts keys into integers" do
# A json column forces keys to be strings, but we want them to be integers because they're product ids
record = create(:cached_sales_related_products_info, counts: { 123 => 456 })
record.reload
expect(record.counts).to eq({ "123" => 456 })
expect(record.normalized_counts).to eq({ 123 => 456 })
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/collaborator_invitation_spec.rb | spec/models/collaborator_invitation_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe CollaboratorInvitation, type: :model do
describe "#accept!" do
it "destroys the invitation" do
invitation = create(:collaborator_invitation)
expect { invitation.accept! }.to change(CollaboratorInvitation, :count).by(-1)
expect { invitation.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
it "sends a notification email" do
invitation = create(:collaborator_invitation)
expect { invitation.accept! }
.to have_enqueued_mail(AffiliateMailer, :collaborator_invitation_accepted).with { invitation.id }
end
end
describe "#decline!" do
let(:collaborator) { create(:collaborator) }
let(:invitation) { create(:collaborator_invitation, collaborator:) }
it "marks the collaborator as deleted" do
expect { invitation.decline! }.to change { collaborator.reload.deleted? }.from(false).to(true)
end
it "disables the is_collab flag on associated products" do
products = create_list(:product, 2, is_collab: true)
create(:product_affiliate, product: products.first, affiliate: collaborator)
create(:product_affiliate, product: products.second, affiliate: collaborator)
expect { invitation.decline! }
.to change { products.first.reload.is_collab }.from(true).to(false)
.and change { products.second.reload.is_collab }.from(true).to(false)
end
it "sends an email to the collaborator" do
expect { invitation.decline! }
.to have_enqueued_mail(AffiliateMailer, :collaborator_invitation_declined).with { invitation.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/guyana_bank_account_spec.rb | spec/models/guyana_bank_account_spec.rb | # frozen_string_literal: true
describe GuyanaBankAccount do
describe "#bank_account_type" do
it "returns GY" do
expect(create(:guyana_bank_account).bank_account_type).to eq("GY")
end
end
describe "#country" do
it "returns GY" do
expect(create(:guyana_bank_account).country).to eq("GY")
end
end
describe "#currency" do
it "returns gyd" do
expect(create(:guyana_bank_account).currency).to eq("gyd")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:guyana_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAAGYGGXYZ")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:guyana_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
expect(build(:guyana_bank_account)).to be_valid
expect(build(:guyana_bank_account, account_number: "00012345678910111213141516171819")).to be_valid
expect(build(:guyana_bank_account, account_number: "1")).to be_valid
expect(build(:guyana_bank_account, account_number: "GUY12345678910111213141516171819")).to be_valid
gy_bank_account = build(:guyana_bank_account, account_number: "0001234567891011121314151617181920")
expect(gy_bank_account).to_not be_valid
expect(gy_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
gy_bank_account = build(:guyana_bank_account, account_number: "GUY1234567891011121314151617181920")
expect(gy_bank_account).to_not be_valid
expect(gy_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/seller_profile_posts_section_spec.rb | spec/models/seller_profile_posts_section_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SellerProfilePostsSection do
describe "validations" do
it "validates json_data with the correct schema" do
section = build(:seller_profile_posts_section, shown_posts: [1])
section.json_data["garbage"] = "should not be here"
schema = JSON.parse(File.read(Rails.root.join("lib", "json_schemas", "seller_profile_posts_section.json").to_s))
expect(JSON::Validator).to receive(:new).with(schema, insert_defaults: true, record_errors: true).and_wrap_original do |original, *args|
validator = original.call(*args)
expect(validator).to receive(:validate).with(section.json_data).and_call_original
validator
end
section.validate
expect(section.errors.full_messages.to_sentence).to eq("The property '#/' contains additional properties [\"garbage\"] outside of the schema when none are allowed")
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_folder_spec.rb | spec/models/product_folder_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ProductFolder do
it "validates presence of attributes" do
product_folder = build(:product_folder, name: "")
expect(product_folder.valid?).to eq(false)
expect(product_folder.errors.messages).to eq(
name: ["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/sweden_bank_account_spec.rb | spec/models/sweden_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SwedenBankAccount do
describe "#bank_account_type" do
it "returns sweden" do
expect(create(:sweden_bank_account).bank_account_type).to eq("SE")
end
end
describe "#country" do
it "returns SE" do
expect(create(:sweden_bank_account).country).to eq("SE")
end
end
describe "#currency" do
it "returns sek" do
expect(create(:sweden_bank_account).currency).to eq("sek")
end
end
describe "#routing_number" do
it "returns nil" do
expect(create(:sweden_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(:sweden_bank_account, account_number_last_four: "0003").account_number_visual).to eq("SE******0003")
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(:sweden_bank_account)).to be_valid
expect(build(:sweden_bank_account, account_number: "SE35 5000 0000 0549 1000 0003")).to be_valid
se_bank_account = build(:sweden_bank_account, account_number: "SE12345")
expect(se_bank_account).to_not be_valid
expect(se_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
se_bank_account = build(:sweden_bank_account, account_number: "DE61109010140000071219812874")
expect(se_bank_account).to_not be_valid
expect(se_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
se_bank_account = build(:sweden_bank_account, account_number: "8937040044053201300000")
expect(se_bank_account).to_not be_valid
expect(se_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
se_bank_account = build(:sweden_bank_account, account_number: "SEABCDE")
expect(se_bank_account).to_not be_valid
expect(se_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_spec.rb | spec/models/variant_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/max_purchase_count_concern"
describe Variant do
it_behaves_like "MaxPurchaseCount concern", :variant
describe "lifecycle hooks" do
describe "before_validation :strip_subscription_price_change_message" do
it "ensures text is present or sets message to nil" do
["", "<p><br></p>", "<div></div>"].each do |message|
variant = build(:variant, subscription_price_change_message: message)
expect do
variant.valid?
end.to change { variant.subscription_price_change_message }.to(nil)
end
["<p>hello</p>", "<a href='foo'>a link</a>"].each do |message|
variant = build(:variant, subscription_price_change_message: message)
expect do
variant.valid?
end.not_to change { variant.subscription_price_change_message }
end
end
end
describe "before_create :set_position" do
it "sets the position if not already set" do
preexisting_variant = create(:variant)
variant = build(:variant, variant_category: preexisting_variant.variant_category)
variant.save!
expect(variant.reload.position_in_category).to eq 1
end
it "does not set the position if already set" do
preexisting_variant = create(:variant)
variant = build(
:variant,
variant_category: preexisting_variant.variant_category,
position_in_category: 0
)
variant.save!
expect(variant.reload.position_in_category).to eq 0
end
end
describe "after_save :set_customizable_price" do
context "for a tier variant" do
let(:product) { create(:membership_product) }
let(:tier) { product.tiers.first }
let(:monthly_price) { tier.prices.alive.find_by!(recurrence: BasePrice::Recurrence::MONTHLY) }
context "when the variant has at least one price with price_cents > 0" do
it "does not set customizable_price to true" do
expect(monthly_price.price_cents).not_to eq 0
create(:variant_price, variant: tier, price_cents: 0, recurrence: BasePrice::Recurrence::YEARLY)
tier.save
expect(tier.reload.customizable_price).to be nil
end
end
context "when the variant has no prices" do
it "does not set customizable_price" do
tier.save
expect(tier.reload.customizable_price).to be nil
end
end
context "when the variant has no prices with price_cents > 0" do
it "sets customizable_price to true" do
monthly_price.update!(price_cents: 0)
create(:variant_price, variant: tier, price_cents: 0, recurrence: BasePrice::Recurrence::YEARLY, deleted_at: Time.current)
tier.save
expect(tier.reload.customizable_price).to eq true
end
end
end
context "for a non-tier variant" do
it "does not set customizable_price" do
variant = create(:variant)
create(:variant_price, variant:, price_cents: 0)
variant.save
expect(variant.customizable_price).to be nil
end
end
end
end
describe "validations" do
describe "price_must_be_within_range" do
let(:variant) { create(:variant) }
context "for a variant with live prices" do
it "succeeds if prices are within acceptable bounds" do
create(:variant_price, variant:, price_cents: 1_00)
create(:variant_price, variant:, price_cents: 5000_00)
expect(variant).to be_valid
end
it "fails if a price is too high" do
create(:variant_price, variant:, price_cents: 5000_01)
expect(variant).not_to be_valid
expect(variant.errors.full_messages).to include "Sorry, we don't support pricing products above $5,000."
end
it "fails if a price is too low" do
create(:variant_price, variant:, price_cents: 98)
expect(variant).not_to be_valid
expect(variant.errors.full_messages).to include "Sorry, a product must be at least $0.99."
end
end
context "for a variant without live prices" do
it "succeeds" do
create(:variant_price, variant:, price_cents: 98, deleted_at: Time.current)
expect(variant).to be_valid
end
end
end
describe "apply_price_changes_to_existing_memberships_settings" do
it "succeeds if setting is disabled" do
variant = build(:variant, apply_price_changes_to_existing_memberships: false)
expect(variant).to be_valid
end
context "setting is enabled" do
let(:variant) { build(:variant, apply_price_changes_to_existing_memberships: true) }
it "succeeds if effective date is present" do
variant.subscription_price_change_effective_date = 7.days.from_now.to_date
expect(variant).to be_valid
end
it "fails if effective date is missing" do
expect(variant).not_to be_valid
expect(variant.errors.full_messages).to include "Effective date for existing membership price changes must be present"
end
it "fails if effective date is < 7 days from now" do
variant.subscription_price_change_effective_date = 6.days.from_now.in_time_zone(variant.user.timezone).to_date
expect(variant).not_to be_valid
expect(variant.errors.full_messages).to include "The effective date must be at least 7 days from today"
end
it "succeeds if effective date is < 7 days from now but is not being changed" do
variant.subscription_price_change_effective_date = 6.days.from_now.in_time_zone(variant.user.timezone).to_date
variant.save(validate: false)
expect(variant).to be_valid
end
end
end
describe "variant belongs to call" do
let(:call) { create(:call_product) }
let(:variant_category) { call.variant_categories.first }
context "duration_in_minutes is not a number" do
it "adds an error" do
variant = build(:variant, variant_category:, duration_in_minutes: nil)
expect(variant).not_to be_valid
expect(variant.errors.full_messages).to eq(["Duration in minutes is not a number"])
variant.duration_in_minutes = "not a number"
expect(variant).not_to be_valid
expect(variant.errors.full_messages).to eq(["Duration in minutes is not a number"])
end
end
context "duration_in_minutes is less than or equal to 0" do
it "adds an error" do
variant = build(:variant, variant_category:, duration_in_minutes: 0)
expect(variant).not_to be_valid
expect(variant.errors.full_messages).to eq(["Duration in minutes must be greater than 0"])
variant.duration_in_minutes = -1
expect(variant).not_to be_valid
expect(variant.errors.full_messages).to eq(["Duration in minutes must be greater than 0"])
end
end
context "duration_in_minutes is greater than 0" do
it "does not add an error" do
variant = build(:variant, variant_category:, duration_in_minutes: 100)
expect(variant).to be_valid
end
end
end
describe "variant belongs to coffee" do
let(:seller) { create(:user, :eligible_for_service_products) }
let(:coffee) { create(:product, user: seller, native_type: Link::NATIVE_TYPE_COFFEE) }
let(:variant_category) { create(:variant_category, link: coffee) }
context "name is blank" do
it "does not add an error" do
variant = build(:variant, variant_category:, price_difference_cents: 100)
expect(variant).to be_valid
end
end
end
end
describe "#is_downloadable?" do
let(:variant) { create(:variant) }
it "returns false if product is rent-only" do
variant.link.update!(purchase_type: "rent_only", rental_price_cents: 1_00)
expect(variant.is_downloadable?).to eq(false)
end
it "returns false if product has stampable PDFs" do
variant.product_files << create(:readable_document, link: variant.link)
variant.product_files << create(:readable_document, pdf_stamp_enabled: true, link: variant.link)
expect(variant.is_downloadable?).to eq(false)
end
it "returns false if product has only stream-only files" do
variant.product_files << create(:streamable_video, stream_only: true, link: variant.link)
expect(variant.is_downloadable?).to eq(false)
end
it "returns true if product has at least one unstampable file that's not stream-only" do
variant.product_files << create(:readable_document, link: variant.link)
variant.product_files << create(:streamable_video, stream_only: true, link: variant.link)
expect(variant.is_downloadable?).to eq(true)
end
end
describe "sales_count_for_inventory" do
context "when the product is not a membership" do
before :each do
@variant = create(:variant)
product = @variant.link
create(:purchase, link: product, variant_attributes: [@variant])
create(:purchase, link: product, variant_attributes: [@variant], purchase_state: "failed")
end
it "count all successful purchases" do
expect(@variant.sales_count_for_inventory).to eq 1
end
it "excludes purchases for other products" do
create(:purchase)
create(:membership_purchase)
expect(@variant.sales_count_for_inventory).to eq 1
end
end
context "when the product is a membership" do
before :each do
@product = create(:membership_product)
tier_category = @product.tier_category
@first_tier = tier_category.variants.first
@second_tier = create(:variant, variant_category: tier_category, name: "2nd Tier")
# first tier has 1 active subscription, 1 inactive subscription, and 1 non-subscription purchase
active_subscription = create(:subscription, link: @product)
create(:purchase, link: @product, variant_attributes: [@first_tier], subscription: active_subscription, is_original_subscription_purchase: true)
inactive_subscription = create(:subscription, link: @product, deactivated_at: Time.current)
create(:purchase, link: @product, variant_attributes: [@first_tier], subscription: inactive_subscription, is_original_subscription_purchase: true)
create(:purchase, link: @product, variant_attributes: [@first_tier])
# second tier has 1 active subscription, 1 inactive subscription, and 1 non-subscription purchase
active_subscription = create(:subscription, link: @product)
create(:purchase, link: @product, variant_attributes: [@second_tier], subscription: active_subscription, is_original_subscription_purchase: true)
inactive_subscription = create(:subscription, link: @product, deactivated_at: Time.current)
create(:purchase, link: @product, variant_attributes: [@second_tier], subscription: inactive_subscription, is_original_subscription_purchase: true)
create(:purchase, link: @product, variant_attributes: [@second_tier])
end
it "only counts active subscriptions + non-subscription purchases for the given tier" do
expect(@first_tier.sales_count_for_inventory).to eq 2
end
it "excludes purchases for other products" do
create(:purchase)
create(:membership_purchase)
expect(@first_tier.sales_count_for_inventory).to eq 2
end
end
end
describe "quantity_left" do
describe "has max_purchase_count" do
before do
@variant = create(:variant, max_purchase_count: 3)
@purchase = create(:purchase)
@purchase.variant_attributes << @variant
@purchase.save
end
it "show correctly" do
expect(@variant.quantity_left).to eq 2
end
end
describe "no max_purchase_count" do
before do
@variant = create(:variant)
end
it "returns nil" do
expect(@variant.quantity_left).to eq nil
end
end
describe "max_purchase_count and validation" do
before do
@variant = create(:variant, max_purchase_count: 1)
@purchase = create(:purchase, variant_attributes: [@variant])
end
it "is valid" do
@variant.save
expect(@variant).to be_valid
end
it "remains valid if when inventory sold is greater" do
@variant = create(:variant, max_purchase_count: 3)
create_list(:purchase, 3, link: @variant.variant_category.link, variant_attributes: [@variant])
@variant.update_column(:max_purchase_count, 1)
expect(@variant.valid?).to eq(true)
@variant.max_purchase_count = 2
expect(@variant.valid?).to eq(false)
end
end
end
describe "price_formatted_without_dollar_sign" do
describe "whole dollar amount" do
before do
@variant = create(:variant, price_difference_cents: 300)
end
it "shows correctly" do
expect(@variant.price_formatted_without_dollar_sign).to eq "3"
end
end
describe "dollars and cents" do
before do
@variant = create(:variant, price_difference_cents: 350)
end
it "shows correctly" do
expect(@variant.price_formatted_without_dollar_sign).to eq "3.50"
end
end
end
describe "available?" do
describe "no max_purchase_count" do
before do
@variant = create(:variant)
end
it "returns true" do
expect(@variant.available?).to be(true)
end
end
describe "available" do
before do
@variant = create(:variant, max_purchase_count: 2)
end
it "returns true" do
expect(@variant.available?).to be(true)
end
end
describe "unavailable" do
before do
@variant = create(:variant, max_purchase_count: 1)
@purchase = create(:purchase, variant_attributes: [@variant])
end
it "returns false" do
expect(@variant.available?).to be(false)
end
end
end
describe "#mark_deleted" do
before do
@variant = create(:variant)
end
it "marks the variant deleted" do
travel_to(Time.current) do
expect { @variant.mark_deleted }.to change { @variant.reload.deleted_at.try(:utc).try(:to_i) }.from(nil).to(Time.current.to_i)
end
end
it "marks the variant deleted and enqueues deletion for rich content and product file archives" do
freeze_time do
expect do
@variant.mark_deleted
end.to change { @variant.reload.deleted_at }.from(nil).to(Time.current)
expect(DeleteProductRichContentWorker).to have_enqueued_sidekiq_job(@variant.variant_category.link_id, @variant.id)
expect(DeleteProductFilesArchivesWorker).to have_enqueued_sidekiq_job(@variant.variant_category.link_id, @variant.id)
end
end
end
describe "price_difference_cents_validation" do
it "marks negative variants as invalid" do
expect { create(:variant, price_difference_cents: -100) }.to raise_error(ActiveRecord::RecordInvalid)
end
end
describe "scopes" do
describe "alive" do
before do
@variant_category = create(:variant_category, link: create(:product))
@variant = create(:variant, variant_category: @variant_category)
create(:variant, variant_category: @variant_category, deleted_at: Time.current)
end
it "retuns the correct variants" do
expect(@variant_category.variants.alive.count).to eq 1
expect(@variant_category.variants.alive.first.id).to eq @variant.id
end
end
end
describe "#user" do
before do
@product = create(:product)
@variant_category = create(:variant_category, link: @product)
@variant = create(:variant, variant_category: @variant_category)
end
it "returns value matches the owning link user" do
expect(@variant.user).to eq(@product.user)
end
end
describe "#name_displayable" do
before do
@product = create(:product, name: "Crazy Link")
@variant_category = create(:variant_category, link: @product)
@variant = create(:variant, variant_category: @variant_category, name: "Version A")
end
it "consolidates the link and variant names" do
expect(@variant.name_displayable).to eq("Crazy Link (Version A)")
end
end
describe "#free?" do
it "returns true when price_difference_cents IS 0 and the variant HAS NO live prices with price_cents > 0" do
variant = create(:variant)
create(:variant_price, variant:, price_cents: 0)
create(:variant_price, variant:, price_cents: 100, deleted_at: Time.current)
expect(variant).to be_free
end
it "returns false when price_difference_cents IS 0 and the variant HAS live prices with price_cents > 0" do
variant = create(:variant)
create(:variant_price, variant:, price_cents: 100)
expect(variant).not_to be_free
end
it "returns false when price_difference_cents IS NOT 0 and the variant HAS NO live prices with price_cents > 0" do
variant = create(:variant, price_difference_cents: 100)
create(:variant_price, variant:, price_cents: 0)
create(:variant_price, variant:, price_cents: 100, deleted_at: Time.current)
expect(variant).not_to be_free
end
it "returns false when price_difference_cents IS 0 and the variant HAS live prices with price_cents > 0" do
variant = create(:variant)
create(:variant_price, variant:, price_cents: 100)
create(:variant_price, variant:, price_cents: 100, deleted_at: Time.current)
expect(variant).not_to be_free
end
it "returns true when price_difference_cents IS 0 and the variant only has live RENTAL prices with price_cents > 0" do
variant = create(:variant)
price = create(:variant_price, variant:, price_cents: 100)
price.is_rental = true
price.save!
expect(variant).to be_free
end
it "does not error if price_difference_cents is nil" do
variant = create(:variant, price_difference_cents: nil)
expect(variant).to be_free
end
end
describe "#as_json" do
context "for a variant with prices" do
context "and is pay-what-you-want enabled" do
it "includes prices and pay-what-you-want state" do
variant = create(:variant, customizable_price: true)
create(:price, link: variant.link, recurrence: "monthly")
create(:variant_price, variant:, suggested_price_cents: 5_00, price_cents: 3_00, recurrence: "monthly")
variant_hash = variant.as_json
prices_hash = variant_hash["recurrence_price_values"]
expect(variant_hash["is_customizable_price"]).to eq true
expect(prices_hash["monthly"][:enabled]).to eq true
expect(prices_hash["monthly"][:price]).to eq "3"
expect(prices_hash["monthly"][:suggested_price]).to eq "5"
end
end
context "and is NOT pay-what-you-want enabled" do
it "includes prices and pay-what-you-want state" do
variant = create(:variant, customizable_price: false)
create(:price, link: variant.link, recurrence: "monthly")
create(:variant_price, variant:, price_cents: 3_00, recurrence: "monthly")
variant_hash = variant.as_json
prices_hash = variant_hash["recurrence_price_values"]
expect(variant_hash["is_customizable_price"]).to eq false
expect(prices_hash["monthly"][:enabled]).to eq true
expect(prices_hash["monthly"][:price]).to eq "3"
expect(prices_hash["monthly"].has_key?(:suggested_price)).to be false
end
end
it "excludes rental prices" do
variant = create(:variant, customizable_price: true)
price = create(:variant_price, variant:, suggested_price_cents: 5_00, price_cents: 3_00, recurrence: "monthly")
price.is_rental = true
price.save!
variant_hash = variant.as_json
monthly_price_hash = variant_hash["recurrence_price_values"]["monthly"]
expect(monthly_price_hash[:enabled]).to eq false
expect(monthly_price_hash[:price]).to be_nil
end
end
context "for a variant without prices" do
it "does not include prices or pay-what-you-want state" do
variant = create(:variant)
variant_hash = variant.as_json
expect(variant_hash.has_key?("is_customizable_price")).to be false
expect(variant_hash.has_key?("recurrence_price_values")).to be false
end
end
context "for_seller" do
let(:variant) { create(:variant) }
it "includes protected information when for_seller is true" do
variant_hash = variant.as_json(for_views: true, for_seller: true)
expect(variant_hash.has_key?("active_subscriber_count")).to eq true
expect(variant_hash.has_key?("settings")).to eq true
end
it "does not include protected information when for_seller is false or missing" do
variant_hash = variant.as_json(for_views: true, for_seller: false)
expect(variant_hash.has_key?("active_subscriber_count")).to eq false
expect(variant_hash.has_key?("settings")).to eq false
variant_hash = variant.as_json(for_views: true)
expect(variant_hash.has_key?("active_subscriber_count")).to eq false
expect(variant_hash.has_key?("settings")).to eq false
end
end
end
describe "#to_option" do
it "returns a hash of attributes for use in checkout" do
variant = create(:variant, name: "Red", description: "The red one")
expect(variant.to_option).to eq(
id: variant.external_id,
name: variant.name,
quantity_left: nil,
description: variant.description,
price_difference_cents: 0,
recurrence_price_values: nil,
is_pwyw: false,
duration_in_minutes: nil,
)
end
end
describe "#recurrence_price_values" do
context "with subscription recurrence" do
before do
@variant = create(:variant)
@variant_price = create(:variant_price, variant: @variant, recurrence: "yearly")
product_price = create(:price, link: @variant.link, recurrence: "yearly")
payment_option = create(:payment_option, price: product_price)
@subscription = payment_option.subscription
create(:membership_purchase, subscription: @subscription, variant_attributes: [@variant], price_cents: 1234)
end
context "with deleted prices" do
before :each do
@variant_price.mark_deleted!
end
it "includes the deleted price details for the subscription's recurrence" do
result = @variant.recurrence_price_values
expect(result["yearly"]).not_to be
result = @variant.recurrence_price_values(subscription_attrs: {
recurrence: @subscription.recurrence,
variants: @subscription.original_purchase.variant_attributes,
price_cents: @subscription.original_purchase.displayed_price_cents,
})
expect(result["yearly"]).to be
end
it "does not include deleted price details for other recurrences" do
create(:price, link: @variant.link, recurrence: "monthly", deleted_at: 1.day.ago)
create(:variant_price, variant: @variant, recurrence: "monthly")
result = @variant.recurrence_price_values(subscription_attrs: {
recurrence: @subscription.recurrence,
variants: @subscription.original_purchase.variant_attributes,
price_cents: @subscription.original_purchase.displayed_price_cents,
})
expect(result["monthly"]).not_to be
end
it "uses the subscription's existing price" do
result = @variant.recurrence_price_values(subscription_attrs: {
recurrence: @subscription.recurrence,
variants: @subscription.original_purchase.variant_attributes,
price_cents: @subscription.original_purchase.displayed_price_cents,
})
expect(result["yearly"][:price_cents]).to eq 1234
end
end
context "when the subscription tier has been deleted" do
it "only includes the price for the current subscription recurrence" do
create(:price, link: @variant.link, recurrence: "monthly")
create(:variant_price, variant: @variant, recurrence: "monthly")
result = @variant.recurrence_price_values(subscription_attrs: {
recurrence: @subscription.recurrence,
variants: @subscription.original_purchase.variant_attributes,
price_cents: @subscription.original_purchase.displayed_price_cents,
})
expect(result.keys).to match_array ["monthly", "yearly"]
@variant.mark_deleted!
result = @variant.recurrence_price_values(subscription_attrs: {
recurrence: @subscription.recurrence,
variants: @subscription.original_purchase.variant_attributes,
price_cents: @subscription.original_purchase.displayed_price_cents,
})
expect(result.keys).to match_array ["yearly"]
end
end
end
end
describe "#save_recurring_prices!" do
before :each do
@variant = create(:variant)
@recurrence_price_values = {
BasePrice::Recurrence::MONTHLY => {
enabled: true,
price: "20",
suggested_price: "25",
suggested_price_cents: 2500,
},
BasePrice::Recurrence::YEARLY => {
enabled: true,
price_cents: 9999,
suggested_price: ""
},
BasePrice::Recurrence::BIANNUALLY => { enabled: false }
}
end
it "saves valid prices" do
@variant.save_recurring_prices!(@recurrence_price_values)
prices = @variant.prices
monthly_price = prices.find_by!(recurrence: BasePrice::Recurrence::MONTHLY)
yearly_price = prices.find_by!(recurrence: BasePrice::Recurrence::YEARLY)
expect(prices.length).to eq 2
expect(monthly_price.price_cents).to eq 2000
expect(monthly_price.suggested_price_cents).to eq 2500
expect(yearly_price.price_cents).to eq 9999
expect(yearly_price.suggested_price_cents).to be_nil
end
it "saves product prices with price_cents 0" do
@variant.save_recurring_prices!(@recurrence_price_values)
prices = @variant.link.prices.alive
monthly_price = prices.find_by(recurrence: BasePrice::Recurrence::MONTHLY)
yearly_price = prices.find_by(recurrence: BasePrice::Recurrence::YEARLY)
expect(prices.length).to eq 2
expect(monthly_price.price_cents).to eq 0
expect(monthly_price.suggested_price_cents).to eq 0
expect(yearly_price.price_cents).to eq 0
expect(yearly_price.suggested_price_cents).to be_nil
end
it "deletes any old prices" do
biannual_price = create(:variant_price, variant: @variant, recurrence: BasePrice::Recurrence::BIANNUALLY)
quarterly_price = create(:variant_price, variant: @variant, recurrence: BasePrice::Recurrence::QUARTERLY)
non_recurring_price = create(:variant_price, variant: @variant, recurrence: nil)
@variant.save_recurring_prices!(@recurrence_price_values)
expect(@variant.prices.alive.length).to eq 2
expect(biannual_price.reload).to be_deleted
expect(quarterly_price.reload).to be_deleted
expect(non_recurring_price.reload).to be_deleted
end
context "updating Elasticsearch" do
before :each do
@variant.save_recurring_prices!(@recurrence_price_values)
@product = @variant.link
end
it "enqueues Elasticsearch update if a price is new or has changed" do
updated_recurrence_prices = @recurrence_price_values.merge(
BasePrice::Recurrence::MONTHLY => {
enabled: true,
price: "25",
suggested_price: "30"
},
BasePrice::Recurrence::QUARTERLY => {
enabled: true,
price: "70",
suggested_price: "75"
}
)
# update is called for the changed monthly variant price and new quarterly variant and product prices
expect(@product).to receive(:enqueue_index_update_for).with(["price_cents", "available_price_cents"]).exactly(3).times
@variant.save_recurring_prices!(updated_recurrence_prices)
end
it "does not enqueue Elasticsearch update if prices have not changed" do
expect(@product).not_to receive(:enqueue_index_update_for).with(["price_cents", "available_price_cents"])
@variant.save_recurring_prices!(@recurrence_price_values)
end
it "enqueues Elasticsearch update if a prices is disabled" do
updated_recurrence_prices = @recurrence_price_values.merge(
BasePrice::Recurrence::YEARLY => { enabled: false }
)
# called for yearly variant price change and product price
expect(@product).to receive(:enqueue_index_update_for).with(["price_cents", "available_price_cents"]).exactly(2).times
@variant.save_recurring_prices!(updated_recurrence_prices)
end
end
context "missing price" do
it "raises an error" do
invalid_values = @recurrence_price_values
invalid_values[BasePrice::Recurrence::MONTHLY].delete(:price)
expect do
@variant.save_recurring_prices!(invalid_values)
end.to raise_error Link::LinkInvalid
end
end
context "with price that is too low" do
it "raises an error" do
@recurrence_price_values[BasePrice::Recurrence::MONTHLY][:price] = "0.98"
expect do
@variant.save_recurring_prices!(@recurrence_price_values)
end.to raise_error ActiveRecord::RecordInvalid
end
end
context "with price that is too high" do
it "raises an error" do
@recurrence_price_values[BasePrice::Recurrence::MONTHLY][:price] = "5000.01"
expect do
@variant.save_recurring_prices!(@recurrence_price_values)
end.to raise_error ActiveRecord::RecordInvalid
end
end
end
describe "associations" do
context "has many `base_variant_integrations`" do
it "returns alive and deleted base_variant_integrations" do
integration_1 = create(:circle_integration)
integration_2 = create(:circle_integration)
variant = create(:variant, active_integrations: [integration_1, integration_2])
expect do
variant.base_variant_integrations.find_by(integration: integration_1).mark_deleted!
end.to change { variant.base_variant_integrations.count }.by(0)
expect(variant.base_variant_integrations.pluck(:integration_id)).to match_array [integration_1, integration_2].map(&:id)
end
end
context "has many `live_base_variant_integrations`" do
it "does not return deleted base_variant_integrations" do
integration_1 = create(:circle_integration)
integration_2 = create(:circle_integration)
variant = create(:variant, active_integrations: [integration_1, integration_2])
expect do
variant.base_variant_integrations.find_by(integration: integration_1).mark_deleted!
end.to change { variant.live_base_variant_integrations.count }.by(-1)
expect(variant.live_base_variant_integrations.pluck(:integration_id)).to match_array [integration_2.id]
end
end
context "has many `active_integrations`" do
it "does not return deleted integrations" do
integration_1 = create(:circle_integration)
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/call_spec.rb | spec/models/call_spec.rb | # frozen_string_literal: true
require "sidekiq/testing"
describe Call do
let(:link) { create(:call_product, :available_for_a_year) }
let(:call_limitation_info) { link.call_limitation_info }
describe "normalizations", :freeze_time do
before { travel_to(DateTime.parse("May 1 2024 UTC")) }
it "drops sub-minute precision from start_time and end_time when assigning" do
call = build(
:call,
start_time: DateTime.parse("May 8 2024 10:28:01.123456 UTC"),
end_time: DateTime.parse("May 9 2024 11:29:59.923456 UTC"),
link:
)
expect(call.start_time).to eq(DateTime.parse("May 8 2024 10:28 UTC"))
expect(call.end_time).to eq(DateTime.parse("May 9 2024 11:29 UTC"))
end
it "drops sub-minute precision from start_time and end_time when querying" do
call = create(
:call,
start_time: DateTime.parse("May 8 2024 10:28:01.123456 UTC"),
end_time: DateTime.parse("May 9 2024 11:29:59.923456 UTC"),
link:
)
expect(Call.find_by(start_time: call.start_time.change(sec: 2))).to eq(call)
expect(Call.find_by(end_time: call.end_time.change(sec: 58))).to eq(call)
end
end
describe "validations" do
it "validates that start_time is before end_time" do
call = build(:call, start_time: 2.days.from_now, end_time: 1.day.from_now)
expect(call).to be_invalid
expect(call.errors.full_messages).to include("Start time must be before end time.")
end
it "validates that start_time and end_time are present" do
call = build(:call, start_time: nil, end_time: nil)
expect(call).to be_invalid
expect(call.errors.full_messages).to include("Start time can't be blank", "End time can't be blank")
end
it "validates that the purchased product is a call" do
call = build(:call, purchase: create(:physical_purchase))
expect(call).to be_invalid
expect(call.errors.full_messages).to include("Purchased product must be a call")
end
it "validates that the selected time is allowed by #call_limitation_info" do
call = build(:call, link:)
allow(call_limitation_info).to receive(:allows?).with(call.start_time).and_return(false)
expect(call).to be_invalid
expect(call.errors.full_messages).to include("Selected time is no longer available")
allow(call_limitation_info).to receive(:allows?).with(call.start_time).and_return(true)
expect(call).to be_valid
end
it "validates that the selected time is available and not yet taken" do
call = build(:call, link:)
link.call_availabilities.destroy_all
expect(call).to be_invalid
expect(call.errors.full_messages).to include("Selected time is no longer available")
create(:call_availability, start_time: call.start_time, end_time: call.end_time, call: link)
expect(call).to be_valid
create(:call, start_time: call.start_time, end_time: call.end_time, purchase: build(:call_purchase, :refunded, link:))
expect(call).to be_valid
create(:call, start_time: call.start_time, end_time: call.end_time, link:)
expect(call).to be_invalid
expect(call.errors.full_messages).to include("Selected time is no longer available")
end
it "does not validate selected time availability for gift receiver purchases" do
start_time = 1.day.from_now
end_time = start_time + 1.hour
create(:call, start_time:, end_time:, link:)
call = build(:call, start_time:, end_time:, link:)
expect(call).to be_invalid
expect(call.errors.full_messages).to include("Selected time is no longer available")
call.purchase.is_gift_receiver_purchase = true
expect(call).to be_valid
end
end
describe "scopes", :freeze_time do
before { travel_to(DateTime.parse("May 1 2024 UTC")) }
let(:time_1) { 1.day.from_now }
let(:time_2) { 2.days.from_now }
let(:time_3) { 3.days.from_now }
let(:time_4) { 4.days.from_now }
describe ".occupies_availability" do
let!(:refunded) { create(:call_purchase, :refunded, link:) }
let!(:failed) { create(:call_purchase, purchase_state: "failed", link:) }
let!(:test_successful) { create(:call_purchase, purchase_state: "test_successful", link:) }
let!(:gift_receiver_purchase_successful) { create(:call_purchase, purchase_state: "gift_receiver_purchase_successful", link:) }
let!(:successful) { create(:call_purchase, purchase_state: "successful") }
let!(:not_charged) { create(:call_purchase, purchase_state: "not_charged") }
let!(:in_progress) { create(:call_purchase, purchase_state: "in_progress") }
it "returns calls that take up availability" do
expect(Call.occupies_availability).to contain_exactly(successful.call, not_charged.call, in_progress.call)
end
end
describe ".upcoming" do
let!(:not_started) { create(:call, :skip_validation, start_time: 2.days.from_now, end_time: 3.days.from_now, link:) }
let!(:started_but_not_ended) { create(:call, :skip_validation, start_time: 2.days.ago, end_time: 1.day.from_now, link:) }
let!(:ended) { create(:call, :skip_validation, start_time: 2.days.ago, end_time: 1.day.ago, link:) }
it "returns calls that haven't ended" do
expect(Call.upcoming).to contain_exactly(not_started, started_but_not_ended)
end
end
describe ".ordered_chronologically" do
let!(:call_2_to_3) { create(:call, start_time: time_2, end_time: time_3, link:) }
let!(:call_1_to_3) { create(:call, start_time: time_1, end_time: time_3) }
let!(:call_1_to_2) { create(:call, start_time: time_1, end_time: time_2, link:) }
it "returns calls ordered chronologically" do
expect(Call.ordered_chronologically.pluck(:id)).to eq([call_1_to_2.id, call_1_to_3.id, call_2_to_3.id])
end
end
describe ".starts_on_date" do
let(:pt) { ActiveSupport::TimeZone.new("Pacific Time (US & Canada)") }
let(:et) { ActiveSupport::TimeZone.new("Eastern Time (US & Canada)") }
let(:tomorrow_8_pm_pt) { pt.now.next_day.change(hour: 20) }
let(:tomorrow_10_pm_pt) { pt.now.next_day.change(hour: 22) }
let!(:call_tomorrow_8_pm_pt) { create(:call, start_time: tomorrow_8_pm_pt, end_time: tomorrow_8_pm_pt + 1.hour, link:) }
let!(:call_tomorrow_10_pm_pt) { create(:call, start_time: tomorrow_10_pm_pt, end_time: tomorrow_10_pm_pt + 1.hour, link:) }
it "returns calls that start on the given time's date in the given time zone" do
expect(Call.starts_on_date(tomorrow_8_pm_pt, pt)).to contain_exactly(call_tomorrow_8_pm_pt, call_tomorrow_10_pm_pt)
expect(Call.starts_on_date(tomorrow_8_pm_pt, et)).to contain_exactly(call_tomorrow_8_pm_pt)
end
end
describe ".overlaps_with" do
let!(:call_1_to_2) { create(:call, start_time: time_1, end_time: time_2, link:) }
let!(:call_3_to_4) { create(:call, start_time: time_3, end_time: time_4, link:) }
it "returns calls that overlap with the given time range" do
expect(Call.overlaps_with(time_1, time_2)).to contain_exactly(call_1_to_2)
expect(Call.overlaps_with(time_1, time_3)).to contain_exactly(call_1_to_2)
expect(Call.overlaps_with(time_1, time_4)).to contain_exactly(call_1_to_2, call_3_to_4)
expect(Call.overlaps_with(time_2, time_3)).to be_empty
expect(Call.overlaps_with(time_2, time_4)).to contain_exactly(call_3_to_4)
end
end
end
describe "#formatted_time_range" do
let(:call) { create(:call, :skip_validation, start_time: DateTime.parse("January 1 2024 10:00"), end_time: DateTime.parse("January 1 2024 11:00")) }
it "returns the formatted time range" do
expect(call.formatted_time_range).to eq("02:00 AM - 03:00 AM PST")
end
end
describe "#formatted_date_range" do
context "when start and end times are on the same day" do
let(:call) { create(:call, :skip_validation, start_time: DateTime.parse("January 1 2024 10:00"), end_time: DateTime.parse("January 1 2024 11:00")) }
it "returns the formatted date" do
expect(call.formatted_date_range).to eq("Monday, January 1st, 2024")
end
end
context "when start and end times are on different days" do
let(:call) { create(:call, :skip_validation, start_time: DateTime.parse("January 1 2024"), end_time: DateTime.parse("January 2 2024")) }
it "returns the formatted date range" do
expect(call.formatted_date_range).to eq("Sunday, December 31st, 2023 - Monday, January 1st, 2024")
end
end
end
describe "#eligible_for_reminder?" do
context "when the purchase is in progress" do
let(:purchase) { create(:call_purchase, purchase_state: "in_progress") }
let(:call) { purchase.call }
it "returns true" do
expect(call.eligible_for_reminder?).to be true
end
end
context "when the purchase is a gift sender purchase" do
let(:purchase) { create(:call_purchase, is_gift_sender_purchase: true) }
let(:call) { purchase.call }
it "returns false" do
expect(call.eligible_for_reminder?).to be false
end
end
context "when the purchase has been refunded" do
let(:purchase) { create(:call_purchase, :refunded) }
let(:call) { purchase.call }
it "returns false" do
expect(call.eligible_for_reminder?).to be false
end
end
context "when the purchase failed" do
let(:purchase) { create(:call_purchase, purchase_state: "failed") }
let(:call) { purchase.call }
it "returns false" do
expect(call.eligible_for_reminder?).to be false
end
end
context "when the purchase is a gift receiver purchase" do
let(:product) { create(:call_product, :available_for_a_year, name: "Portfolio review") }
let(:variant_category) { product.variant_categories.first }
let(:variant) { create(:variant, name: "60 minutes", duration_in_minutes: 60, variant_category:) }
let(:gifter_purchase) { create(:call_purchase, link: product, variant_attributes: [variant]) }
let(:giftee_purchase) { create(:call_purchase, :gift_receiver, link: product, variant_attributes: [variant]) }
let!(:gift) { create(:gift, gifter_purchase:, giftee_purchase:) }
let(:call) { giftee_purchase.call }
it "returns true" do
expect(call.eligible_for_reminder?).to be true
end
end
context "when the purchase is successful" do
let(:purchase) { create(:call_purchase, purchase_state: "successful") }
let(:call) { purchase.call }
it "returns true" do
expect(call.eligible_for_reminder?).to be true
end
end
end
describe "scheduling reminder emails" do
context "when the call is less than 24 hours away" do
let(:start_time) { 23.hours.from_now }
let(:end_time) { start_time + 1.hour }
let(:call) { build(:call, start_time:, end_time:, link:) }
it "does not schedule reminder emails" do
expect do
call.save!
end.to not_have_enqueued_mail(ContactingCreatorMailer, :upcoming_call_reminder)
.and not_have_enqueued_mail(CustomerMailer, :upcoming_call_reminder)
end
end
context "when the call is more than 24 hours away" do
let(:start_time) { 25.hours.from_now }
let(:end_time) { start_time + 1.hour }
let(:call) { build(:call, start_time:, end_time:, link:) }
it "schedules reminder emails" do
expect do
call.save!
end.to have_enqueued_mail(ContactingCreatorMailer, :upcoming_call_reminder)
.and have_enqueued_mail(CustomerMailer, :upcoming_call_reminder)
end
end
context "when the call is for a gift sender purchase" do
let(:start_time) { 25.hours.from_now }
let(:end_time) { start_time + 1.hour }
let(:call) { build(:call, start_time:, end_time:, purchase: create(:call_purchase, is_gift_sender_purchase: true)) }
it "does not schedule reminder emails" do
expect do
call.save!
end.to not_have_enqueued_mail(ContactingCreatorMailer, :upcoming_call_reminder)
.and not_have_enqueued_mail(CustomerMailer, :upcoming_call_reminder)
end
end
end
describe "google calendar integration" do
let(:integration) { create(:google_calendar_integration) }
let(:call) { create(:call, link: create(:call_product, :available_for_a_year, active_integrations: [integration])) }
let(:call2) { create(:call, link: create(:call_product, :available_for_a_year)) }
it "schedules google calendar invites" do
expect do
call.save!
end.to change(GoogleCalendarInviteJob.jobs, :size).by(1)
expect(GoogleCalendarInviteJob.jobs.last["args"]).to eq([call.id])
end
it "does not schedule google calendar invites if the call is not linked to a google calendar integration" do
expect do
call2.save!
end.to change(GoogleCalendarInviteJob.jobs, :size).by(0)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/saint_lucia_bank_account_spec.rb | spec/models/saint_lucia_bank_account_spec.rb | # frozen_string_literal: true
describe SaintLuciaBankAccount do
describe "#bank_account_type" do
it "returns LC" do
expect(create(:saint_lucia_bank_account).bank_account_type).to eq("LC")
end
end
describe "#country" do
it "returns LC" do
expect(create(:saint_lucia_bank_account).country).to eq("LC")
end
end
describe "#currency" do
it "returns xcd" do
expect(create(:saint_lucia_bank_account).currency).to eq("xcd")
end
end
describe "#routing_number" do
it "returns valid for 8 to 11 characters" do
expect(build(:saint_lucia_bank_account, bank_code: "AAAALCLCXYZ")).to be_valid
expect(build(:saint_lucia_bank_account, bank_code: "AAAALCLC")).to be_valid
expect(build(:saint_lucia_bank_account, bank_code: "AAAALCLCXYZZ")).not_to be_valid
expect(build(:saint_lucia_bank_account, bank_code: "AAAALCL")).not_to be_valid
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:saint_lucia_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(:saint_lucia_bank_account)).to be_valid
expect(build(:saint_lucia_bank_account, account_number: "000123456789")).to be_valid
expect(build(:saint_lucia_bank_account, account_number: "00012345678910111213141516171819")).to be_valid
expect(build(:saint_lucia_bank_account, account_number: "ABC12345678910111213141516171819")).to be_valid
expect(build(:saint_lucia_bank_account, account_number: "12345678910111213141516171819ABC")).to be_valid
lc_bank_account = build(:saint_lucia_bank_account, account_number: "000123456789101112131415161718192")
expect(lc_bank_account).to_not be_valid
expect(lc_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
lc_bank_account = build(:saint_lucia_bank_account, account_number: "ABCD12345678910111213141516171819")
expect(lc_bank_account).to_not be_valid
expect(lc_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
lc_bank_account = build(:saint_lucia_bank_account, account_number: "12345678910111213141516171819ABCD")
expect(lc_bank_account).to_not be_valid
expect(lc_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
lc_bank_account = build(:saint_lucia_bank_account, account_number: "AB12345678910111213141516171819CD")
expect(lc_bank_account).to_not be_valid
expect(lc_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/product_integration_spec.rb | spec/models/product_integration_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ProductIntegration do
describe "validations" do
before do
@integration = create(:circle_integration)
@product = create(:product)
end
it "raises error if product_id is not present" do
product_integration = ProductIntegration.new(integration_id: @integration.id)
expect(product_integration.valid?).to eq(false)
expect(product_integration.errors.full_messages).to include("Product can't be blank")
end
it "raises error if integration_id is not present" do
product_integration = ProductIntegration.new(product_id: @product.id)
expect(product_integration.valid?).to eq(false)
expect(product_integration.errors.full_messages).to include("Integration can't be blank")
end
it "raises error if (product_id, integration_id) is not unique" do
ProductIntegration.create!(integration_id: @integration.id, product_id: @product.id)
product_integration_2 = ProductIntegration.new(integration_id: @integration.id, product_id: @product.id)
expect(product_integration_2.valid?).to eq(false)
expect(product_integration_2.errors.full_messages).to include("Integration has already been taken")
end
it "is successful if (product_id, integration_id) is not unique but all clashing entries have been deleted" do
product_integration_1 = ProductIntegration.create!(integration_id: @integration.id, product_id: @product.id)
product_integration_1.mark_deleted!
ProductIntegration.create!(integration_id: @integration.id, product_id: @product.id)
expect(ProductIntegration.count).to eq(2)
expect(@product.active_integrations.count).to eq(1)
end
it "is successful if same product has different integrations" do
ProductIntegration.create!(integration_id: @integration.id, product_id: @product.id)
ProductIntegration.create!(integration_id: create(:circle_integration).id, product_id: @product.id)
expect(ProductIntegration.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/zoom_integration_spec.rb | spec/models/zoom_integration_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ZoomIntegration do
it "creates the correct json details" do
integration = create(:zoom_integration)
ZoomIntegration::INTEGRATION_DETAILS.each do |detail|
expect(integration.respond_to?(detail)).to eq true
end
end
it "saves details correctly" do
integration = create(:zoom_integration)
expect(integration.type).to eq(Integration.type_for(Integration::ZOOM))
expect(integration.user_id).to eq("0")
expect(integration.email).to eq("test@zoom.com")
expect(integration.access_token).to eq("test_access_token")
expect(integration.refresh_token).to eq("test_refresh_token")
end
describe "#as_json" do
it "returns the correct json object" do
integration = create(:zoom_integration)
expect(integration.as_json).to eq({ keep_inactive_members: false,
name: "zoom", integration_details: {
"user_id" => "0",
"email" => "test@zoom.com",
"access_token" => "test_access_token",
"refresh_token" => "test_refresh_token",
} })
end
end
describe ".is_enabled_for" do
it "returns true if a zoom integration is enabled on the product" do
product = create(:product, active_integrations: [create(:zoom_integration)])
purchase = create(:purchase, link: product)
expect(ZoomIntegration.is_enabled_for(purchase)).to eq(true)
end
it "returns false if a zoom integration is not enabled on the product" do
product = create(:product, active_integrations: [create(:discord_integration)])
purchase = create(:purchase, link: product)
expect(ZoomIntegration.is_enabled_for(purchase)).to eq(false)
end
it "returns false if a deleted zoom integration exists on the product" do
product = create(:product, active_integrations: [create(:zoom_integration)])
purchase = create(:purchase, link: product)
product.product_integrations.first.mark_deleted!
expect(ZoomIntegration.is_enabled_for(purchase)).to eq(false)
end
end
describe "#same_connection?" do
let(:zoom_integration) { create(:zoom_integration) }
let(:same_connection_zoom_integration) { create(:zoom_integration) }
let(:other_zoom_integration) { create(:zoom_integration, user_id: "1") }
it "returns true if both integrations have the same user id" do
expect(zoom_integration.same_connection?(same_connection_zoom_integration)).to eq(true)
end
it "returns false if both integrations have different user ids" do
expect(zoom_integration.same_connection?(other_zoom_integration)).to eq(false)
end
it "returns false if both integrations have different types" do
same_connection_zoom_integration.update(type: "NotZoomIntegration")
expect(zoom_integration.same_connection?(same_connection_zoom_integration)).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/large_seller_spec.rb | spec/models/large_seller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe LargeSeller do
before do
@user = create(:user)
end
describe ".create_if_warranted" do
it "doesn't create a record if large seller already exists" do
create(:large_seller, user: @user)
expect do
described_class.create_if_warranted(@user)
end.not_to change(LargeSeller, :count)
end
it "doesn't create a record if sales count below lower limit" do
allow(@user).to receive(:sales).and_return(double(count: 90))
expect do
described_class.create_if_warranted(@user)
end.not_to change(LargeSeller, :count)
end
it "creates a record if sales count above lower limit" do
allow(@user).to receive(:sales).and_return(double(count: 7_000))
expect do
described_class.create_if_warranted(@user)
end.to change(LargeSeller, :count)
expect(@user.large_seller).to be_present
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/mongolia_bank_account_spec.rb | spec/models/mongolia_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe MongoliaBankAccount do
describe "#bank_account_type" do
it "returns MN" do
expect(create(:mongolia_bank_account).bank_account_type).to eq("MN")
end
end
describe "#country" do
it "returns MN" do
expect(create(:mongolia_bank_account).country).to eq("MN")
end
end
describe "#currency" do
it "returns mnt" do
expect(create(:mongolia_bank_account).currency).to eq("mnt")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:mongolia_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAAMNUBXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:mongolia_bank_account, account_number_last_four: "2001").account_number_visual).to eq("******2001")
end
end
describe "#validate_bank_code" do
it "allows 8 to 11 characters only" do
expect(build(:mongolia_bank_account, bank_code: "AAAAMNUBXXX")).to be_valid
expect(build(:mongolia_bank_account, bank_code: "AAAAMNUB")).to be_valid
expect(build(:mongolia_bank_account, bank_code: "AAAAMNUBXXXX")).not_to be_valid
expect(build(:mongolia_bank_account, bank_code: "AAAAMNU")).not_to be_valid
end
end
describe "#validate_account_number" do
let(:bank_account) { build(:mongolia_bank_account) }
it "validates account number format" do
bank_account.account_number = "000123456789"
bank_account.account_number_last_four = "6789"
expect(bank_account).to be_valid
bank_account.account_number = "1234"
bank_account.account_number_last_four = "1234"
expect(bank_account).to be_valid
bank_account.account_number = "1234567890123456"
bank_account.account_number_last_four = "3456"
expect(bank_account).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/sent_email_info_spec.rb | spec/models/sent_email_info_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SentEmailInfo do
describe "validations" do
it "doesn't allow empty keys" do
expect do
SentEmailInfo.set_key!(nil)
end.to raise_error(ActiveRecord::RecordInvalid)
end
it "doesn't allow duplicate keys" do
SentEmailInfo.set_key!("key")
expect do
sent_email_info = SentEmailInfo.new
sent_email_info.key = "key"
sent_email_info.save!
end.to raise_error(ActiveRecord::RecordNotUnique)
end
end
describe ".key_exists?" do
before do
@sent_email_info = create(:sent_email_info)
end
it "returns true if record exists" do
expect(SentEmailInfo.key_exists?(@sent_email_info.key)).to eq true
expect(SentEmailInfo.key_exists?("non-existing-key")).to eq false
end
end
describe ".set_key!" do
before do
@sent_email_info = SentEmailInfo.set_key!("test_key")
end
it "sets the record in SentEmailInfo" do
expect(@sent_email_info).to eq(true)
expect(SentEmailInfo.find_by(key: "test_key")).not_to be_nil
end
it "doesn't set duplicate records" do
was_set = SentEmailInfo.set_key!("test_key")
expect(was_set).to eq(nil)
expect(SentEmailInfo.where(key: "test_key").count).to eq 1
end
end
describe ".mailer_exists?" do
it "returns true if a record exists for the mailer" do
expect(SentEmailInfo.mailer_exists?("Mailer", "action", 123, 456)).to eq(false)
SentEmailInfo.ensure_mailer_uniqueness("Mailer", "action", 123, 456) { }
expect(SentEmailInfo.mailer_exists?("Mailer", "action", 123, 456)).to eq(true)
end
end
describe ".ensure_mailer_uniqueness" do
before do
@shipment = create(:shipment)
end
it "doesn't allow sending email for given key and params" do
expect do
SentEmailInfo.ensure_mailer_uniqueness("CustomerLowPriorityMailer",
"order_shipped",
@shipment.id) do
CustomerLowPriorityMailer.order_shipped(@shipment.id).deliver_later
end
SentEmailInfo.ensure_mailer_uniqueness("CustomerLowPriorityMailer",
"order_shipped",
@shipment.id) do
CustomerLowPriorityMailer.order_shipped(@shipment.id).deliver_later
end
end.to have_enqueued_mail(CustomerLowPriorityMailer, :order_shipped).once
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/tanzania_bank_account_spec.rb | spec/models/tanzania_bank_account_spec.rb | # frozen_string_literal: true
describe TanzaniaBankAccount do
describe "#bank_account_type" do
it "returns TZ" do
expect(create(:tanzania_bank_account).bank_account_type).to eq("TZ")
end
end
describe "#country" do
it "returns TZ" do
expect(create(:tanzania_bank_account).country).to eq("TZ")
end
end
describe "#currency" do
it "returns tzs" do
expect(create(:tanzania_bank_account).currency).to eq("tzs")
end
end
describe "#routing_number" do
it "returns valid for 8 to 11 characters" do
expect(build(:tanzania_bank_account, bank_code: "AAAATZTXXXX")).to be_valid
expect(build(:tanzania_bank_account, bank_code: "AAAATZTX")).to be_valid
expect(build(:tanzania_bank_account, bank_code: "AAAATZTXXXXX")).not_to be_valid
expect(build(:tanzania_bank_account, bank_code: "AAAATZT")).not_to be_valid
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:tanzania_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(:tanzania_bank_account)).to be_valid
expect(build(:tanzania_bank_account, account_number: "0000123456789")).to be_valid
expect(build(:tanzania_bank_account, account_number: "0000123456")).to be_valid
expect(build(:tanzania_bank_account, account_number: "ABC12345678")).to be_valid
expect(build(:tanzania_bank_account, account_number: "0001234567ABCD")).to be_valid
na_bank_account = build(:tanzania_bank_account, account_number: "000012345")
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(:tanzania_bank_account, account_number: "000012345678910")
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(:tanzania_bank_account, account_number: "0001234567ABCDE")
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(:tanzania_bank_account, account_number: "ABCDE0001234567")
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/seller_profile_products_section_spec.rb | spec/models/seller_profile_products_section_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SellerProfileProductsSection do
describe "validations" do
it "validates json_data with the correct schema" do
section = build(:seller_profile_products_section, shown_products: [create(:product, name: "Product 1").id])
section.json_data["garbage"] = "should not be here"
schema = JSON.parse(File.read(Rails.root.join("lib", "json_schemas", "seller_profile_products_section.json").to_s))
expect(JSON::Validator).to receive(:new).with(schema, insert_defaults: true, record_errors: true).and_wrap_original do |original, *args|
validator = original.call(*args)
expect(validator).to receive(:validate).with(section.json_data).and_call_original
validator
end
section.validate
expect(section.errors.full_messages.to_sentence).to eq("The property '#/' contains additional properties [\"garbage\"] outside of the schema when none are allowed")
end
end
describe "#product_names" do
let(:seller) { create(:user) }
let(:section) { create(:seller_profile_products_section, seller:, shown_products: [create(:product, user: seller, name: "Product 1").id, create(:product, user: seller, name: "Product 2").id]) }
it "returns the names of the products in the section" do
expect(section.product_names).to eq(["Product 1", "Product 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/commission_spec.rb | spec/models/commission_spec.rb | # frozen_string_literal: true
describe Commission, :vcr do
describe "validations" do
it "validates inclusion of status in STATUSES" do
commission = build(:commission, status: "invalid_status")
expect(commission).to be_invalid
expect(commission.errors.full_messages).to include("Status is not included in the list")
commission.status = nil
expect(commission).to be_invalid
expect(commission.errors.full_messages).to include("Status is not included in the list")
end
it "validates presence of deposit_purchase" do
commission = build(:commission, deposit_purchase: nil)
expect(commission).to be_invalid
expect(commission.errors.full_messages).to include("Deposit purchase must exist")
end
it "validates that deposit_purchase and completion_purchase are different" do
purchase = create(:purchase)
commission = build(:commission, deposit_purchase: purchase, completion_purchase: purchase)
expect(commission).to be_invalid
expect(commission.errors.full_messages).to include("Deposit purchase and completion purchase must be different purchases")
end
it "validates that deposit_purchase and completion_purchase belong to the same commission" do
commission = build(:commission, deposit_purchase: create(:purchase, link: create(:product)), completion_purchase: create(:purchase, link: create(:product)))
expect(commission).to be_invalid
expect(commission.errors.full_messages).to include("Deposit purchase and completion purchase must belong to the same commission product")
end
it "validates that the purchased product is a commission" do
product = create(:product, native_type: Link::NATIVE_TYPE_DIGITAL)
commission = build(:commission, deposit_purchase: create(:purchase, link: product), completion_purchase: create(:purchase, link: product))
expect(commission).to be_invalid
expect(commission.errors.full_messages).to include("Purchased product must be a commission")
end
end
describe "#create_completion_purchase!" do
context "when status is already completed" do
let!(:commission) { create(:commission, status: Commission::STATUS_COMPLETED) }
it "does not create a completion purchase" do
expect { commission.create_completion_purchase! }.not_to change { Purchase.count }
end
end
context "when status is not completed" do
let(:commission) { create(:commission, status: Commission::STATUS_IN_PROGRESS) }
let(:deposit_purchase) { commission.deposit_purchase }
let(:product) { deposit_purchase.link }
before do
deposit_purchase.update!(zip_code: "10001")
deposit_purchase.update!(displayed_price_cents: 100)
deposit_purchase.create_tip!(value_cents: 20)
deposit_purchase.variant_attributes << create(:variant, name: "Deluxe")
end
it "creates a completion purchase with correct attributes, processes it, and updates status" do
expect { commission.create_completion_purchase! }.to change { Purchase.count }.by(1)
completion_purchase = commission.reload.completion_purchase
expect(completion_purchase.perceived_price_cents).to eq((deposit_purchase.price_cents / Commission::COMMISSION_DEPOSIT_PROPORTION) - deposit_purchase.price_cents)
expect(completion_purchase.link).to eq(deposit_purchase.link)
expect(completion_purchase.purchaser).to eq(deposit_purchase.purchaser)
expect(completion_purchase.credit_card_id).to eq(deposit_purchase.credit_card_id)
expect(completion_purchase.email).to eq(deposit_purchase.email)
expect(completion_purchase.full_name).to eq(deposit_purchase.full_name)
expect(completion_purchase.street_address).to eq(deposit_purchase.street_address)
expect(completion_purchase.country).to eq(deposit_purchase.country)
expect(completion_purchase.zip_code).to eq(deposit_purchase.zip_code)
expect(completion_purchase.city).to eq(deposit_purchase.city)
expect(completion_purchase.ip_address).to eq(deposit_purchase.ip_address)
expect(completion_purchase.ip_state).to eq(deposit_purchase.ip_state)
expect(completion_purchase.ip_country).to eq(deposit_purchase.ip_country)
expect(completion_purchase.browser_guid).to eq(deposit_purchase.browser_guid)
expect(completion_purchase.referrer).to eq(deposit_purchase.referrer)
expect(completion_purchase.quantity).to eq(deposit_purchase.quantity)
expect(completion_purchase.was_product_recommended).to eq(deposit_purchase.was_product_recommended)
expect(completion_purchase.seller).to eq(deposit_purchase.seller)
expect(completion_purchase.credit_card_zipcode).to eq(deposit_purchase.credit_card_zipcode)
expect(completion_purchase.affiliate).to eq(deposit_purchase.affiliate.try(:alive?) ? deposit_purchase.affiliate : nil)
expect(completion_purchase.offer_code).to eq(deposit_purchase.offer_code)
expect(completion_purchase.is_commission_completion_purchase).to be true
expect(completion_purchase.tip.value_cents).to eq(20)
expect(completion_purchase.variant_attributes).to eq(deposit_purchase.variant_attributes)
expect(completion_purchase).to be_successful
expect(commission.reload.status).to eq(Commission::STATUS_COMPLETED)
end
context "when the completion purchase fails" do
it "marks the purchase as failed" do
expect(Stripe::PaymentIntent).to receive(:create).and_raise(Stripe::IdempotencyError)
expect { commission.create_completion_purchase! }.to raise_error(ActiveRecord::RecordInvalid)
purchase = Purchase.last
expect(purchase).to be_failed
expect(purchase.is_commission_completion_purchase).to eq(true)
expect(commission.reload.completion_purchase).to be_nil
end
end
context "when the product price changes after the deposit purchase" do
it "creates a completion purchase with the original price" do
product.update!(price_cents: product.price_cents + 1000)
expect { commission.create_completion_purchase! }.to change { Purchase.count }.by(1)
completion_purchase = commission.reload.completion_purchase
expect(completion_purchase.perceived_price_cents).to eq((deposit_purchase.price_cents / Commission::COMMISSION_DEPOSIT_PROPORTION) - deposit_purchase.price_cents)
end
end
end
context "when the product adds a new variant after the deposit purchase" do
let!(:product) { create(:commission_product, price_cents: 1000) }
let!(:deposit_purchase) { create(:commission_deposit_purchase, link: product) }
let!(:commission) { create(:commission, status: Commission::STATUS_IN_PROGRESS, deposit_purchase: deposit_purchase) }
it "creates a completion purchase without any variant attributes" do
expect(deposit_purchase.variant_attributes).to be_empty
expect(deposit_purchase.price_cents).to eq(500)
create(:variant, price_difference_cents: 2000, variant_category: create(:variant_category, link: product))
expect { commission.create_completion_purchase! }.to change { Purchase.count }.by(1)
completion_purchase = commission.reload.completion_purchase
expect(completion_purchase.price_cents).to eq(500)
end
end
context "when the purchased variant has changed since the deposit purchase" do
let!(:product) { create(:commission_product, price_cents: 1000) }
let!(:category) { create(:variant_category, link: product, title: "Version") }
let!(:variant) { create(:variant, variant_category: category, price_difference_cents: 1000) }
let!(:deposit_purchase) { create(:commission_deposit_purchase, link: product, variant_attributes: [variant]) }
let!(:commission) { create(:commission, status: Commission::STATUS_IN_PROGRESS, deposit_purchase: deposit_purchase) }
context "variant price changed" do
it "creates a completion purchase with the original price" do
expect(deposit_purchase.price_cents).to eq(1000)
Product::VariantsUpdaterService.new(
product:,
variants_params: [
{
id: category.external_id,
name: category.title,
options: [
{
id: variant.external_id,
name: variant.name,
price_difference_cents: 2000,
}
],
}
]
).perform
expect { commission.create_completion_purchase! }.to change { Purchase.count }.by(1)
completion_purchase = commission.reload.completion_purchase
expect(completion_purchase.price_cents).to eq(1000)
end
end
context "variant soft deleted" do
it "creates a completion purchase with the original price" do
expect(deposit_purchase.price_cents).to eq(1000)
variant.mark_deleted!
expect { commission.create_completion_purchase! }.to change { Purchase.count }.by(1)
completion_purchase = commission.reload.completion_purchase
expect(completion_purchase.price_cents).to eq(1000)
end
end
end
context "when the deposit purchase used a discount code" do
let!(:product) { create(:commission_product, price_cents: 2000) }
let!(:offer_code) { create(:offer_code, products: [product], amount_cents: 1000) }
let!(:deposit_purchase) { create(:commission_deposit_purchase, link: product, offer_code:, discount_code: offer_code.code) }
let!(:commission) { create(:commission, status: Commission::STATUS_IN_PROGRESS, deposit_purchase: deposit_purchase) }
it "creates a completion purchase with the original price" do
expect(deposit_purchase.price_cents).to eq(500)
expect { commission.create_completion_purchase! }.to change { Purchase.count }.by(1)
completion_purchase = commission.reload.completion_purchase
expect(completion_purchase.price_cents).to eq(500)
end
context "offer code has been soft deleted" do
it "creates a completion purchase with the original price" do
expect(deposit_purchase.price_cents).to eq(500)
offer_code.mark_deleted!
expect { commission.reload.create_completion_purchase! }.to change { Purchase.count }.by(1)
completion_purchase = commission.reload.completion_purchase
expect(completion_purchase.price_cents).to eq(500)
end
end
context "offer code is single-use" do
it "creates a completion purchase with the original price" do
expect(deposit_purchase.price_cents).to eq(500)
offer_code.update!(max_purchase_count: 1)
expect { commission.reload.create_completion_purchase! }.to change { Purchase.count }.by(1)
completion_purchase = commission.reload.completion_purchase
expect(completion_purchase.price_cents).to eq(500)
end
end
end
context "when the deposit purchase has PPP discount applied" do
before do
PurchasingPowerParityService.new.set_factor("LV", 0.5)
end
let(:seller) do
create(
:user,
:eligible_for_service_products,
purchasing_power_parity_enabled: true,
purchasing_power_parity_payment_verification_disabled: true
)
end
let!(:product) { create(:commission_product, price_cents: 2000, user: seller) }
let!(:deposit_purchase) do
create(
:commission_deposit_purchase,
link: product,
is_purchasing_power_parity_discounted: true,
ip_country: "Latvia",
card_country: "LV"
).tap do |purchase|
purchase.create_purchasing_power_parity_info(factor: 0.5)
end
end
let!(:commission) { create(:commission, status: Commission::STATUS_IN_PROGRESS, deposit_purchase:) }
it "creates a completion purchase with PPP discount applied" do
expect(deposit_purchase.is_purchasing_power_parity_discounted).to eq(true)
expect(deposit_purchase.purchasing_power_parity_info).to be_present
expect(deposit_purchase.purchasing_power_parity_info.factor).to eq(0.5)
expect { commission.create_completion_purchase! }.to change { Purchase.count }.by(1)
completion_purchase = commission.reload.completion_purchase
expect(completion_purchase.is_purchasing_power_parity_discounted).to eq(true)
expect(completion_purchase.purchasing_power_parity_info).to be_present
expect(completion_purchase.purchasing_power_parity_info.factor).to eq(0.5)
expect(completion_purchase.price_cents).to eq(500)
end
end
end
describe "#completion_price_cents" do
let(:deposit_purchase) { create(:purchase, price_cents: 5000, is_commission_deposit_purchase: true) }
let(:commission) { create(:commission, deposit_purchase: deposit_purchase) }
it "returns the correct completion price" do
expect(commission.completion_price_cents).to eq(5000)
end
end
describe "statuses" do
let(:commission) { build(:commission) }
describe "#is_in_progress?" do
it "returns true if the status is in_progress" do
commission.status = Commission::STATUS_IN_PROGRESS
expect(commission.is_in_progress?).to be true
end
it "returns false if the status is completed or cancelled" do
commission.status = Commission::STATUS_COMPLETED
expect(commission.is_in_progress?).to be false
commission.status = Commission::STATUS_CANCELLED
expect(commission.is_in_progress?).to be false
end
end
describe "#is_completed?" do
it "returns true if the status is completed" do
commission.status = Commission::STATUS_COMPLETED
expect(commission.is_completed?).to be true
end
it "returns false if the status is in_progress or cancelled" do
commission.status = Commission::STATUS_IN_PROGRESS
expect(commission.is_completed?).to be false
commission.status = Commission::STATUS_CANCELLED
expect(commission.is_completed?).to be false
end
end
describe "#is_cancelled?" do
it "returns true if the status is cancelled" do
commission.status = Commission::STATUS_CANCELLED
expect(commission.is_cancelled?).to be true
end
it "returns false if the status is in_progress or completed" do
commission.status = Commission::STATUS_IN_PROGRESS
expect(commission.is_cancelled?).to be false
commission.status = Commission::STATUS_COMPLETED
expect(commission.is_cancelled?).to be false
end
end
end
describe "#completion_display_price_cents" do
let(:deposit_purchase) { create(:purchase, displayed_price_cents: 5000, is_commission_deposit_purchase: true) }
let(:commission) { create(:commission, deposit_purchase: deposit_purchase) }
it "returns the correct completion price" do
expect(commission.completion_display_price_cents).to eq(5000)
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_review_stat_spec.rb | spec/models/product_review_stat_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ProductReviewStat do
describe "#rating_counts" do
it "returns counts of ratings" do
review_stat = build(:product_review_stat, ratings_of_one_count: 7, ratings_of_three_count: 11)
expect(review_stat.rating_counts).to eq(1 => 7, 2 => 0, 3 => 11, 4 => 0, 5 => 0)
end
end
describe "#rating_percentages" do
it "returns zero when there are no ratings" do
review_stat = build(:product_review_stat)
expect(review_stat.rating_percentages).to eq(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0)
end
it "returns percentages" do
review_stat = build(:product_review_stat, reviews_count: 4, ratings_of_one_count: 1, ratings_of_three_count: 3)
expect(review_stat.rating_percentages).to eq(1 => 25, 2 => 0, 3 => 75, 4 => 0, 5 => 0)
end
it "adjusts non-integer values to total 100" do
review_stat = build(
:product_review_stat,
reviews_count: 4 + 3 + 7 + 12 + 428,
ratings_of_one_count: 4,
ratings_of_two_count: 3,
ratings_of_three_count: 7,
ratings_of_four_count: 12,
ratings_of_five_count: 428
)
expect(review_stat.rating_percentages).to eq(1 => 1, 2 => 1, 3 => 1, 4 => 3, 5 => 94)
end
it "favors rounding percentages for higher star ratings if there are ties" do
review_stat = build(
:product_review_stat,
reviews_count: 3,
ratings_of_one_count: 1,
ratings_of_three_count: 1,
ratings_of_five_count: 1
)
expect(review_stat.rating_percentages).to eq(1 => 33, 2 => 0, 3 => 33, 4 => 0, 5 => 34)
end
end
describe "#update_with_added_rating" do
it "correctly updates the target & derived columns" do
review_stat = create(:product_review_stat)
review_stat.update_with_added_rating(2)
expect(review_stat.attributes).to include(
"ratings_of_one_count" => 0,
"ratings_of_two_count" => 1,
"ratings_of_three_count" => 0,
"ratings_of_four_count" => 0,
"ratings_of_five_count" => 0,
"reviews_count" => 1,
"average_rating" => 2.0,
)
review_stat.update_with_added_rating(4)
review_stat.update_with_added_rating(2)
expect(review_stat.attributes).to include(
"ratings_of_one_count" => 0,
"ratings_of_two_count" => 2,
"ratings_of_three_count" => 0,
"ratings_of_four_count" => 1,
"ratings_of_five_count" => 0,
"reviews_count" => 3,
"average_rating" => 2.7,
)
end
end
describe "#update_with_changed_rating" do
it "correctly updates the targets & derived columns" do
review_stat = create(:product_review_stat, ratings_of_five_count: 3)
review_stat.update_with_changed_rating(5, 4)
expect(review_stat.attributes).to include(
"ratings_of_one_count" => 0,
"ratings_of_two_count" => 0,
"ratings_of_three_count" => 0,
"ratings_of_four_count" => 1,
"ratings_of_five_count" => 2,
"reviews_count" => 3,
"average_rating" => 4.7,
)
end
end
describe "#update_with_removed_rating" do
it "correctly updates the targets & derived columns" do
review_stat = create(:product_review_stat, ratings_of_four_count: 1, ratings_of_five_count: 2)
review_stat.update_with_removed_rating(5)
expect(review_stat.attributes).to include(
"ratings_of_one_count" => 0,
"ratings_of_two_count" => 0,
"ratings_of_three_count" => 0,
"ratings_of_four_count" => 1,
"ratings_of_five_count" => 1,
"reviews_count" => 2,
"average_rating" => 4.5,
)
end
end
describe "#update_ratings" do
it "updates reviews_count and average_rating appropriately" do
review_stat = create(:product_review_stat)
review_stat.send(:update_ratings, "
ratings_of_one_count = 5,
ratings_of_two_count = 10,
ratings_of_three_count = 20,
ratings_of_four_count = 60,
ratings_of_five_count = 100
")
expect(review_stat.attributes).to include(
"ratings_of_one_count" => 5,
"ratings_of_two_count" => 10,
"ratings_of_three_count" => 20,
"ratings_of_four_count" => 60,
"ratings_of_five_count" => 100,
"reviews_count" => 195,
"average_rating" => 4.2
)
end
end
it "is updated after a purchase is fully refunded", :vcr do
product = create(:product)
purchase = create(:purchase_in_progress, link: product, chargeable: create(:chargeable))
purchase.process!
purchase.update_balance_and_mark_successful!
create(:product_review, purchase: create(:purchase, link: product), rating: 1)
create(:product_review, purchase: create(:purchase, link: product), rating: 5)
create(:product_review, purchase:, rating: 1)
review_stat = product.reload.product_review_stat
expect(review_stat.attributes).to include(
"ratings_of_one_count" => 2,
"ratings_of_two_count" => 0,
"ratings_of_three_count" => 0,
"ratings_of_four_count" => 0,
"ratings_of_five_count" => 1,
"reviews_count" => 3,
"average_rating" => 2.3
)
purchase.refund_and_save!(create(:admin_user).id)
expect(review_stat.reload.attributes).to include(
"ratings_of_one_count" => 1,
"ratings_of_two_count" => 0,
"ratings_of_three_count" => 0,
"ratings_of_four_count" => 0,
"ratings_of_five_count" => 1,
"reviews_count" => 2,
"average_rating" => 3.0
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/link_spec.rb | spec/models/link_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/max_purchase_count_concern"
describe Link, :vcr do
include PreorderHelper
let(:link) { create(:product) }
subject { link }
before do
@mock_obj = Object.new
allow(@mock_obj).to receive(:code).and_return(200)
allow(HTTParty).to receive(:head).and_return(@mock_obj)
end
it_behaves_like "MaxPurchaseCount concern", :product
it "is not a single-unit currency" do
expect(subject.send(:single_unit_currency?)).to be(false)
end
describe "max_purchase_count validations" do
it "can be set on new records with no purchases" do
expect(build(:product, max_purchase_count: nil).valid?).to eq(true)
end
it "prevents to change when inventory sold is greater than the new value" do
product = create(:product, max_purchase_count: 5)
create_list(:purchase, 2, link: product)
product.reload
expect(product.valid?).to eq(true)
product.max_purchase_count = 1
expect(product.valid?).to eq(false)
end
it "does not make the record invalid when inventory sold is greater" do
# While this situation should never happen, it's still possible.
# Ensuring the record stays valid allows the creator to still change other columns.
product = create(:product)
create_list(:purchase, 2, link: product)
product.update_column(:max_purchase_count, 1)
expect(product.reload.valid?).to eq(true)
end
it "allows it to be set on new records with no purchases" do
expect(build(:product, max_purchase_count: 100).valid?).to eq(true)
end
end
it "allows > $1000 links for verified users" do
expect(build(:product, user: create(:user, verified: true), price_cents: 100_100).valid?).to be(true)
end
describe "price_must_be_within_range validation" do
it "succeeds if prices are within acceptable bounds" do
link = build(:product, price_cents: 1_00)
link2 = build(:product, price_cents: 5000_00)
expect(link).to be_valid
expect(link2).to be_valid
end
it "fails if price is too high" do
link = build(:product, price_cents: 5000_01)
expect(link).not_to be_valid
expect(link.errors.full_messages).to include "Sorry, we don't support pricing products above $5,000."
end
it "fails if price is too low" do
link = build(:product, price_cents: 98)
expect(link).not_to be_valid
expect(link.errors.full_messages).to include "Sorry, a product must be at least $0.99."
end
context "when product has prices in multiple currencies" do
let(:product) { create(:product, price_currency_type: "usd", price_cents: 100) }
it "validates prices for the current currency against correct thresholds when switching currencies" do
usd_price = product.default_price
expect(usd_price.currency).to eq "usd"
expect(usd_price.price_cents).to eq 100
expect do
product.update!(price_currency_type: "inr", price_cents: 5000)
end
.to raise_error(ActiveRecord::RecordInvalid)
.with_message("Validation failed: Sorry, a product must be at least ₹73.")
# The USD 1.00 is lower than the INR 73.00 dollar threshold, but should
# be ignored since it's not the current currency
expect do
product.update!(price_currency_type: "inr", price_cents: 50000)
end
.to_not raise_error(ActiveRecord::RecordInvalid)
end
end
end
describe "native_type inclusion validation" do
it "fails if native_type is nil" do
link = build(:product, native_type: nil)
expect(link).to be_invalid
expect { link.save!(validate: false) }.to raise_error ActiveRecord::NotNullViolation
end
it "succeeds if native_type is in the allowed list" do
link = build(:product, native_type: "digital")
expect(link).to be_valid
end
it "fails if native_type is not in the allowed list" do
link = build(:product, native_type: "invalid")
expect(link).not_to be_valid
expect(link.errors.full_messages).to include("Product type is not included in the list")
end
end
describe "discover_fee_per_thousand inclusion validation" do
let(:product) { build(:product) }
it "succeeds if discover_fee_per_thousand is in the allowed list" do
product.discover_fee_per_thousand = 100
expect(product).to be_valid
product.discover_fee_per_thousand = 300
expect(product).to be_valid
product.discover_fee_per_thousand = 1000
expect(product).to be_valid
product.discover_fee_per_thousand = 400
expect(product).to be_valid
product.discover_fee_per_thousand = 100
expect(product).to be_valid
end
it "fails if discover_fee_per_thousand is not in the allowed list" do
message = "Gumroad fee must be between 30% and 100%"
product.discover_fee_per_thousand = 0
expect(product).not_to be_valid
expect(product.errors.full_messages).to include(message)
product.discover_fee_per_thousand = nil
expect(product).not_to be_valid
expect(product.errors.full_messages).to include(message)
product.discover_fee_per_thousand = -1
expect(product).not_to be_valid
expect(product.errors.full_messages).to include(message)
product.discover_fee_per_thousand = 10
expect(product).not_to be_valid
expect(product.errors.full_messages).to include(message)
product.discover_fee_per_thousand = 1001
expect(product).not_to be_valid
expect(product.errors.full_messages).to include(message)
end
end
describe "alive_category_variants_presence validation" do
describe "for physical products" do
let(:product) { create(:physical_product) }
it "succeeds when the product has no versions" do
expect { product.save! }.to_not raise_error
expect(product).to be_valid
expect(product.errors.any?).to be(false)
end
it "succeeds when the product has non-empty versions" do
category_one = create(:variant_category, link: product)
category_two = create(:variant_category, link: product)
create(:sku, link: product)
create(:variant, variant_category: category_one)
create(:variant, variant_category: category_two)
expect { product.save! }.to_not raise_error
expect(product).to be_valid
expect(product.errors.any?).to be(false)
end
it "fails when the product has empty versions" do
category_one = create(:variant_category, link: product)
create(:variant_category, link: product)
create(:sku, link: product)
create(:variant, variant_category: category_one)
expect { product.save! }.to raise_error(ActiveRecord::RecordInvalid)
expect(product).to_not be_valid
expect(product.errors.full_messages.to_sentence).to eq("Sorry, the product versions must have at least one option.")
end
end
describe "for non-physical products" do
let(:product) { create(:product) }
it "succeeds when the product has no versions" do
expect { product.save! }.to_not raise_error
expect(product).to be_valid
expect(product.errors.any?).to be(false)
end
it "succeeds when the product has non-empty versions" do
category_one = create(:variant_category, link: product)
category_two = create(:variant_category, link: product)
create(:variant, variant_category: category_one)
create(:variant, variant_category: category_two)
expect { product.save! }.to_not raise_error
expect(product).to be_valid
expect(product.errors.any?).to be(false)
end
it "fails when the product has empty versions" do
create(:variant_category, link: product)
category_two = create(:variant_category, link: product)
create(:variant, variant_category: category_two)
expect { product.save! }.to raise_error(ActiveRecord::RecordInvalid)
expect(product).to_not be_valid
expect(product.errors.full_messages.to_sentence).to eq("Sorry, the product versions must have at least one option.")
end
end
end
describe "free trial validation" do
context "when product is recurring billing" do
it "allows free_trial_enabled to be set" do
product = build(:subscription_product, free_trial_enabled: true, free_trial_duration_unit: :week, free_trial_duration_amount: 1)
expect(product).to be_valid
end
it "validates presence of free trial properties if free trial is enabled" do
product = build(:subscription_product, free_trial_enabled: true)
expect(product).not_to be_valid
expect(product.errors.full_messages).to match_array ["Free trial duration unit can't be blank", "Free trial duration amount can't be blank"]
product.free_trial_duration_unit = :week
product.free_trial_duration_amount = 1
expect(product).to be_valid
end
it "skips validating free_trial_duration_amount unless changed" do
product = create(:subscription_product, free_trial_enabled: true, free_trial_duration_unit: :week, free_trial_duration_amount: 1)
product.update_attribute(:free_trial_duration_amount, 2) # skip validations
expect(product).to be_valid
product.free_trial_duration_amount = 3
expect(product).not_to be_valid
end
it "does not validate presence of free trial properties if free trial is disabled" do
product = build(:subscription_product, free_trial_enabled: false)
expect(product).to be_valid
end
it "only allows permitted free trial durations" do
product = build(:subscription_product, free_trial_enabled: true, free_trial_duration_unit: :week, free_trial_duration_amount: 1)
expect(product).to be_valid
product.free_trial_duration_amount = 2
expect(product).not_to be_valid
product.free_trial_duration_amount = 0.5
expect(product).not_to be_valid
end
end
context "when product is not recurring billing" do
it "does not allow free_trial_enabled to be set" do
product = build(:product, free_trial_enabled: true)
expect(product).not_to be_valid
expect(product.errors.full_messages).to include "Free trials are only allowed for subscription products."
end
it "does not allow free trial properties to be set" do
product = build(:product, free_trial_duration_unit: :week, free_trial_duration_amount: 1)
expect(product).not_to be_valid
expect(product.errors.full_messages).to include "Free trials are only allowed for subscription products."
end
end
end
describe "callbacks" do
describe "set_default_discover_fee_per_thousand" do
it "sets the boosted discover fee when user has discover_boost_enabled" do
user = create(:user, discover_boost_enabled: true)
product = build(:product, user: user)
product.save
expect(product.discover_fee_per_thousand).to eq Link::DEFAULT_BOOSTED_DISCOVER_FEE_PER_THOUSAND
end
it "doesn't set the boosted discover fee when user doesn't have discover_boost_enabled" do
user = create(:user)
user.update!(discover_boost_enabled: false)
product = build(:product, user: user)
product.save
expect(product.discover_fee_per_thousand).to eq 100
end
end
describe "initialize_tier_if_needed" do
it "creates a Tier variant category and default tier" do
product = create(:membership_product)
expect(product.tier_category.title).to eq "Tier"
expect(product.tiers.first.name).to eq "Untitled"
end
it "creates a default price for the default tier" do
product = create(:membership_product, price_cents: 600)
prices = product.default_tier.prices
expect(prices.count).to eq 1
expect(prices.first.price_cents).to eq 600
expect(prices.first.recurrence).to eq "monthly"
end
it "creates a price with price_cents 0 for the product" do
product = create(:membership_product, price_cents: 600)
prices = product.prices
expect(prices.count).to eq 1
expect(prices.first.price_cents).to eq 0
expect(prices.first.recurrence).to eq "monthly"
end
it "sets subscription_duration to the default if not set" do
product = build(:membership_product, subscription_duration: nil)
product.save(validate: false) # skip default price validation, which fails
expect(product.subscription_duration).to eq BasePrice::Recurrence::DEFAULT_TIERED_MEMBERSHIP_RECURRENCE
end
describe "single-unit currencies" do
it "sets prices correctly" do
product = create(:membership_product, price_currency_type: "jpy", price_cents: 5000)
tier_price = product.default_tier.prices.first
expect(tier_price.currency).to eq "jpy"
expect(tier_price.price_cents).to eq 5000
end
end
end
describe "reset_moderated_by_iffy_flag" do
let(:product) { create(:product, moderated_by_iffy: true) }
context "when the product is alive" do
it "resets the moderated_by_iffy flag when description changes" do
expect do
product.update!(description: "New description")
end.to change { product.reload.moderated_by_iffy }.from(true).to(false)
end
it "does not reset the moderated_by_iffy flag when other attributes change" do
expect do
product.update!(price_cents: 1000)
end.not_to change { product.reload.moderated_by_iffy }
end
end
end
describe "queue_iffy_ingest_job_if_unpublished_by_admin" do
let(:product) { create(:product) }
it "enqueues an Iffy::Product::IngestJob when the product has changed and was already unpublished by admin" do
product.update!(is_unpublished_by_admin: true)
product.update!(description: "New description")
expect(Iffy::Product::IngestJob).to have_enqueued_sidekiq_job(product.id)
end
it "does not enqueue an Iffy::Product::IngestJob when the product is only unpublished by admin" do
expect do
product.unpublish!(is_unpublished_by_admin: true)
end.not_to change { Iffy::Product::IngestJob.jobs.size }
end
it "does not enqueue an Iffy::Product::IngestJob when the product is not unpublished by admin" do
expect do
product.update!(description: "New description")
end.not_to change { Iffy::Product::IngestJob.jobs.size }
end
end
describe "initialize_suggested_amount_if_needed!" do
let(:seller) { create(:user, :eligible_for_service_products) }
let(:product) { build(:product, user: seller, price_cents: 200) }
context "native type is not a coffee" do
it "does nothing" do
product.save
expect(product.price_cents).to eq(200)
expect(product.variant_categories_alive).to be_empty
expect(product.alive_variants).to be_empty
expect(product.customizable_price).to be_nil
end
end
context "native type is a coffee" do
before { product.native_type = Link::NATIVE_TYPE_COFFEE }
it "creates a suggested amount variant category and variant and resets the base price" do
product.save!
product.reload
expect(product.price_cents).to eq(0)
expect(product.variant_categories_alive.first.title).to eq("Suggested Amounts")
expect(product.alive_variants.first.name).to eq("")
expect(product.alive_variants.first.price_difference_cents).to eq(200)
expect(product.customizable_price).to eq(true)
end
end
end
describe "initialize_call_limitation_info_if_needed!" do
let(:seller) { create(:user, :eligible_for_service_products) }
let(:product) { build(:product, user: seller, price_cents: 200) }
context "native type is not call" do
it "does not create a call limitations record" do
product.save
expect(product.call_limitation_info).to be_nil
end
end
context "native type is call" do
before { product.native_type = Link::NATIVE_TYPE_CALL }
it "creates a call limitations record" do
product.save!
call_limitation_info = product.call_limitation_info
expect(call_limitation_info.minimum_notice_in_minutes).to eq(CallLimitationInfo::DEFAULT_MINIMUM_NOTICE_IN_MINUTES)
expect(call_limitation_info.maximum_calls_per_day).to be_nil
end
end
end
describe "initialize_duration_variant_category_for_calls!" do
context "native type is call" do
let(:call) { create(:call_product) }
it "creates a duration variant category" do
expect(call.variant_categories.count).to eq(1)
expect(call.variant_categories.first.title).to eq("Duration")
end
end
context "native type is not call" do
let(:product) { create(:physical_product) }
it "does not create a duration variant category" do
expect(product.variant_categories.count).to eq(0)
end
end
end
describe "delete_unused_prices" do
let!(:product) { create(:product, purchase_type: :buy_and_rent, price_cents: 500, rental_price_cents: 100) }
let(:buy_price) { product.prices.is_buy.first }
let(:rental_price) { product.prices.is_rental.first }
context "when switching to a buy_only product" do
it "deletes any rental prices" do
expect do
product.update!(purchase_type: :buy_only)
end.to change { product.prices.alive.count }.from(2).to(1)
.and change { product.prices.alive.is_rental.count }.from(1).to(0)
expect(rental_price).to be_deleted
end
end
context "when switching to a rent_only product" do
it "deletes any buy prices" do
expect do
product.update!(purchase_type: :rent_only)
end.to change { product.prices.alive.count }.from(2).to(1)
.and change { product.prices.alive.is_buy.count }.from(1).to(0)
expect(buy_price).to be_deleted
end
end
context "when switching to a buy_and_rent product" do
it "does nothing" do
buy_product = create(:product, purchase_type: :buy_only)
expect do
buy_product.update!(purchase_type: :buy_and_rent)
end.not_to change { buy_product.prices.alive.count }
rental_product = create(:product, purchase_type: :rent_only, rental_price_cents: 100)
expect do
rental_product.update!(purchase_type: :buy_and_rent)
end.not_to change { rental_product.prices.alive.count }
end
end
context "when leaving purchase_type unchanged" do
it "does not run the callback" do
expect(product).not_to receive(:delete_unused_prices)
product.update!(purchase_type: :buy_and_rent)
end
end
end
describe "adding to profile sections" do
it "adds newly created products to all sections that have add_new_products set" do
seller = create(:user)
default_sections = create_list(:seller_profile_products_section, 2, seller:)
other_sections = create_list(:seller_profile_products_section, 2, seller:, add_new_products: false)
link = create(:product, user: seller)
default_sections.each do |section|
expect(section.reload.shown_products).to include link.id
end
other_sections.each do |section|
expect(section.reload.shown_products).to_not include link.id
end
end
end
end
describe "associations" do
it { is_expected.to have_many(:self_service_affiliate_products).with_foreign_key(:product_id) }
describe "#confirmed_collaborators" do
it "returns all confirmed collaborators" do
product = create(:product)
# Those who have not accepted the invitation are not included,
# regardless of self-deleted status.
create(:collaborator, :with_pending_invitation, products: [product], deleted_at: 1.minute.ago)
collaborator = create(:collaborator, :with_pending_invitation, products: [product])
expect(product.confirmed_collaborators).to be_empty
# Those who have accepted the invitation are included...
collaborator.collaborator_invitation.destroy!
expect(product.confirmed_collaborators).to contain_exactly(collaborator)
# ...regardless of self-deleted status.
collaborator.mark_deleted!
expect(product.confirmed_collaborators).to contain_exactly(collaborator)
end
end
describe "#collaborator" do
it "returns the live collaborator" do
product = create(:product)
create(:collaborator, products: [product], deleted_at: 1.minute.ago)
collaborator = create(:collaborator, products: [product])
expect(product.collaborator).to eq collaborator
end
end
describe "#collaborator_for_display" do
it "returns the collaborating user if they should be shown as a co-creator" do
product = create(:product)
collaborator = create(:collaborator)
expect(product.collaborator_for_display).to eq nil
collaborator.products = [product]
allow_any_instance_of(Collaborator).to receive(:show_as_co_creator_for_product?).and_return(true)
expect(product.collaborator_for_display).to eq collaborator.affiliate_user
allow_any_instance_of(Collaborator).to receive(:show_as_co_creator_for_product?).and_return(false)
expect(product.collaborator_for_display).to eq nil
end
end
describe "#current_base_variants" do
it "returns variants and SKUs that have not been deleted and whose variant category has not been deleted" do
product = create(:physical_product)
# live category with 1 live variant, 1 deleted variant
size_category = create(:variant_category, link: product, title: "Size")
small_variant = create(:variant, variant_category: size_category, name: "Small")
create(:variant, variant_category: size_category, name: "Large", deleted_at: Time.current)
# deleted category with 1 live variant, 1 deleted variant
color_category = create(:variant_category, link: product, title: "Color", deleted_at: Time.current)
create(:variant, variant_category: color_category, name: "Red")
create(:variant, variant_category: color_category, name: "Blue", deleted_at: Time.current)
# 2 live SKUs, 1 deleted SKU
default_sku = product.skus.is_default_sku.first
live_sku = create(:sku, link: product, name: "Small-Red")
create(:sku, link: product, name: "Large-Blue", deleted_at: Time.current)
expect(product.current_base_variants).to match_array [small_variant, live_sku, default_sku]
end
end
describe "#public_files" do
it "returns all public files associated with the product" do
product = create(:product)
public_file = create(:public_file, resource: product)
deleted_public_file = create(:public_file, resource: product, deleted_at: Time.current)
_another_product_public_file = create(:public_file)
expect(product.public_files).to eq([public_file, deleted_public_file])
end
end
describe "#alive_public_files" do
it "returns all alive public files associated with the product" do
product = create(:product)
public_file = create(:public_file, resource: product)
_deleted_public_file = create(:public_file, resource: product, deleted_at: Time.current)
_another_product_public_file = create(:public_file)
expect(product.alive_public_files).to eq([public_file])
end
end
describe "#communities" do
it "returns all communities associated with the product" do
product = create(:product)
communities = [
create(:community, resource: product, deleted_at: 1.minute.ago),
create(:community, resource: product),
]
expect(product.communities).to match_array(communities)
end
end
describe "#active_community" do
it "returns the live community" do
product = create(:product)
create(:community, resource: product, deleted_at: 1.minute.ago)
community = create(:community, resource: product)
expect(product.active_community).to eq(community)
end
end
end
describe "scopes" do
let(:user) { create(:user) }
describe "alive" do
before do
create(:product, user:, name: "alive")
create(:product, user:, purchase_disabled_at: Time.current)
create(:product, user:, deleted_at: Time.current)
create(:product, user:, banned_at: Time.current)
end
it "returns the correct products do" do
expect(user.links.alive.count).to eq 1
expect(user.links.alive.first.name).to eq "alive"
end
end
describe "visible" do
let!(:deleted_product) { create(:product, user:, deleted_at: Time.current) }
let!(:product) { create(:product, user:) }
let!(:archived_product) { create(:product, user:, archived: true) }
it "returns the correct products" do
expect(user.links.visible.count).to eq 2
expect(user.links.visible).to eq [product, archived_product]
end
end
describe "visible_and_not_archived" do
let!(:deleted_product) { create(:product, user:, deleted_at: Time.current) }
let!(:product) { create(:product, user:) }
let!(:archived_product) { create(:product, user:, archived: true) }
it "returns the correct products" do
expect(user.links.visible_and_not_archived.count).to eq 1
expect(user.links.visible_and_not_archived).to eq [product]
end
end
describe "by_general_permalink" do
before do
@product_1 = create(:product, unique_permalink: "xxx")
@product_2 = create(:product, unique_permalink: "yyy", custom_permalink: "custom")
@product_3 = create(:product, unique_permalink: "zzz", custom_permalink: "awesome")
end
it "matches products by unique permalink" do
expect(Link.by_general_permalink("xxx")).to match_array([@product_1])
end
it "matches products by custom permalink" do
expect(Link.by_general_permalink("custom")).to match_array([@product_2])
end
it "does not match products if empty permalink is passed" do
# Making sure this does not match products without a custom permalink
expect(Link.by_general_permalink(nil)).to be_empty
expect(Link.by_general_permalink("")).to be_empty
end
end
describe "by_unique_permalinks" do
before do
@product_1 = create(:product, unique_permalink: "xxx")
@product_2 = create(:product, unique_permalink: "yyy", custom_permalink: "custom")
@product_3 = create(:product, unique_permalink: "zzz", custom_permalink: "awesome")
end
it "matches products by unique permalink" do
expect(Link.by_unique_permalinks(["xxx", "yyy"])).to match_array([@product_1, @product_2])
end
it "does not match products by custom permalink" do
expect(Link.by_unique_permalinks(["awesome", "custom"])).to be_empty
end
it "returns matched products and ignores permalinks that did not match" do
expect(Link.by_unique_permalinks(["xxx", "custom"])).to match_array([@product_1])
end
it "does not match any products if no permalinks are provided" do
expect(Link.by_unique_permalinks([])).to be_empty
end
end
describe "unpublished" do
before do
create(:product, user:)
create(:product, user:, purchase_disabled_at: Time.current, name: "unpublished")
end
it "returns the correct products do" do
expect(user.links.where.not(purchase_disabled_at: nil).count).to eq 1
expect(user.links.where.not(purchase_disabled_at: nil).first.name).to eq "unpublished"
end
end
describe "publish!" do
before do
@user = create(:user)
@merchant_account = create(:merchant_account_stripe, user: @user)
@product = create(:product_with_pdf_file, purchase_disabled_at: Time.current, user: @user)
end
it "publishes the product" do
expect do
@product.publish!
end.to change { @product.reload.purchase_disabled_at }.to(nil)
end
context "when the user has not confirmed their email address" do
before do
@user.update!(confirmed_at: nil)
end
it "raises a Link::LinkInvalid error" do
expect do
@product.publish!
end.to raise_error(Link::LinkInvalid)
expect(@product.reload.purchase_disabled_at).to_not be(nil)
expect(@product.errors.full_messages.to_sentence).to eq("You have to confirm your email address before you can do that.")
end
end
context "when a bundle has no alive products" do
before do
@product.update!(is_bundle: true)
create(:bundle_product, bundle: @product, product: create(:product, user: @user), deleted_at: Time.current)
end
it "raises a Link::LinkInvalid error" do
expect do
@product.publish!
end.to raise_error(ActiveRecord::RecordInvalid)
expect(@product.reload.purchase_disabled_at).to_not be(nil)
expect(@product.errors.full_messages.to_sentence).to eq("Bundles must have at least one product.")
end
end
context "when the seller has universal affiliates" do
it "associates those affiliates with the product and notifies them" do
direct_affiliate = create(:direct_affiliate, seller: @user, apply_to_all_products: true)
expect do
@product.publish!
end.to have_enqueued_mail(AffiliateMailer, :notify_direct_affiliate_of_new_product).with(direct_affiliate.id, @product.id)
expect(@product.reload.direct_affiliates).to match_array [direct_affiliate]
expect(direct_affiliate.reload.products).to match_array [@product]
end
context "who are already associated with the product" do
it "does not add or notify them" do
direct_affiliate = create(:direct_affiliate, seller: @user, apply_to_all_products: true, products: [@product])
expect do
@product.publish!
end.to_not have_enqueued_mail(AffiliateMailer, :notify_direct_affiliate_of_new_product).with(direct_affiliate.id, @product.id)
expect(@product.reload.direct_affiliates).to match_array [direct_affiliate]
expect(direct_affiliate.reload.products).to match_array [@product]
end
end
context "when affiliate has been removed" do
it "does not add or notify them" do
direct_affiliate = create(:direct_affiliate, seller: @user, apply_to_all_products: true)
direct_affiliate.mark_deleted!
expect do
@product.publish!
end.to_not have_enqueued_mail(AffiliateMailer, :notify_direct_affiliate_of_new_product).with(direct_affiliate.id, @product.id)
expect(@product.reload.direct_affiliates).to be_empty
expect(direct_affiliate.reload.products).to be_empty
end
end
end
context "video transcoding" do
before do
@video_link = create(:product, draft: true, user: @user)
allow(@user).to receive(:auto_transcode_videos?).and_return(true)
end
it "doesn't transcode video when the link is draft" do
video_file = create(:product_file, link_id: @video_link.id, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4")
expect(TranscodeVideoForStreamingWorker).not_to have_enqueued_sidekiq_job(video_file.id, video_file.class.name)
end
it "transcodes video files on publishing the product only if `queue_for_transcoding?` is true for the product file" do
video_file_1 = create(:product_file, link_id: @video_link.id, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4")
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/installment_event_spec.rb | spec/models/installment_event_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe InstallmentEvent do
context "Creation" do
it "queues update of Installment's installment_events_count" do
installment_event = create(:installment_event)
expect(UpdateInstallmentEventsCountCacheWorker).to have_enqueued_sidekiq_job(installment_event.installment_id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/uruguay_bank_account_spec.rb | spec/models/uruguay_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UruguayBankAccount do
describe "#bank_account_type" do
it "returns UY" do
expect(create(:uruguay_bank_account).bank_account_type).to eq("UY")
end
end
describe "#country" do
it "returns UY" do
expect(create(:uruguay_bank_account).country).to eq("UY")
end
end
describe "#currency" do
it "returns uyu" do
expect(create(:uruguay_bank_account).currency).to eq(Currency::UYU)
end
end
describe "#bank_code" do
it "returns valid for 3 digits" do
expect(build(:uruguay_bank_account, bank_number: "123")).to be_valid
expect(build(:uruguay_bank_account, bank_number: "12")).not_to be_valid
expect(build(:uruguay_bank_account, bank_number: "1234")).not_to be_valid
expect(build(:uruguay_bank_account, bank_number: "abc")).not_to be_valid
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:uruguay_bank_account).account_number_visual).to eq("******6789")
end
end
describe "#validate_account_number" do
it "allows 1 to 18 digits" do
expect(build(:uruguay_bank_account, account_number: "1")).to be_valid
expect(build(:uruguay_bank_account, account_number: "123456789101")).to be_valid
expect(build(:uruguay_bank_account, account_number: "1234567891011")).not_to be_valid
expect(build(:uruguay_bank_account, account_number: "abc")).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/cambodia_bank_account_spec.rb | spec/models/cambodia_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CambodiaBankAccount do
describe "#bank_account_type" do
it "returns KH" do
expect(create(:cambodia_bank_account).bank_account_type).to eq("KH")
end
end
describe "#country" do
it "returns KH" do
expect(create(:cambodia_bank_account).country).to eq("KH")
end
end
describe "#currency" do
it "returns khr" do
expect(create(:cambodia_bank_account).currency).to eq("khr")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:cambodia_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAAKHKHXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
bank_account = create(:cambodia_bank_account, account_number: "000123456789", account_number_last_four: "6789")
expect(bank_account.account_number_visual).to eq("******6789")
end
end
describe "#validate_bank_code" do
it "allows 8 to 11 characters only" do
expect(build(:cambodia_bank_account, bank_code: "AAAAKHKHXXX")).to be_valid
expect(build(:cambodia_bank_account, bank_code: "AAAAKHKH")).to be_valid
expect(build(:cambodia_bank_account, bank_code: "AAAAKHKHXXXX")).not_to be_valid
expect(build(:cambodia_bank_account, bank_code: "AAAAKHK")).not_to be_valid
end
end
describe "#validate_account_number" do
let(:bank_account) { build(:cambodia_bank_account) }
it "validates account number format" do
bank_account.account_number = "000123456789"
bank_account.account_number_last_four = "6789"
expect(bank_account).to be_valid
bank_account.account_number = "00012"
bank_account.account_number_last_four = "0012"
expect(bank_account).to be_valid
bank_account.account_number = "1234"
bank_account.account_number_last_four = "1234"
expect(bank_account).not_to be_valid
bank_account.account_number = "1234567890123456"
bank_account.account_number_last_four = "3456"
expect(bank_account).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/refund_spec.rb | spec/models/refund_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Refund do
it "validates that processor_refund_id is unique" do
create(:refund, processor_refund_id: "ref_id")
new_ref = build(:refund, processor_refund_id: "ref_id")
expect(new_ref.valid?).to_not be(true)
end
describe "flags" do
it "has an `is_for_fraud` flag" do
flag_on = create(:refund, is_for_fraud: true)
flag_off = create(:refund, is_for_fraud: false)
expect(flag_on.is_for_fraud).to be true
expect(flag_off.is_for_fraud).to be false
end
end
it "sets the product and the seller of the purchase" do
refund = create(:refund)
expect(refund.product).to eq(refund.purchase.link)
expect(refund.seller).to eq(refund.purchase.seller)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/follower_spec.rb | spec/models/follower_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/deletable_concern"
RSpec.describe Follower do
it_behaves_like "Deletable concern", :follower
let(:active_follower) { create(:active_follower) }
let(:deleted_follower) { create(:deleted_follower) }
let(:unconfirmed_follower) { create(:follower) }
describe ".unsubscribe" do
it "marks follower as deleted" do
follower = create(:active_follower)
Follower.unsubscribe(follower.followed_id, follower.email)
expect(follower.reload).to be_deleted
end
end
describe "scopes" do
before do
active_follower
deleted_follower
unconfirmed_follower
end
describe ".confirmed" do
it "returns only confirmed followers" do
expect(Follower.confirmed).to contain_exactly(active_follower)
end
end
describe ".active" do
it "returns only confirmed and alive followers" do
expect(Follower.active).to match_array(active_follower)
end
end
end
describe "uniqueness" do
before do
@follower = create(:follower)
end
it "is not valid with same followed_id and email" do
expect(Follower.new(email: @follower.email, followed_id: @follower.followed_id)).to_not be_valid
end
it "is not saved to the database with the same followed_id and email" do
follower = Follower.new(email: @follower.email)
follower.followed_id = @follower.followed_id
expect { follower.save!(validate: false) }.to raise_error(ActiveRecord::RecordNotUnique)
end
end
describe "invalid email" do
it "is not valid with space in the email" do
expect(Follower.new(email: "sahil lavingia@gmail.com")).to_not be_valid
end
end
describe "#mark_undeleted!" do
it "does nothing when follower is not deleted" do
expect(active_follower).to_not receive(:send_confirmation_email)
active_follower.mark_undeleted!
expect(active_follower).not_to be_deleted
end
it "undeletes a follower" do
expect do
deleted_follower.mark_undeleted!
end.to change { deleted_follower.deleted? }.from(true).to(false)
end
end
describe "#mark_deleted!" do
it do
follower = create(:follower)
follower.mark_deleted!
follower.reload
expect(follower).to be_deleted
expect(follower).not_to be_confirmed
end
end
describe "#confirm!" do
it "does nothing when follower is confirmed" do
active_follower
expect(active_follower).to_not receive(:send_confirmation_email)
active_follower.confirm!
expect(active_follower).to be_confirmed
end
it "sets confirmed_at to time when follower is not confirmed" do
time = Time.current
allow(Time).to receive(:current).and_return(time)
user = create(:user)
unconfirmed_follower = create(:follower, id: 99, user:)
unconfirmed_follower.confirm!
expect(unconfirmed_follower.confirmed_at.to_s).to eq(time.utc.to_s)
end
it "removes deleted_at" do
deleted_follower.confirm!
expect(deleted_follower.deleted_at).to eq(nil)
end
end
describe "#confirmed?" do
it "returns if follower has confirmed following or not" do
expect(active_follower.confirmed?).to eq(true)
expect(unconfirmed_follower.confirmed?).to eq(false)
end
end
describe "#unconfirmed?" do
it "returns if follower has unconfirmed following or not" do
expect(active_follower.unconfirmed?).to eq(false)
expect(unconfirmed_follower.unconfirmed?).to eq(true)
end
end
describe "validations" do
before do
@follower = create(:follower)
end
it "checks for valid entry in table User exists by (and only) id for follower" do
follower_user = create(:user)
@follower.follower_user_id = follower_user.id * 2
expect(@follower.valid?).to be(false)
@follower.follower_user_id = follower_user.id
@follower.email = follower_user.email + "dummy"
expect(@follower.valid?).to be(true)
@follower.follower_user_id = nil
expect(@follower.valid?).to be(true)
end
it "prevents records to be saved as both confirmed and deleted" do
@follower.confirmed_at = Time.current
@follower.deleted_at = Time.current
expect(@follower.valid?).to eq(false)
end
end
describe "get_email" do
before do
@follower_user = create(:user)
@follower = create(:follower, follower_user_id: @follower_user.id)
end
it "fetches email from the user table if follower user id exists" do
expect(@follower.follower_user_id).to_not be(nil)
expect(@follower.follower_email).to eq(@follower_user.email)
end
it "fetches email from the followers record if follower_user_id does not exist" do
@follower.follower_user_id = nil
@follower.save!
expect(@follower.follower_email).to eq(@follower.email)
expect(@follower.email).to_not eq(@follower_user.email)
end
it "fetches email from the followers record if follower_user_id exists but the user has a blank email" do
@follower_user.update_column(:email, "")
expect(@follower.follower_email).to eq(@follower.email)
expect(@follower.email).to_not eq(@follower_user.email)
end
it "has the right error message for duplicate followers" do
duplicate_follower = Follower.new(user: @follower.user, email: @follower.email)
duplicate_follower.save
expect(duplicate_follower.errors.full_messages.to_sentence).to eq "You are already following this creator."
end
end
describe "schedule_workflow_jobs" do
before do
@seller = create(:user)
@product = create(:product, user: @seller)
@follower_workflow = create(:workflow, seller: @seller, link: nil, workflow_type: Workflow::FOLLOWER_TYPE, published_at: 1.week.ago)
@seller_workflow = create(:workflow, seller: @seller, link: nil, workflow_type: Workflow::SELLER_TYPE, published_at: 1.week.ago)
@installment1 = create(:installment, workflow: @follower_workflow)
@installment_rule1 = create(:installment_rule, installment: @installment1, delayed_delivery_time: 3.days)
@installment2 = create(:installment, workflow: @follower_workflow)
@installment_rule2 = create(:installment_rule, installment: @installment2, delayed_delivery_time: 3.days)
@seller_installment = create(:installment, workflow: @seller_workflow)
@seller_installment_rule = create(:installment_rule, installment: @seller_installment, delayed_delivery_time: 1.day)
end
it "enqueues 2 installment jobs when follower confirms" do
follower = Follower.create!(user: @seller, email: "email@test.com")
follower.confirm!
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(2)
end
it "doesn't enqueue installment jobs when follower doesn't confirm" do
user = create(:user)
Follower.create!(user:, email: "email@test.com")
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(0)
end
it "doesn't enqueue installment jobs when workflow is marked as member_cancellation and a follower confirms" do
@follower_workflow.update!(workflow_trigger: "member_cancellation")
follower = Follower.create!(user: @seller, email: "email@test.com")
follower.confirm!
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(0)
end
end
describe "#send_confirmation_email" do
context "when confirmation emails are sent repeatedly" do
it "suppresses repeated sending of confirmation emails" do
unconfirmed_follower
# Erase the information about the first confirmation email
Rails.cache.clear
expect do
unconfirmed_follower.send_confirmation_email
end.to have_enqueued_mail(FollowerMailer, :confirm_follower).with(unconfirmed_follower.followed_id, unconfirmed_follower.id)
# Try sending again
expect do
unconfirmed_follower.send_confirmation_email
end.not_to have_enqueued_mail(FollowerMailer, :confirm_follower).with(unconfirmed_follower.followed_id, unconfirmed_follower.id)
end
end
end
context "AudienceMember callbacks" do
describe "#should_be_audience_member?" do
it "only returns true for expected cases" do
expect(create(:follower).should_be_audience_member?).to eq(false)
expect(create(:active_follower).should_be_audience_member?).to eq(true)
expect(create(:deleted_follower).should_be_audience_member?).to eq(false)
follower = create(:active_follower)
follower.update_column(:email, nil)
expect(follower.should_be_audience_member?).to eq(false)
follower.update_column(:email, "some-invalid-email")
expect(follower.should_be_audience_member?).to eq(false)
end
end
it "adds follower to audience when confirmed" do
follower = create(:follower)
expect do
follower.confirm!
end.to change(AudienceMember, :count).by(1)
member = AudienceMember.find_by(email: follower.email, seller: follower.user)
expect(member.details["follower"]).to eq({ "id" => follower.id, "created_at" => follower.created_at.iso8601 })
end
it "removes follower from audience when marked as deleted" do
follower = create(:active_follower)
create(:purchase, :from_seller, seller: follower.user, email: follower.email)
expect do
follower.mark_deleted!
end.not_to change(AudienceMember, :count)
member = AudienceMember.find_by(email: follower.email, seller: follower.user)
expect(member.details["follower"]).to be_nil
expect(member.details["purchases"]).to be_present
end
it "removes audience member when marked as deleted with no other audience types" do
follower = create(:active_follower)
expect do
follower.mark_deleted!
end.to change(AudienceMember, :count).by(-1)
member = AudienceMember.find_by(email: follower.email, seller: follower.user)
expect(member).to be_nil
end
it "recreates audience member when changing email" do
follower = create(:active_follower)
old_email = follower.email
new_email = "new@example.com"
follower.update!(email: new_email)
old_member = AudienceMember.find_by(email: old_email, seller: follower.user)
new_member = AudienceMember.find_by(email: new_email, seller: follower.user)
expect(old_member).to be_nil
expect(new_member).to be_present
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/seller_profile_rich_text_section_spec.rb | spec/models/seller_profile_rich_text_section_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SellerProfileRichTextSection do
describe "validations" do
it "validates json_data with the correct schema" do
section = build(:seller_profile_rich_text_section)
section.json_data["garbage"] = "should not be here"
schema = JSON.parse(File.read(Rails.root.join("lib", "json_schemas", "seller_profile_rich_text_section.json").to_s))
expect(JSON::Validator).to receive(:new).with(schema, insert_defaults: true, record_errors: true).and_wrap_original do |original, *args|
validator = original.call(*args)
expect(validator).to receive(:validate).with(section.json_data).and_call_original
validator
end
section.validate
expect(section.errors.full_messages.to_sentence).to eq("The property '#/' contains additional properties [\"garbage\"] outside of the schema when none are allowed")
end
end
it "limits the size of the text object" do
section = build(:seller_profile_rich_text_section, text: { text: "a" * 500000 })
expect(section).to_not be_valid
expect(section.errors.full_messages.to_sentence).to eq "Text is too large"
end
describe "iffy ingest" do
it "triggers iffy ingest when json_data changes" do
section = create(:seller_profile_rich_text_section)
expect do
section.update!(json_data: {
text: {
content: [
{ type: "paragraph", content: [{ text: "Rich content text" }] },
{ type: "image", attrs: { src: "https://example.com/image1.jpg" } },
{ type: "image", attrs: { src: "https://example.com/image2.jpg" } }
]
}
})
end.to change { Iffy::Profile::IngestJob.jobs.size }.by(1)
end
it "triggers iffy ingest when header changes" do
section = create(:seller_profile_rich_text_section)
expect do
section.update!(header: "New Header")
end.to change { Iffy::Profile::IngestJob.jobs.size }.by(1)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/bosnia_and_herzegovina_bank_account_spec.rb | spec/models/bosnia_and_herzegovina_bank_account_spec.rb | # frozen_string_literal: true
describe BosniaAndHerzegovinaBankAccount do
describe "#bank_account_type" do
it "returns BA" do
expect(create(:bosnia_and_herzegovina_bank_account).bank_account_type).to eq("BA")
end
end
describe "#country" do
it "returns BA" do
expect(create(:bosnia_and_herzegovina_bank_account).country).to eq("BA")
end
end
describe "#currency" do
it "returns bam" do
expect(create(:bosnia_and_herzegovina_bank_account).currency).to eq("bam")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:bosnia_and_herzegovina_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAABABAXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:bosnia_and_herzegovina_bank_account, account_number_last_four: "6000").account_number_visual).to eq("BA******6000")
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_request_spec.rb | spec/models/affiliate_request_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe AffiliateRequest do
describe "validations" do
subject(:affiliate_request) { build(:affiliate_request) }
it "validates without any error" do
expect(affiliate_request).to be_valid
end
describe "presence" do
subject(:affiliate_request) { described_class.new }
it "validates presence of attributes" do
expect(affiliate_request).to be_invalid
expect(affiliate_request.errors.messages).to eq(
seller: ["can't be blank"],
name: ["can't be blank"],
email: ["can't be blank", "is invalid"],
promotion_text: ["can't be blank"]
)
end
end
describe "name length" do
it "validates length of name" do
affiliate_request.name = Faker::String.random(length: 101)
expect(affiliate_request).to be_invalid
expect(affiliate_request.errors.messages).to eq(
name: ["Your name is too long. Please try again with a shorter one."],
)
end
end
describe "email format" do
it "validates email format" do
affiliate_request.email = "invalid-email"
expect(affiliate_request).to be_invalid
expect(affiliate_request.errors.full_messages.first).to eq("Email is invalid")
end
end
describe "duplicate_request_validation" do
let(:existing_affiliate_request) { create(:affiliate_request, email: "requester@example.com") }
let(:duplicate_affiliate_request) { build(:affiliate_request, seller: existing_affiliate_request.seller, email: "requester@example.com") }
context "when requester's previous request is unattended" do
it "doesn't allow new request from the same requester" do
expect(duplicate_affiliate_request).to be_invalid
expect(duplicate_affiliate_request.errors.full_messages.first).to eq("You have already requested to become an affiliate of this creator.")
end
end
context "when requester's previous request is approved" do
let(:existing_affiliate_request) { create(:affiliate_request, email: "requester@example.com", state: :approved) }
it "doesn't allow new request from the same requester" do
expect(duplicate_affiliate_request).to be_invalid
expect(duplicate_affiliate_request.errors.full_messages.first).to eq("You have already requested to become an affiliate of this creator.")
end
end
context "when requester's previous request is ignored" do
let(:existing_affiliate_request) { create(:affiliate_request, email: "requester@example.com", state: :ignored) }
it "allows new request from the same requester" do
expect(duplicate_affiliate_request).to be_valid
end
end
end
describe "requester_is_not_seller" do
let(:creator) { create(:user) }
subject(:affiliate_request) { build(:affiliate_request, seller: creator, email: creator.email) }
it "doesn't allow the creator to become an affiliate of oneself" do
expect(affiliate_request).to be_invalid
expect(affiliate_request.errors.full_messages.first).to eq("You cannot request to become an affiliate of yourself.")
end
end
end
describe "scopes" do
describe "unattended_or_approved_but_awaiting_requester_to_sign_up" do
let!(:unattended_request_one) { create(:affiliate_request) }
let!(:unattended_request_two) { create(:affiliate_request) }
let!(:ignored_request) { create(:affiliate_request, state: "ignored") }
let!(:approved_request_of_signed_up_requester) { create(:affiliate_request, state: "approved", email: create(:user).email) }
let!(:approved_request_of_not_signed_up_requester) { create(:affiliate_request, state: "approved") }
it "returns both unattended requests and approved requests whose requester hasn't signed up yet" do
result = described_class.unattended_or_approved_but_awaiting_requester_to_sign_up
expect(result.size).to eq(3)
expect(result).to match_array([unattended_request_one, unattended_request_two, approved_request_of_not_signed_up_requester])
end
end
end
describe "#as_json" do
it "returns JSON representation" do
seller = create(:user, timezone: "Mumbai")
travel_to DateTime.new(2021, 01, 15).in_time_zone(seller.timezone) do
affiliate_request = create(:affiliate_request, seller:)
expect(affiliate_request.as_json).to eq(
id: affiliate_request.external_id,
name: affiliate_request.name,
email: affiliate_request.email,
promotion: affiliate_request.promotion_text,
date: "2021-01-15T05:30:00+05:30",
state: "created",
can_update: false
)
end
end
end
describe "#to_param" do
subject(:affiliate_request) { create(:affiliate_request) }
it "uses 'external_id' instead of 'id' for constructing URLs to the objects of this model" do
expect(affiliate_request.to_param).to eq(affiliate_request.external_id)
end
end
describe "#can_perform_action?" do
let(:affiliate_request) { create(:affiliate_request) }
context "when action is 'approve'" do
let(:action) { AffiliateRequest::ACTION_APPROVE }
context "when request is already attended" do
before do
affiliate_request.approve!
end
it "returns false" do
expect(affiliate_request.can_perform_action?(action)).to eq(false)
end
end
context "when request is not attended" do
it "returns true" do
expect(affiliate_request.can_perform_action?(action)).to eq(true)
end
end
end
context "when action is 'ignore'" do
let(:action) { AffiliateRequest::ACTION_IGNORE }
context "when request is already approved" do
before do
affiliate_request.approve!
end
it "returns true when the affiliate doesn't have an account" do
expect(affiliate_request.can_perform_action?(action)).to eq(true)
end
it "returns false when the affiliate has an account" do
create(:user, email: affiliate_request.email)
expect(affiliate_request.can_perform_action?(action)).to eq(false)
end
end
context "when request is already ignored" do
before do
affiliate_request.ignore!
end
it "returns false" do
expect(affiliate_request.can_perform_action?(action)).to eq(false)
end
end
context "when request is not attended" do
it "returns true" do
expect(affiliate_request.can_perform_action?(action)).to eq(true)
end
end
end
end
describe "#approve!" do
subject(:affiliate_request) { create(:affiliate_request) }
it "marks the request as approved and makes the requester an affiliate" do
expect(affiliate_request).to receive(:make_requester_an_affiliate!)
expect do
affiliate_request.approve!
end.to change { affiliate_request.reload.approved? }.from(false).to(true)
end
it "schedules workflow posts for the newly approved affiliate" do
creator = create(:user)
affiliate_user = create(:user)
published_product_one = create(:product, user: creator)
create(:self_service_affiliate_product, enabled: true, seller: creator, product: published_product_one, affiliate_basis_points: 1000)
affiliate_request = create(:affiliate_request, seller: creator, email: affiliate_user.email)
affiliate_workflow = create(:workflow, seller: creator, link: nil, workflow_type: Workflow::AFFILIATE_TYPE, published_at: 1.week.ago)
installment1 = create(:installment, workflow: affiliate_workflow)
create(:installment_rule, installment: installment1, delayed_delivery_time: 3.days)
installment2 = create(:installment, workflow: affiliate_workflow)
create(:installment_rule, installment: installment2, delayed_delivery_time: 10.days)
expect_any_instance_of(DirectAffiliate).to receive(:schedule_workflow_jobs).and_call_original
expect do
expect do
affiliate_request.approve!
end.to change { affiliate_request.reload.approved? }.from(false).to(true)
end.to change { DirectAffiliate.count }.by(1)
expect(SendWorkflowInstallmentWorker.jobs.size).to eq(2)
end
end
describe "#ignore!" do
let(:affiliate_request) { create(:affiliate_request) }
context "when request is already ignored" do
before do
affiliate_request.ignore!
end
it "does not allow to ignore again" do
expect do
affiliate_request.ignore!
end.to raise_error(StateMachines::InvalidTransition)
end
end
context "when request is already approved" do
before do
affiliate_request.approve!
end
it "ignores the request when the affiliate doesn't have an account" do
expect do
affiliate_request.ignore!
end.to change { affiliate_request.reload.ignored? }.from(false).to(true)
end
it "notifies the requester of the ignored request" do
expect do
affiliate_request.ignore!
end.to have_enqueued_mail(AffiliateRequestMailer, :notify_requester_of_ignored_request).with(affiliate_request.id)
end
it "does not allow to ignore the request when the affiliate has an account" do
create(:user, email: affiliate_request.email)
expect do
affiliate_request.ignore!
end.to raise_error(StateMachines::InvalidTransition)
end
end
context "when request is not attended yet" do
it "marks the request as ignored" do
expect do
affiliate_request.ignore!
end.to change { affiliate_request.reload.ignored? }.from(false).to(true)
end
it "notifies the requester of the ignored request" do
expect do
affiliate_request.ignore!
end.to have_enqueued_mail(AffiliateRequestMailer, :notify_requester_of_ignored_request).with(affiliate_request.id)
end
end
end
describe "#make_requester_an_affiliate!" do
let(:creator) { create(:named_user) }
let(:requester_email) { "requester@example.com" }
let(:affiliate_request) { create(:affiliate_request, email: requester_email, seller: creator, state: :approved) }
let(:published_product_one) { create(:product, user: creator) }
let(:published_product_two) { create(:product, user: creator) }
let!(:published_product_three) { create(:product, user: creator) }
let(:published_product_four) { create(:product, user: creator) }
let(:deleted_product) { create(:product, user: creator, deleted_at: 1.day.ago) }
let!(:enabled_self_service_affiliate_product_for_published_product_one) { create(:self_service_affiliate_product, enabled: true, seller: creator, product: published_product_one) }
let!(:enabled_self_service_affiliate_product_for_published_product_two) { create(:self_service_affiliate_product, enabled: true, seller: creator, product: published_product_two, destination_url: "https://example.com") }
let!(:enabled_self_service_affiliate_product_for_published_product_four) { create(:self_service_affiliate_product, enabled: true, seller: creator, product: published_product_four, affiliate_basis_points: 1000) }
let!(:enabled_self_service_affiliate_product_for_deleted_product) { create(:self_service_affiliate_product, enabled: true, seller: creator, product: deleted_product) }
context "when requester doesn't have an account" do
it "sends request approval email to the requester but does not make them an affiliate" do
expect do
expect do
expect do
affiliate_request.make_requester_an_affiliate!
end.to_not change { creator.direct_affiliates.count }
end.to_not have_enqueued_mail(AffiliateRequestMailer, :notify_requester_of_request_approval)
end.to have_enqueued_mail(AffiliateRequestMailer, :notify_unregistered_requester_of_request_approval)
end
end
context "when requester is already an affiliate of some of the self-service affiliate products" do
let(:requester) { create(:user, email: requester_email) }
let(:affiliate) { create(:direct_affiliate, seller: creator, affiliate_user: requester, affiliate_basis_points: 45_00) }
it "makes the requester an affiliate of all the enabled products with the configured commission fee" do
create(:product_affiliate, affiliate:, product: published_product_four, affiliate_basis_points: 10_00)
expect do
expect do
affiliate_request.make_requester_an_affiliate!
end.to change { creator.direct_affiliates.count }.by(0)
.and change { affiliate.reload.product_affiliates.count }.from(1).to(3)
.and have_enqueued_mail(AffiliateRequestMailer, :notify_requester_of_request_approval).with(affiliate_request.id)
end.to_not have_enqueued_mail(AffiliateMailer, :direct_affiliate_invitation)
expect(affiliate.reload.send_posts).to eq(true)
expect(affiliate.affiliate_basis_points).to eq(45_00)
expect(affiliate.product_affiliates.count).to eq(3)
affiliate_product_1 = affiliate.reload.product_affiliates.find_by(link_id: published_product_one.id)
expect(affiliate_product_1.affiliate_basis_points).to eq(5_00)
expect(affiliate_product_1.destination_url).to be_nil
affiliate_product_2 = affiliate.reload.product_affiliates.find_by(link_id: published_product_two.id)
expect(affiliate_product_2.affiliate_basis_points).to eq(5_00)
expect(affiliate_product_2.destination_url).to eq("https://example.com")
affiliate_product_3 = affiliate.reload.product_affiliates.find_by(link_id: published_product_four.id)
expect(affiliate_product_3.affiliate_basis_points).to eq(10_00)
expect(affiliate_product_3.destination_url).to be_nil
end
end
context "when requester is already an affiliate of all of the self-service affiliate products" do
let(:requester) { create(:user, email: requester_email) }
before do
affiliate = create(:direct_affiliate, seller: creator, affiliate_user: requester)
create(:product_affiliate, affiliate:, product: published_product_one)
create(:product_affiliate, affiliate:, product: published_product_two)
create(:product_affiliate, affiliate:, product: published_product_three)
create(:product_affiliate, affiliate:, product: published_product_four)
end
it "does nothing" do
expect do
expect do
expect do
expect do
affiliate_request.make_requester_an_affiliate!
end.to_not change { creator.direct_affiliates.count }
end.to_not change { requester.directly_affiliated_products.count }
end.to_not have_enqueued_mail(AffiliateRequestMailer, :notify_requester_of_request_approval)
end.to_not have_enqueued_mail(AffiliateMailer, :direct_affiliate_invitation)
end
end
end
describe "after_commit callbacks" do
it "sends emails to both requester and seller about the submitted affiliate request" do
expect do
create(:affiliate_request)
end.to have_enqueued_mail(AffiliateRequestMailer, :notify_requester_of_request_submission)
.and have_enqueued_mail(AffiliateRequestMailer, :notify_seller_of_new_request)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/philippines_bank_account_spec.rb | spec/models/philippines_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PhilippinesBankAccount do
describe "#bank_account_type" do
it "returns philippines" do
expect(create(:philippines_bank_account).bank_account_type).to eq("PH")
end
end
describe "#country" do
it "returns PH" do
expect(create(:philippines_bank_account).country).to eq("PH")
end
end
describe "#currency" do
it "returns php" do
expect(create(:philippines_bank_account).currency).to eq("php")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:philippines_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("BCDEFGHI123")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:philippines_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789")
end
end
describe "#validate_bank_code" do
it "allows 8 to 11 characters only" do
expect(build(:philippines_bank_account, bank_code: "BCDEFGHI")).to be_valid
expect(build(:philippines_bank_account, bank_code: "BCDEFGHI1")).to be_valid
expect(build(:philippines_bank_account, bank_code: "BCDEFGHI12")).to be_valid
expect(build(:philippines_bank_account, bank_code: "BCDEFGHI123")).to be_valid
expect(build(:philippines_bank_account, bank_code: "BCDEFGH")).not_to be_valid
expect(build(:philippines_bank_account, bank_code: "BCDEFGHI1234")).not_to be_valid
end
end
describe "#validate_account_number" do
it "allows records that match the required account number regex" do
expect(build(:philippines_bank_account, account_number: "1")).to be_valid
expect(build(:philippines_bank_account, account_number: "123456789")).to be_valid
expect(build(:philippines_bank_account, account_number: "12345678901234567")).to be_valid
ph_bank_account = build(:philippines_bank_account, account_number: "ABCDEFGHIJKL")
expect(ph_bank_account).to_not be_valid
expect(ph_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
ph_bank_account = build(:philippines_bank_account, account_number: "123456789012345678")
expect(ph_bank_account).to_not be_valid
expect(ph_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/tag_spec.rb | spec/models/tag_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Tag do
before { @product = create(:product) }
it "Creates a new tag by name" do
expect(@product.has_tag?("bAdger")).to be(false)
expect { @product.tag!("Badger") }.to change { @product.tags.count }.by(1)
expect(@product.tags.last.name).to eq("badger")
expect(@product.has_tag?("bAdGEr")).to be(true)
end
describe "clean before validation" do
it "cleans tag name before save" do
@product.tag!(" UP space ")
expect(@product.tags.last.name).to eq("up space")
end
it "only cleans if name has changed" do
create(:tag, name: "will be overwritten").update_column(:name, "INVA LID")
tag = Tag.all.first
expect(tag.name).to eq "INVA LID"
tag.humanized_name = "invalid-human"
tag.save!
expect(tag.name).to eq "INVA LID"
end
end
describe "validation" do
it "does not raise exception on tags without names" do
expect(Tag.new.valid?).to be false
end
it "must have name" do
tag = Tag.new
tag.name = nil
expect { tag.save! }.to raise_error(ActiveRecord::RecordInvalid)
end
it "must be unique, regardless of case" do
create(:tag, name: "existing")
expect { create(:tag, name: "existing") }.to raise_error(ActiveRecord::RecordInvalid)
expect { create(:tag, name: "EXISTING") }.to raise_error(ActiveRecord::RecordInvalid)
end
it "checks for names longer than max allowed" do
expect { create(:tag, name: "12345678901234567890_") }.to raise_error(ActiveRecord::RecordInvalid, /A tag is too long/)
end
it "checks for names shorter than min allowed" do
expect { create(:tag, name: "a") }.to raise_error(ActiveRecord::RecordInvalid, /A tag is too short/)
end
it "disallows tags starting with hashes" do
expect { create(:tag, name: "#icon") }.to raise_error(ActiveRecord::RecordInvalid, /cannot start with hashes/)
end
it "disallows tags with commas" do
expect { create(:tag, name: ",icon") }.to raise_error(ActiveRecord::RecordInvalid, /cannot.* contain commas/)
end
end
it "Tags with an existing tag by name" do
create(:tag, name: "Ocelot")
expect { @product.tag!("Ocelot") }.to_not change { Tag.count }
expect(@product.tags.last.name).to eq("ocelot")
end
it "Lists tags for a product" do
@product.tag!("otter")
@product.tag!("brontosaurus")
expect(@product.tags.map(&:name)).to eq(%w[otter brontosaurus])
end
it "Lists products for a tag" do
@product.tag!("otter")
second_product = create(:product)
second_product.tag!("otter")
expect(Tag.find_by(name: "otter").products).to eq([@product, second_product])
end
it "Finds scoped products by tag list" do
5.times { create(:product).tag!("fennec") }
3.times { create(:product).tag!("weasel") }
other_product = create(:product)
other_product.tag!("Weasel")
other_product.tag!("Fennec")
@product.tag!("Fennec")
@product.tag!("Weasel")
expect(Link.with_tags(["fennec"]).length).to eq(7)
expect(Link.with_tags(%w[fennec weasel]).sort).to eq([other_product, @product].sort)
expect(@product.user.links.with_tags(["fennec"])).to eq([@product])
expect(@product.user.links.with_tags(%w[fennec weasel])).to eq([@product])
expect(@product.user.links.with_tags(%w[fennec weasel hedgehog])).to be_empty
@product.tag!("Hedgehog")
expect(@product.user.links.with_tags(%w[fennec weasel hedgehog])).to eq([@product])
expect(@product.user.links.with_tags(%w[fennec weasel])).to eq([@product])
end
it "Untags" do
expect do
3.times { |i| create(:tag, name: "Some Tag #{i}") }
@product.tag!("Wildebeest")
expect(@product.has_tag?("WILDEBEEST")).to be(true)
expect { @product.untag!("wIlDeBeeST") }.to change { @product.tags.count }.to(0)
expect(@product.has_tag?("wildebeest")).to be(false)
end.to change { Tag.count }.by(4)
end
it "Flags" do
tag = create(:tag)
expect { tag.flag! }.to change { tag.flagged? }.from(false).to(true)
end
it "Unflags" do
tag = create(:tag, flagged_at: Time.current)
expect { tag.unflag! }.to change { tag.flagged? }.from(true).to(false)
end
describe "#humanized_name" do
it "capitalizes" do
expect(create(:tag, name: "photoshop tutorial").humanized_name).to eq("Photoshop Tutorial")
end
it "titleizes" do
expect(create(:tag, name: "raiders_of_stuff").humanized_name).to eq("Raiders Of Stuff")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/shipping_destination_spec.rb | spec/models/shipping_destination_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ShippingDestination do
before :each do
@product = create(:product)
end
it "it does not allow saving if the country code is nil or invalid" do
@product.shipping_destinations << ShippingDestination.new(country_code: "dummy",
one_item_rate_cents: 10,
multiple_items_rate_cents: 10)
expect(@product).to_not be_valid
valid_shipping_destination = ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2,
one_item_rate_cents: 10,
multiple_items_rate_cents: 10)
@product.reload.shipping_destinations << valid_shipping_destination
@product.save!
expect(@product.shipping_destinations.first).to eq(valid_shipping_destination)
end
it "does not allow saving if the standalone rate or the combined rate is missing" do
@product.shipping_destinations << ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2,
one_item_rate_cents: 10)
expect(@product).to_not be_valid
@product.reload.shipping_destinations << ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2,
multiple_items_rate_cents: 10)
expect(@product).to_not be_valid
valid_shipping_destination = ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2,
one_item_rate_cents: 10,
multiple_items_rate_cents: 10)
@product.reload.shipping_destinations << valid_shipping_destination
@product.save!
expect(@product.shipping_destinations.first).to eq(valid_shipping_destination)
end
it "does not allow associating a single record with both a user and a product" do
valid_shipping_destination1 = ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2,
one_item_rate_cents: 10,
multiple_items_rate_cents: 10)
valid_shipping_destination2 = ShippingDestination.new(country_code: Compliance::Countries::DEU.alpha2,
one_item_rate_cents: 10,
multiple_items_rate_cents: 10)
@product.shipping_destinations << valid_shipping_destination1
@product.save!
expect(@product.shipping_destinations.first).to eq(valid_shipping_destination1)
@product.user.shipping_destinations << valid_shipping_destination1
@product.save!
expect(@product.reload.user.shipping_destinations).to be_empty
@product.user.reload.shipping_destinations << valid_shipping_destination2
@product.save!
expect(@product.user.shipping_destinations.first).to eq(valid_shipping_destination2)
end
it "does not allow duplicate entries for a country code for a product" do
valid_shipping_destination = ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2,
one_item_rate_cents: 20,
multiple_items_rate_cents: 10)
@product.shipping_destinations << valid_shipping_destination
@product.save!
expect(@product.shipping_destinations.first).to eq(valid_shipping_destination)
@product.shipping_destinations << ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2,
one_item_rate_cents: 10,
multiple_items_rate_cents: 10)
expect(@product).to_not be_valid
end
it "does not allow duplicate entries for a country code for a user" do
valid_shipping_destination = ShippingDestination.new(country_code: ShippingDestination::Destinations::ELSEWHERE,
one_item_rate_cents: 20,
multiple_items_rate_cents: 10)
@product.user.shipping_destinations << valid_shipping_destination
@product.save!
expect(@product.user.shipping_destinations.first).to eq(valid_shipping_destination)
@product.user.shipping_destinations << ShippingDestination.new(country_code: ShippingDestination::Destinations::ELSEWHERE,
one_item_rate_cents: 10,
multiple_items_rate_cents: 10)
@product.save!
expect(@product.user.reload.shipping_destinations).to eq([valid_shipping_destination])
end
describe "#calculate_shipping_rate" do
before do
@shipping_destination = ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2,
one_item_rate_cents: 20,
multiple_items_rate_cents: 10)
end
it "returns nil for quantity < 1" do
expect(@shipping_destination.calculate_shipping_rate(quantity: -1)).to be_nil
end
it "returns one_item_rate_cents for quantity = 1" do
expect(@shipping_destination.calculate_shipping_rate(quantity: 1)).to eq(20)
end
it "returns one_item_rate_cents + (quantity -1)*multiple_items_rate_cents for quantity > 1" do
expect(@shipping_destination.calculate_shipping_rate(quantity: 2)).to eq(30)
expect(@shipping_destination.calculate_shipping_rate(quantity: 3)).to eq(40)
expect(@shipping_destination.calculate_shipping_rate(quantity: 6)).to eq(70)
end
end
describe "#for_product_and_country_code" do
it "returns nil if the destination country code is nil or the product is not physical" do
link = create(:product)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: nil)).to be_nil
shipping_destination = ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2, one_item_rate_cents: 20, multiple_items_rate_cents: 10)
link.shipping_destinations << shipping_destination
link.is_physical = false
link.save!
expect(ShippingDestination.for_product_and_country_code(product: link.reload, country_code: Compliance::Countries::USA.alpha2)).to be_nil
link.is_physical = true
link.shipping_destinations << ShippingDestination.new(country_code: ShippingDestination::Destinations::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::USA.alpha2)).to eq(shipping_destination)
end
it "returns a configured shipping destination if there is a match" do
link = create(:product)
shipping_destination1 = ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2, one_item_rate_cents: 20, multiple_items_rate_cents: 10)
shipping_destination2 = ShippingDestination.new(country_code: Compliance::Countries::DEU.alpha2, one_item_rate_cents: 10, multiple_items_rate_cents: 5)
shipping_destination3 = ShippingDestination.new(country_code: Compliance::Countries::GBR.alpha2, one_item_rate_cents: 10, multiple_items_rate_cents: 5)
link.is_physical = true
link.require_shipping = true
link.shipping_destinations << shipping_destination1 << shipping_destination2 << shipping_destination3
link.save!
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::USA.alpha2)).to eq(shipping_destination1)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::DEU.alpha2)).to eq(shipping_destination2)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::GBR.alpha2)).to eq(shipping_destination3)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::ESP.alpha2)).to be_nil
end
it "returns a match for any country if there is a configuration for ELSEWHERE" do
link = create(:product)
shipping_destination = ShippingDestination.new(country_code: ShippingDestination::Destinations::ELSEWHERE, one_item_rate_cents: 20, multiple_items_rate_cents: 10)
link.shipping_destinations << shipping_destination
link.is_physical = true
link.require_shipping = true
link.save!
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::USA.alpha2)).to eq(shipping_destination)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::DEU.alpha2)).to eq(shipping_destination)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::ESP.alpha2)).to eq(shipping_destination)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::GBR.alpha2)).to eq(shipping_destination)
end
it "returns a match for the specific country before matching ELSEWHERE" do
link = create(:product)
shipping_destination1 = ShippingDestination.new(country_code: ShippingDestination::Destinations::ELSEWHERE, one_item_rate_cents: 20, multiple_items_rate_cents: 10)
shipping_destination2 = ShippingDestination.new(country_code: Compliance::Countries::DEU.alpha2, one_item_rate_cents: 10, multiple_items_rate_cents: 5)
link.shipping_destinations << shipping_destination1 << shipping_destination2
link.is_physical = true
link.require_shipping = true
link.save!
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::USA.alpha2)).to eq(shipping_destination1)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::ESP.alpha2)).to eq(shipping_destination1)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::GBR.alpha2)).to eq(shipping_destination1)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::DEU.alpha2)).to eq(shipping_destination2)
end
describe "virtual countries" do
it "returns a configured shipping destination if there is a match" do
link = create(:product)
shipping_destination1 = ShippingDestination.new(country_code: ShippingDestination::Destinations::EUROPE, one_item_rate_cents: 20, multiple_items_rate_cents: 10, is_virtual_country: true)
shipping_destination2 = ShippingDestination.new(country_code: ShippingDestination::Destinations::ASIA, one_item_rate_cents: 10, multiple_items_rate_cents: 5, is_virtual_country: true)
shipping_destination3 = ShippingDestination.new(country_code: ShippingDestination::Destinations::NORTH_AMERICA, one_item_rate_cents: 10, multiple_items_rate_cents: 5, is_virtual_country: true)
link.is_physical = true
link.require_shipping = true
link.shipping_destinations << shipping_destination1 << shipping_destination2 << shipping_destination3
link.save!
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::ESP.alpha2)).to eq(shipping_destination1)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::DEU.alpha2)).to eq(shipping_destination1)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::FRA.alpha2)).to eq(shipping_destination1)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::IND.alpha2)).to eq(shipping_destination2)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::CHN.alpha2)).to eq(shipping_destination2)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::MNG.alpha2)).to eq(shipping_destination2)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::USA.alpha2)).to eq(shipping_destination3)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::MEX.alpha2)).to eq(shipping_destination3)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::CAN.alpha2)).to eq(shipping_destination3)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::NGA.alpha2)).to be_nil
end
it "returns a country match before a virtual country match" do
link = create(:product)
shipping_destination1 = ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2, one_item_rate_cents: 20, multiple_items_rate_cents: 10)
shipping_destination2 = ShippingDestination.new(country_code: ShippingDestination::Destinations::NORTH_AMERICA, one_item_rate_cents: 10, multiple_items_rate_cents: 5, is_virtual_country: true)
link.shipping_destinations << shipping_destination1 << shipping_destination2
link.is_physical = true
link.require_shipping = true
link.save!
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::USA.alpha2)).to eq(shipping_destination1)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::MEX.alpha2)).to eq(shipping_destination2)
end
it "returns a match for a virtual country before matching ELSEWHERE" do
link = create(:product)
shipping_destination1 = ShippingDestination.new(country_code: ShippingDestination::Destinations::ELSEWHERE, one_item_rate_cents: 20, multiple_items_rate_cents: 10)
shipping_destination2 = ShippingDestination.new(country_code: ShippingDestination::Destinations::NORTH_AMERICA, one_item_rate_cents: 10, multiple_items_rate_cents: 5, is_virtual_country: true)
link.shipping_destinations << shipping_destination1 << shipping_destination2
link.is_physical = true
link.require_shipping = true
link.save!
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::USA.alpha2)).to eq(shipping_destination2)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::ESP.alpha2)).to eq(shipping_destination1)
expect(ShippingDestination.for_product_and_country_code(product: link, country_code: Compliance::Countries::GBR.alpha2)).to eq(shipping_destination1)
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/seller_profile_featured_product_section_spec.rb | spec/models/seller_profile_featured_product_section_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SellerProfileFeaturedProductSection do
describe "validations" do
it "validates json_data with the correct schema" do
section = build(:seller_profile_featured_product_section, featured_product_id: 1)
section.json_data["garbage"] = "should not be here"
schema = JSON.parse(File.read(Rails.root.join("lib", "json_schemas", "seller_profile_featured_product_section.json").to_s))
expect(JSON::Validator).to receive(:new).with(schema, insert_defaults: true, record_errors: true).and_wrap_original do |original, *args|
validator = original.call(*args)
expect(validator).to receive(:validate).with(section.json_data).and_call_original
validator
end
section.validate
expect(section.errors.full_messages.to_sentence).to eq("The property '#/' contains additional properties [\"garbage\"] outside of the schema when none are allowed")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/post_email_blast_spec.rb | spec/models/post_email_blast_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe PostEmailBlast do
let(:blast) { create(:post_email_blast) }
describe ".aggregated", :freeze_time do
before do
create(:post_email_blast, requested_at: Time.current, started_at: nil, first_email_delivered_at: nil, last_email_delivered_at: nil, delivery_count: 0)
create(:post_email_blast, requested_at: 1.day.ago, started_at: 1.day.ago + 30.seconds, first_email_delivered_at: 1.day.ago + 10.minutes, last_email_delivered_at: 1.day.ago + 20.minutes, delivery_count: 15)
create(:post_email_blast, requested_at: 1.day.ago, started_at: 1.day.ago + 10.seconds, first_email_delivered_at: 1.day.ago + 20.minutes, last_email_delivered_at: 1.day.ago + 40.minutes, delivery_count: 25)
end
it "returns the aggregated data" do
result = PostEmailBlast.aggregated.to_a
expect(result.size).to eq(2)
expect(result[0]).to have_attributes(
date: Date.current,
total: 1,
total_delivery_count: 0,
average_start_latency: nil,
average_first_email_delivery_latency: nil,
average_last_email_delivery_latency: nil,
average_deliveries_per_minute: nil
)
expect(result[1]).to have_attributes(
date: 1.day.ago.to_date,
total: 2,
total_delivery_count: 40, # 15 + 25
average_start_latency: 20.0, # (30 seconds + 10 seconds) / 2
average_first_email_delivery_latency: 15.minutes.to_f, # (10 minutes + 20 minutes) / 2
average_last_email_delivery_latency: 30.minutes.to_f, # (20 minutes + 40 minutes) / 2
average_deliveries_per_minute: 1.375 # (15 deliveries in 10 minutes + 25 deliveries in 20 minutes) / 2
)
end
end
describe "Latency metrics", :freeze_time do
describe "#start_latency" do
it "returns the difference between requested_at and started_at" do
expect(blast.start_latency).to eq(5.minutes)
end
it "returns nil if started_at is nil" do
blast.update!(started_at: nil)
expect(blast.start_latency).to be_nil
end
it "returns nil if requested_at is nil" do
blast.update!(requested_at: nil)
expect(blast.start_latency).to be_nil
end
end
describe "#first_email_delivery_latency" do
it "returns the difference between requested_at and first_email_delivered_at" do
expect(blast.first_email_delivery_latency).to eq(10.minutes)
end
it "returns nil if first_email_delivered_at is nil" do
blast.update!(first_email_delivered_at: nil)
expect(blast.first_email_delivery_latency).to be_nil
end
it "returns nil if requested_at is nil" do
blast.update!(requested_at: nil)
expect(blast.first_email_delivery_latency).to be_nil
end
end
describe "#last_email_delivery_latency" do
it "returns the difference between requested_at and last_email_delivered_at" do
expect(blast.last_email_delivery_latency).to eq(20.minutes)
end
it "returns nil if last_email_delivered_at is nil" do
blast.update!(last_email_delivered_at: nil)
expect(blast.last_email_delivery_latency).to be_nil
end
it "returns nil if requested_at is nil" do
blast.update!(requested_at: nil)
expect(blast.last_email_delivery_latency).to be_nil
end
end
describe "#deliveries_per_minute" do
it "returns the deliveries per minute" do
# 1500 deliveries in 10 minutes = 150 deliveries per minute
expect(blast.deliveries_per_minute).to eq(150.0)
end
it "returns nil if last_email_delivered_at is nil" do
blast.update!(last_email_delivered_at: nil)
expect(blast.deliveries_per_minute).to be_nil
end
it "returns nil if first_email_delivered_at is nil" do
blast.update!(first_email_delivered_at: nil)
expect(blast.deliveries_per_minute).to be_nil
end
end
end
describe ".acknowledge_email_delivery" do
let(:blast) { create(:post_email_blast, :just_requested) }
it "sets first_email_delivered_at and last_email_delivered_at to the current time and increment deliveries count", :freeze_time do
described_class.acknowledge_email_delivery(blast.id)
blast.reload
expect(blast.first_email_delivered_at).to eq(Time.current)
expect(blast.last_email_delivered_at).to eq(Time.current)
expect(blast.delivery_count).to eq(1)
end
it "called twice only updates last_email_delivered_at to the current time" do
current_time = Time.current
travel_to current_time do
described_class.acknowledge_email_delivery(blast.id)
end
travel_to current_time + 1.hour do
described_class.acknowledge_email_delivery(blast.id)
blast.reload
expect(blast.first_email_delivered_at).to eq(1.hour.ago)
expect(blast.last_email_delivered_at).to eq(Time.current)
expect(blast.delivery_count).to eq(2)
end
end
end
describe ".format_datetime" do
it "returns a string without the timezone" do
expect(described_class.format_datetime(Time.zone.local(2001, 2, 3, 4, 5, 6))).to eq("2001-02-03 04:05:06")
end
it "returns nil if the datetime is nil" do
expect(described_class.format_datetime(nil)).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/collaborator_spec.rb | spec/models/collaborator_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Collaborator do
describe "associations" do
it { is_expected.to belong_to(:seller) }
end
describe "validations" do
it { is_expected.to validate_numericality_of(:affiliate_basis_points).is_greater_than_or_equal_to(1_00).is_less_than_or_equal_to(50_00).allow_nil }
context "when another record exists" do
before { create(:collaborator) }
it { is_expected.to validate_uniqueness_of(:seller_id).scoped_to(:affiliate_user_id, :deleted_at) }
end
describe "affiliate_basis_points presence" do
it "requires affiliate_basis_points to be present if apply_to_all_products is set" do
collaborator = build(:collaborator, apply_to_all_products: true, affiliate_basis_points: nil)
expect(collaborator).not_to be_valid
expect(collaborator.errors.full_messages).to eq ["Affiliate basis points can't be blank"]
collaborator.affiliate_basis_points = 30_00
expect(collaborator).to be_valid
end
it "does not require affiliate_basis_points to be present if apply_to_all_products is not set" do
collaborator = build(:collaborator, apply_to_all_products: false, affiliate_basis_points: nil)
expect(collaborator).to be_valid
end
end
describe "collaborator_does_not_require_approval" do
context "when affiliate_user has changed" do
let(:collaborator) { build(:collaborator, affiliate_user: create(:user, require_collab_request_approval: true)) }
it "requires the affiliate user to allow collaborator requests without approval" do
expect(collaborator.save).to eq false
expect(collaborator.errors.full_messages).to match_array ["You cannot add this user as a collaborator"]
end
end
context "when affiliate_user has not changed" do
let(:collaborator) { create(:collaborator) }
before { collaborator.affiliate_user.update!(require_collab_request_approval: true) }
it "does not require the affiliate user to allow collaborator requests without approval" do
expect(collaborator.update(affiliate_basis_points: 25_00)).to eq true
end
end
end
describe "eligible_for_stripe_payments" do
let(:seller) { create(:user) }
let(:affiliate_user) { create(:user) }
let(:collaborator) { build(:collaborator, seller:, affiliate_user:) }
context "when affiliate user has a Brazilian Stripe Connect account" do
before do
allow(affiliate_user).to receive(:has_brazilian_stripe_connect_account?).and_return(true)
allow(seller).to receive(:has_brazilian_stripe_connect_account?).and_return(false)
end
it "is invalid" do
expect(collaborator).not_to be_valid
expect(collaborator.errors[:base]).to include(
"This user cannot be added as a collaborator because they use a Brazilian Stripe account."
)
end
end
context "when seller has a Brazilian Stripe Connect account" do
before do
allow(affiliate_user).to receive(:has_brazilian_stripe_connect_account?).and_return(false)
allow(seller).to receive(:has_brazilian_stripe_connect_account?).and_return(true)
end
it "is invalid" do
expect(collaborator).not_to be_valid
expect(collaborator.errors[:base]).to include(
"You cannot add a collaborator because you are using a Brazilian Stripe account."
)
end
end
context "when neither user has a Brazilian Stripe Connect account" do
before do
allow(seller).to receive(:has_brazilian_stripe_connect_account?).and_return(false)
allow(affiliate_user).to receive(:has_brazilian_stripe_connect_account?).and_return(false)
end
it "is valid" do
expect(collaborator).to be_valid
end
end
end
end
describe "scopes" do
describe ".invitation_accepted and .invitation_pending" do
it "returns collaborators without invitations" do
accepted_collaborator = create(:collaborator)
pending_collaborator = create(:collaborator, :with_pending_invitation)
expect(Collaborator.invitation_accepted).to contain_exactly(accepted_collaborator)
expect(Collaborator.invitation_pending).to contain_exactly(pending_collaborator)
end
end
end
describe "#invitation_accepted?" do
it "returns true when the collaborator has no invitation" do
collaborator = create(:collaborator)
collaborator.create_collaborator_invitation!
expect(collaborator.invitation_accepted?).to be false
collaborator.collaborator_invitation.destroy!
expect(collaborator.reload.invitation_accepted?).to be true
end
end
describe "#as_json" do
it "returns a hash of attributes" do
product = create(:product)
collaborator = create(:collaborator, seller: product.user, affiliate_basis_points: 25_00, dont_show_as_co_creator: true)
collaborator.product_affiliates.create!(product:, affiliate_basis_points: 50_00)
expect(collaborator.as_json).to match(
id: collaborator.external_id,
email: collaborator.affiliate_user.email,
name: collaborator.affiliate_user.display_name(prefer_email_over_default_username: true),
apply_to_all_products: collaborator.apply_to_all_products?,
avatar_url: collaborator.affiliate_user.avatar_url,
percent_commission: 25,
setup_incomplete: false,
dont_show_as_co_creator: true,
invitation_accepted: true,
)
end
it "includes the invitation_accepted status" do
collaborator = create(:collaborator)
create(:collaborator_invitation, collaborator: collaborator)
expect(collaborator.as_json[:invitation_accepted]).to be false
end
end
describe "#mark_deleted!" do
it "disables the is_collab flag on all associated products" do
products = create_list(:product, 2, is_collab: true)
collaborator = create(:collaborator, products:)
expect do
collaborator.mark_deleted!
end.to change { collaborator.reload.deleted? }.from(false).to(true)
.and change { products.first.reload.is_collab }.from(true).to(false)
.and change { products.last.reload.is_collab }.from(true).to(false)
end
end
describe "#basis_points" do
let(:collaborator) { create(:collaborator, affiliate_basis_points: 10_00) }
let(:product_affiliate) { create(:product_affiliate, affiliate: collaborator, affiliate_basis_points: product_affiliate_basis_points) }
context "when no product_id is provided" do
let(:product_affiliate_basis_points) { nil }
it "returns the collaborator's basis points" do
expect(collaborator.basis_points).to eq 10_00
end
end
context "when product_id is provided" do
context "and the product affiliate commission is set" do
let(:product_affiliate_basis_points) { 20_00 }
it "returns the product affiliate's basis points" do
expect(collaborator.basis_points(product_id: product_affiliate.link_id)).to eq 20_00
end
end
context "and product affiliate commission is not set" do
let(:product_affiliate_basis_points) { nil }
it "returns the collaborator's basis points" do
expect(collaborator.basis_points(product_id: product_affiliate.link_id)).to eq 10_00
end
end
end
end
describe "#show_as_co_creator_for_product?" do
let(:product) { create(:product) }
context "when apply_to_all_products is true" do
let(:collaborator) { create(:collaborator) }
let!(:product_affiliate) { create(:product_affiliate, affiliate: collaborator, product:, dont_show_as_co_creator: true) }
it "returns true if dont_show_as_co_creator is false, false otherwise" do
expect(collaborator.show_as_co_creator_for_product?(product)).to eq true
collaborator.dont_show_as_co_creator = true
expect(collaborator.show_as_co_creator_for_product?(product)).to eq false
end
end
context "when apply_to_all_products is false" do
let(:collaborator) { create(:collaborator, apply_to_all_products: false, dont_show_as_co_creator: true) }
let!(:product_affiliate) { create(:product_affiliate, affiliate: collaborator, product:, dont_show_as_co_creator: false) }
it "returns true if the product_affiliate's dont_show_as_co_creator is false, false otherwise" do
expect(collaborator.show_as_co_creator_for_product?(product)).to eq true
product_affiliate.update!(dont_show_as_co_creator: true)
expect(collaborator.show_as_co_creator_for_product?(product)).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/gibraltar_bank_account_spec.rb | spec/models/gibraltar_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GibraltarBankAccount do
describe "#bank_account_type" do
it "returns gibraltar" do
expect(create(:gibraltar_bank_account).bank_account_type).to eq("GI")
end
end
describe "#country" do
it "returns GI" do
expect(create(:gibraltar_bank_account).country).to eq("GI")
end
end
describe "#currency" do
it "returns gbp" do
expect(create(:gibraltar_bank_account).currency).to eq("gbp")
end
end
describe "#routing_number" do
it "returns nil" do
expect(create(:gibraltar_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(:gibraltar_bank_account, account_number_last_four: "0000").account_number_visual).to eq("GI******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(:gibraltar_bank_account)).to be_valid
expect(build(:gibraltar_bank_account, account_number: "GI75NWBK000000007099453")).to be_valid
gi_bank_account = build(:gibraltar_bank_account, account_number: "GI12345")
expect(gi_bank_account).to_not be_valid
expect(gi_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
gi_bank_account = build(:gibraltar_bank_account, account_number: "DE61109010140000071219812874")
expect(gi_bank_account).to_not be_valid
expect(gi_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
gi_bank_account = build(:gibraltar_bank_account, account_number: "8937040044053201300000")
expect(gi_bank_account).to_not be_valid
expect(gi_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
gi_bank_account = build(:gibraltar_bank_account, account_number: "GIABCDE")
expect(gi_bank_account).to_not be_valid
expect(gi_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/product_tagging_spec.rb | spec/models/product_tagging_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ProductTagging do
before do
@creator = create(:user)
product_a = create(:product)
product_a.tag!("tag a")
product_a.tag!("tag b")
product_a.tag!("tag c")
product_b = create(:product, user: @creator)
product_b.tag!("tag b")
product_b.tag!("tag c")
product_c = create(:product)
product_c.tag!("tag b")
end
describe ".sorted_by_tags_usage_for_products" do
it "returns tags sorted by number of tagged products" do
product_taggings = ProductTagging.sorted_by_tags_usage_for_products(Link.all)
expect(product_taggings.to_a.map(&:tag).map(&:name)).to eq([
"tag b",
"tag c",
"tag a",
])
end
end
describe ".owned_by_user" do
it "returns tags owned by a user" do
product_tagging = ProductTagging.owned_by_user(@creator)
expect(product_tagging.first.tag.name).to eq("tag b")
end
end
describe ".has_tag_name" do
it "returns tags by name" do
product_tagging = ProductTagging.has_tag_name("tag b")
expect(product_tagging.first.tag.name).to eq("tag b")
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_review_video_spec.rb | spec/models/product_review_video_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe ProductReviewVideo, type: :model do
describe "approval status transitions" do
let(:product_review) { create(:product_review) }
let!(:pending_video) { create(:product_review_video, :pending_review, product_review:) }
let!(:approved_video) { create(:product_review_video, :approved, product_review:) }
let!(:rejected_video) { create(:product_review_video, :rejected, product_review:) }
it "marks other videos of the same status as deleted" do
new_video = create(:product_review_video, product_review:)
expect { new_video.pending_review! }
.to change { pending_video.reload.deleted? }
.from(false).to(true)
expect { new_video.approved! }
.to change { approved_video.reload.deleted? }
.from(false).to(true)
expect { new_video.rejected! }
.to change { rejected_video.reload.deleted? }
.from(false).to(true)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/bulgaria_bank_account_spec.rb | spec/models/bulgaria_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BulgariaBankAccount do
describe "#bank_account_type" do
it "returns bulgaria" do
expect(create(:bulgaria_bank_account).bank_account_type).to eq("BG")
end
end
describe "#country" do
it "returns BG" do
expect(create(:bulgaria_bank_account).country).to eq("BG")
end
end
describe "#currency" do
it "returns eur" do
expect(create(:bulgaria_bank_account).currency).to eq("eur")
end
end
describe "#routing_number" do
it "returns nil" do
expect(create(:bulgaria_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(:bulgaria_bank_account, account_number_last_four: "2874").account_number_visual).to eq("BG******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(:bulgaria_bank_account)).to be_valid
expect(build(:bulgaria_bank_account, account_number: "BG80 BNBG 9661 1020 3456 78")).to be_valid
bg_bank_account = build(:bulgaria_bank_account, account_number: "BG12345")
expect(bg_bank_account).to_not be_valid
expect(bg_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
bg_bank_account = build(:bulgaria_bank_account, account_number: "DE61109010140000071219812874")
expect(bg_bank_account).to_not be_valid
expect(bg_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
bg_bank_account = build(:bulgaria_bank_account, account_number: "8937040044053201300000")
expect(bg_bank_account).to_not be_valid
expect(bg_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
bg_bank_account = build(:bulgaria_bank_account, account_number: "BGABCDE")
expect(bg_bank_account).to_not be_valid
expect(bg_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/botswana_bank_account_spec.rb | spec/models/botswana_bank_account_spec.rb | # frozen_string_literal: true
describe BotswanaBankAccount do
describe "#bank_account_type" do
it "returns BW" do
expect(create(:botswana_bank_account).bank_account_type).to eq("BW")
end
end
describe "#country" do
it "returns BW" do
expect(create(:botswana_bank_account).country).to eq("BW")
end
end
describe "#currency" do
it "returns bwp" do
expect(create(:botswana_bank_account).currency).to eq("bwp")
end
end
describe "#routing_number" do
it "returns valid for 8 to 11 characters" do
expect(build(:botswana_bank_account, bank_code: "AAAAOMO")).not_to be_valid
expect(build(:botswana_bank_account, bank_code: "AAAAOMOM")).to be_valid
expect(build(:botswana_bank_account, bank_code: "AAAAOMOMX")).to be_valid
expect(build(:botswana_bank_account, bank_code: "AAAAOMOMXX")).to be_valid
expect(build(:botswana_bank_account, bank_code: "AAAAOMOMXXX")).to be_valid
expect(build(:botswana_bank_account, bank_code: "AAAAOMOMXXXX")).not_to be_valid
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:botswana_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(:botswana_bank_account)).to be_valid
expect(build(:botswana_bank_account, account_number: "123456")).to be_valid
expect(build(:botswana_bank_account, account_number: "000123456789")).to be_valid
expect(build(:botswana_bank_account, account_number: "1234567890123456")).to be_valid
expect(build(:botswana_bank_account, account_number: "ABCDEFGHIJKLMNOP")).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)
botswana_bank_account = build(:botswana_bank_account, account_number: "00012345678910111")
expect(botswana_bank_account).not_to be_valid
expect(botswana_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
botswana_bank_account = build(:botswana_bank_account, account_number: "ABCDEFGHIJKLMNOPQ")
expect(botswana_bank_account).not_to be_valid
expect(botswana_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
botswana_bank_account = build(:botswana_bank_account, account_number: "BW123456789012345")
expect(botswana_bank_account).not_to be_valid
expect(botswana_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/backtax_agreement_spec.rb | spec/models/backtax_agreement_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BacktaxAgreement do
describe "validation" do
it "is valid with expected parameters" do
expect(build(:backtax_agreement)).to be_valid
end
it "validates the presence of a signature" do
expect(build(:backtax_agreement, signature: nil)).to be_invalid
end
it "validates the inclusion of jurisdiction within a certain set" do
expect(build(:backtax_agreement, jurisdiction: "United States")).to be_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_spec.rb | spec/models/purchase_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Purchase, :vcr do
include CurrencyHelper
include ProductsHelper
def verify_balance(user, expected_balance)
expect(user.unpaid_balance_cents).to eq expected_balance
end
let(:ip_address) { "24.7.90.214" }
let(:initial_balance) { 200 }
let(:user) { create(:user, unpaid_balance_cents: initial_balance) }
let(:link) { create(:product, user:) }
let(:chargeable) { create :chargeable }
before do
allow_any_instance_of(Link).to receive(:recommendable?).and_return(true)
end
describe "scopes" do
describe "in_progress" do
before do
@in_progress_purchase = create(:purchase, purchase_state: "in_progress")
@successful_purchase = create(:purchase, purchase_state: "successful")
end
it "returns in_progress purchases" do
expect(Purchase.in_progress).to include @in_progress_purchase
end
it "does not return failed purchases" do
expect(Purchase.in_progress).to_not include @successful_purchase
end
end
describe "successful" do
before do
@successful_purchase = create(:purchase, purchase_state: "successful")
@failed_purchase = create(:purchase, purchase_state: "failed")
end
it "returns successful purchases" do
expect(Purchase.successful).to include @successful_purchase
end
it "does not return failed purchases" do
expect(Purchase.successful).to_not include @failed_purchase
end
end
describe ".not_successful" do
before do
@successful_purchase = create(:purchase, purchase_state: "successful")
@failed_purchase = create(:purchase, purchase_state: "failed")
end
it "returns only unsuccessful purchases" do
expect(described_class.not_successful).to include @failed_purchase
expect(described_class.not_successful).to_not include @successful_purchase
end
end
describe "failed" do
before do
@successful_purchase = create(:purchase, purchase_state: "successful")
@failed_purchase = create(:purchase, purchase_state: "failed")
end
it "does not returns successful purchases" do
expect(Purchase.failed).to_not include @successful_purchase
end
it "does return failed purchases" do
expect(Purchase.failed).to include @failed_purchase
end
end
describe "stripe_failed" do
before do
@failed_purchase_no_stripe_fingerprint = create(:purchase, stripe_fingerprint: nil, purchase_state: "failed")
@failed_purchase_with_stripe_fingerprint = create(:purchase, stripe_fingerprint: "asdfas235afasa", purchase_state: "failed")
@successful_purchase_with_stripe_fingerprint = create(:purchase, stripe_fingerprint: "asdfas235afasa", purchase_state: "successful")
end
it "returns failed purchases with non-blank stripe fingerprint" do
expect(Purchase.stripe_failed).to include @failed_purchase_with_stripe_fingerprint
end
it "does not return successful purchases" do
expect(Purchase.stripe_failed).to_not include @successful_purchase_with_stripe_fingerprint
end
it "does not return failed purchases with blank stripe fingerprint" do
expect(Purchase.stripe_failed).to_not include @failed_purchase_no_stripe_fingerprint
end
end
describe "non_free" do
before do
@non_zero_fee = create(:purchase)
@zero_fee = create(:free_purchase)
end
it "returns purchases with fee > 0" do
expect(Purchase.non_free).to include @non_zero_fee
end
it "does not return purchases with 0 fee" do
expect(Purchase.non_free).to_not include @zero_fee
end
end
describe "paid" do
before do
@non_refunded_purchase = create(:purchase, price_cents: 300, stripe_refunded: nil)
@free_purchase = create(:purchase, link: create(:product, price_range: "0+"), price_cents: 0, stripe_transaction_id: nil, stripe_fingerprint: nil)
@refunded_purchase = create(:purchase, price_cents: 300, stripe_refunded: true)
end
it "returns non-refunded non-free purchases" do
expect(Purchase.paid).to include @non_refunded_purchase
end
it "does not return refunded purchases" do
expect(Purchase.paid).to_not include @refunded_purchase
end
it "does not return free purchases" do
expect(Purchase.paid).to_not include @free_purchase
end
it "has charge processor id set" do
expect(@non_refunded_purchase.charge_processor_id).to be_present
expect(@free_purchase.charge_processor_id).to be(nil)
expect(@refunded_purchase.charge_processor_id).to be_present
end
end
describe "not_fully_refunded" do
before do
@refunded_purchase = create(:purchase, stripe_refunded: true)
@non_refunded_purchase = create(:purchase, stripe_refunded: nil)
end
it "returns non-refunded purchases" do
expect(Purchase.not_fully_refunded).to include @non_refunded_purchase
end
it "does not return refunded purchases" do
expect(Purchase.not_fully_refunded).to_not include @refunded_purchase
end
end
describe "not_chargedback" do
before do
@chargebacked_purchase = create(:purchase, chargeback_date: Date.yesterday)
@reversed_chargebacked_purchase = create(:purchase, chargeback_date: Date.yesterday, chargeback_reversed: true)
@non_chargebacked_purchase = create(:purchase)
end
it "does not return chargebacked purchase" do
expect(Purchase.not_chargedback).to_not include @chargebacked_purchase
expect(Purchase.not_chargedback).to_not include @reversed_chargebacked_purchase
end
it "returns non-chargebacked purchase" do
expect(Purchase.not_chargedback).to include @non_chargebacked_purchase
expect(Purchase.not_chargedback).to_not include @reversed_chargebacked_purchase
end
end
describe "not_chargedback_or_chargedback_reversed" do
before do
@chargebacked_purchase = create(:purchase, chargeback_date: Date.yesterday)
@reversed_chargebacked_purchase = create(:purchase, chargeback_date: Date.yesterday, chargeback_reversed: true)
@non_chargebacked_purchase = create(:purchase)
end
it "does not return chargebacked purchase" do
expect(Purchase.not_chargedback_or_chargedback_reversed).to_not include @chargebacked_purchase
end
it "returns non-chargebacked purchase" do
expect(Purchase.not_chargedback_or_chargedback_reversed).to include @non_chargebacked_purchase
end
it "returns chargebacked reversed purchase" do
expect(Purchase.not_chargedback_or_chargedback_reversed).to include @reversed_chargebacked_purchase
end
end
describe "additional contribution and max purchase quantity" do
before do
@product = create(:product, max_purchase_count: 1)
@purchase = create(:purchase, link: @product, is_additional_contribution: true)
end
it "does not count the additional contribution towards the max quantity" do
expect(@product.remaining_for_sale_count).to eq 1
end
end
describe "not_additional_contribution" do
before do
@additional_contribution = create(:purchase, is_additional_contribution: true)
@not_additional_contribution = create(:purchase)
end
it "returns puchases that are not additional contributions" do
expect(Purchase.not_additional_contribution).to include @not_additional_contribution
end
it "does not return purchases that are additional contribution" do
expect(Purchase.not_additional_contribution).to_not include @additional_contribution
end
end
describe "not_recurring_charge" do
before do
@normal_purchase = create(:purchase)
subscription = create(:subscription)
@original_subscription_purchase = create(:purchase, subscription:, is_original_subscription_purchase: true)
@recurring_purchase = create(:purchase, subscription:, is_original_subscription_purchase: false)
end
it "does not return purchases that are subscriptions and not original_subscription_purchase" do
expect(Purchase.not_recurring_charge).to_not include @recurring_purchase
end
it "returns purchases that are original_subscription_purchase" do
expect(Purchase.not_recurring_charge).to include @original_subscription_purchase
end
it "returns normal purchases" do
expect(Purchase.not_recurring_charge).to include @normal_purchase
end
end
describe "recurring_charge" do
before do
@normal_purchase = create(:purchase)
subscription = create(:subscription)
@original_subscription_purchase = create(:purchase, subscription:, is_original_subscription_purchase: true)
@recurring_purchase = create(:purchase, subscription:, is_original_subscription_purchase: false)
end
it "does not return purchases that are original_subscription_purchase" do
expect(Purchase.recurring_charge).to_not include @original_subscription_purchase
end
it "returns purchases that are original_subscription_purchase" do
expect(Purchase.recurring_charge).to include @recurring_purchase
end
it "does not return normal purchases" do
expect(Purchase.recurring_charge).to_not include @normal_purchase
end
end
describe ".paypal_orders" do
before do
@paypal_order_purchase = create(:purchase, paypal_order_id: "SamplePaypalOrderID")
@non_paypal_order_purchase = create(:purchase)
end
it "returns only paypal order purchases" do
expect(described_class.paypal_orders).to include @paypal_order_purchase
expect(described_class.paypal_orders).to_not include @non_paypal_order_purchase
end
end
describe ".unsuccessful_paypal_orders" do
before do
@unsuccessful_paypal_order_purchase = create(:purchase, paypal_order_id: "SamplePaypalOrderID1",
purchase_state: "in_progress",
created_at: 1.hour.ago)
@obsolete_unsuccessful_paypal_order_purchase = create(:purchase, paypal_order_id: "SamplePaypalOrderID1",
purchase_state: "in_progress",
created_at: 4.hours.ago)
@recent_unsuccessful_paypal_order_purchase = create(:purchase, paypal_order_id: "SamplePaypalOrderID2",
purchase_state: "in_progress",
created_at: 1.minute.ago)
@successful_paypal_order_purchase = create(:purchase, paypal_order_id: "SamplePaypalOrderID3",
purchase_state: "successful",
created_at: 1.hour.ago)
@successful_non_paypal_order_purchase = create(:purchase, purchase_state: "successful",
created_at: 1.hour.ago)
@unsuccessful_non_paypal_order_purchase = create(:purchase, purchase_state: "in_progress",
created_at: 1.hour.ago)
@unsuccessful_paypal_order_purchases = described_class.unsuccessful_paypal_orders(2.5.hours.ago, 0.5.hours.ago)
end
it "returns only unsuccessful paypal order purchases created in specified time" do
expect(@unsuccessful_paypal_order_purchases).to include @unsuccessful_paypal_order_purchase
expect(@unsuccessful_paypal_order_purchases).to_not include @obsolete_unsuccessful_paypal_order_purchase
expect(@unsuccessful_paypal_order_purchases).to_not include @recent_unsuccessful_paypal_order_purchase
expect(@unsuccessful_paypal_order_purchases).to_not include @successful_paypal_order_purchase
expect(@unsuccessful_paypal_order_purchases).to_not include @successful_non_paypal_order_purchase
expect(@unsuccessful_paypal_order_purchases).to_not include @unsuccessful_non_paypal_order_purchase
end
end
describe ".with_credit_card_id" do
it "returns the records with a credit_card_id value present" do
purchase1 = create(:purchase, credit_card_id: create(:credit_card).id)
purchase2 = create(:purchase)
purchase3 = create(:purchase, credit_card_id: create(:credit_card).id)
result = described_class.with_credit_card_id
expect(result).to include purchase1
expect(result).to_not include purchase2
expect(result).to include purchase3
end
end
describe ".not_rental_expired" do
it "returns purchases where rental_expired field is nil or false" do
purchase1 = create(:purchase, rental_expired: true)
purchase2 = create(:purchase, rental_expired: false)
purchase3 = create(:purchase, rental_expired: nil)
expect(Purchase.not_rental_expired).to include(purchase2)
expect(Purchase.not_rental_expired).to include(purchase3)
expect(Purchase.not_rental_expired).not_to include(purchase1)
end
end
describe ".for_library" do
it "excludes archived original subscription purchases" do
purchase = create(:purchase, is_archived_original_subscription_purchase: true)
expect(Purchase.for_library).not_to include(purchase)
end
it "includes updated original subscription purchases with not_charged state" do
purchase = create(:purchase, purchase_state: "not_charged")
expect(Purchase.for_library).to include(purchase)
end
it "excludes purchase with access revoked" do
purchase = create(:purchase, is_access_revoked: true)
expect(Purchase.for_library).not_to include(purchase)
end
end
describe ".for_mobile_listing" do
it "returns successful purchases" do
digital = create(:purchase, purchase_state: "successful")
subscription = create(:purchase, is_original_subscription_purchase: true, purchase_state: "successful")
updated_subscription = create(:purchase, is_original_subscription_purchase: true, purchase_state: "not_charged")
archived = create(:purchase, purchase_state: "successful", is_archived: true)
gift = create(:purchase, purchase_state: "gift_receiver_purchase_successful")
expect(Purchase.for_mobile_listing).to match_array [digital, subscription, updated_subscription, gift, archived]
end
it "excludes failed, refunded or chargedback, gift sender, recurring charge, buyer deleted, and expired rental purchases" do
create(:purchase, purchase_state: "failed")
create(:purchase, purchase_state: "successful", is_additional_contribution: true)
create(:purchase, purchase_state: "successful", is_gift_sender_purchase: true)
create(:purchase, purchase_state: "successful", stripe_refunded: true)
create(:purchase, purchase_state: "successful", chargeback_date: 1.day.ago)
create(:purchase, purchase_state: "successful", rental_expired: true)
create(:purchase, purchase_state: "successful", is_deleted_by_buyer: true)
original_purchase = create(:membership_purchase)
create(:membership_purchase, purchase_state: "successful", is_original_subscription_purchase: false, subscription: original_purchase.subscription)
create(:membership_purchase, purchase_state: "successful", is_original_subscription_purchase: true, is_archived_original_subscription_purchase: true)
expect(Purchase.where.not(id: original_purchase.id).for_mobile_listing).to be_empty
end
end
describe ".for_sales_api" do
it "includes successful purchases" do
purchase = create(:purchase, purchase_state: "successful")
expect(Purchase.for_sales_api).to match_array [purchase]
end
it "includes free trial not_charged purchases" do
purchase = create(:free_trial_membership_purchase)
expect(Purchase.for_sales_api).to match_array [purchase]
end
it "does not include other purchases" do
%w(
failed
gift_receiver_purchase_successful
preorder_authorization_successful
test_successful
).each do |purchase_state|
create(:purchase, purchase_state:)
end
original_purchase = create(:membership_purchase, is_archived_original_subscription_purchase: true)
create(:membership_purchase, subscription: original_purchase.subscription, link: original_purchase.link, purchase_state: "not_charged")
expect(Purchase.for_sales_api).to match_array [original_purchase]
end
end
describe ".for_visible_posts" do
it "returns only eligible purchases for viewing posts" do
buyer = create(:user)
successful_purchase = create(:purchase, purchaser: buyer, purchase_state: "successful")
free_trial_purchase = create(:free_trial_membership_purchase, purchaser: buyer)
gift_purchase = create(:purchase, purchase_state: "gift_receiver_purchase_successful", purchaser: buyer)
preorder_authorization_purchase = create(:preorder_authorization_purchase, purchaser: buyer)
membership_purchase = create(:membership_purchase, purchaser: buyer)
physical_purchase = create(:physical_purchase, purchaser: buyer)
create(:refunded_purchase, purchaser: buyer)
create(:failed_purchase, purchaser: buyer)
create(:purchase_in_progress, purchaser: buyer)
create(:disputed_purchase, purchaser: buyer)
create(:purchase, purchase_state: "successful")
expect(
Purchase.for_visible_posts(purchaser_id: buyer.id)
).to contain_exactly(
successful_purchase,
free_trial_purchase,
gift_purchase,
preorder_authorization_purchase,
membership_purchase,
physical_purchase
)
end
end
describe ".exclude_not_charged_except_free_trial" do
it "excludes purchases that are 'not_charged' but are not free trial purchases" do
included_purchases = %w(
successful
failed
gift_receiver_purchase_successful
preorder_authorization_successful
test_successful
).map do |purchase_state|
create(:purchase, purchase_state:)
end
included_purchases << create(:free_trial_membership_purchase)
create(:purchase, purchase_state: "not_charged")
expect(Purchase.exclude_not_charged_except_free_trial).to match_array included_purchases
end
end
describe ".no_or_active_subscription" do
it "returns non-subscription purchases and purchases with an active subscription" do
normal_purchase = create(:purchase)
subscription = create(:subscription)
subscription_purchase = create(:purchase, subscription:, is_original_subscription_purchase: true)
expect(Purchase.no_or_active_subscription).to eq([normal_purchase, subscription_purchase])
end
it "does not include purchases with inactive subscription" do
normal_purchase = create(:purchase)
subscription = create(:subscription, deactivated_at: 1.day.ago)
create(:purchase, subscription:, is_original_subscription_purchase: true)
expect(Purchase.no_or_active_subscription).to eq([normal_purchase])
end
end
describe ".inactive_subscription" do
it "returns subscription purchases which have been deactivated" do
create(:purchase)
active_subscription = create(:subscription)
create(:purchase, subscription: active_subscription, is_original_subscription_purchase: true)
deactivated_subscription = create(:subscription, deactivated_at: 1.day.ago)
deactivated_subscription_purchase = create(:purchase, subscription: deactivated_subscription, is_original_subscription_purchase: true)
expect(Purchase.inactive_subscription).to eq([deactivated_subscription_purchase])
end
end
describe ".can_access_content" do
it "includes non-subscription purchases" do
purchase = create(:purchase)
expect(Purchase.can_access_content).to match_array [purchase]
end
context "subscription purchases" do
let(:purchase) { create(:membership_purchase) }
let(:subscription) { purchase.subscription }
it "includes active subscription purchases" do
expect(Purchase.can_access_content).to match_array [purchase]
end
it "includes inactive subscription purchases where subscribers are allowed to access product content after the subscription has lapsed" do
subscription.update!(deactivated_at: 1.minute.ago)
expect(Purchase.can_access_content).to match_array [purchase]
end
it "excludes inactive subscription purchases if subscribers should lose access when subscription lapses" do
subscription.update!(deactivated_at: 1.minute.ago)
subscription.link.update!(block_access_after_membership_cancellation: true)
expect(Purchase.can_access_content).to be_empty
end
end
end
end
describe "lifecycle hooks" do
describe "check perceived_price_cents_matches_price_cents" do
let(:product) { create(:product, price_cents: 10_00) }
let(:purchase) { build(:purchase, link: product, perceived_price_cents: 5_00) }
it "returns false if the perceived price is different from the link price" do
purchase.save
expect(purchase.errors.full_messages).to include "Price cents The price just changed! Refresh the page for the updated price."
end
it "returns true if the purchase is_upgrade_purchase" do
purchase.is_upgrade_purchase = true
purchase.save
expect(purchase.errors.full_messages).to be_empty
end
end
end
describe "not_for_sale" do
it "doesn't allow purchases of unpublished products" do
link = create(:product, purchase_disabled_at: Time.current)
purchase = create(:purchase, link:, seller: link.user)
expect(purchase.errors[:base].present?).to be(true)
expect(purchase.error_code).to eq PurchaseErrorCode::NOT_FOR_SALE
end
it "allows purchases when is_commission_completion_purchase is true even if product is unpublished" do
link = create(:product, purchase_disabled_at: Time.current)
purchase = create(:purchase, link:, seller: link.user, is_commission_completion_purchase: true)
expect(purchase.errors[:base].present?).to be(false)
expect(purchase.error_code).to be_nil
end
end
describe "temporarily blocked product" do
before do
Feature.activate(:block_purchases_on_product)
@product = create(:product)
BlockedObject.block!(
BLOCKED_OBJECT_TYPES[:product],
@product.id,
nil,
expires_in: 6.hours
)
end
context "when the price is zero" do
before { @product.price_cents = 0 }
it "allows the purchase of temporarily blocked products" do
purchase = create(:purchase, price_cents: 0, link: @product)
expect(purchase.purchase_state).to eq "successful"
expect(purchase.error_code).to be_blank
end
end
context "when the price is not zero" do
it "doesn't allow purchases of temporarily blocked products" do
purchase = create(:purchase, link: @product)
expect(purchase.errors[:base].present?).to be(true)
expect(purchase.error_code).to eq PurchaseErrorCode::TEMPORARILY_BLOCKED_PRODUCT
expect(purchase.errors.full_messages).to include "Your card was not charged."
end
end
end
describe "sold_out" do
it "doesn't allow purchase once sold out" do
link = create(:product, max_purchase_count: 1)
create(:purchase, link:, seller: link.user)
p2 = create(:purchase, link:, purchase_state: "in_progress")
expect(p2.errors[:base].present?).to be(true)
expect(p2.error_code).to eq PurchaseErrorCode::PRODUCT_SOLD_OUT
end
it "doesn't count failed purchases towards the sold-out count" do
link = create(:product, max_purchase_count: 1)
create(:purchase, link:, purchase_state: "failed")
p2 = create(:purchase, link:)
expect(p2).to be_valid
p3 = create(:purchase, link:, purchase_state: "in_progress")
expect(p3.errors[:base].present?).to be(true)
expect(p3.error_code).to eq PurchaseErrorCode::PRODUCT_SOLD_OUT
end
it "allows saving a purchase when sold out" do
link = create(:product, max_purchase_count: 1)
purchase = create(:purchase, link:, seller: link.user)
purchase.email = "testingtesting123@example.org"
expect(purchase.save).to be(true)
end
it "doesn't count additional contributions toward max_purchase_count" do
link = create(:product, max_purchase_count: 1)
create(:purchase, link:, seller: link.user)
p2 = create(:purchase, link:, is_additional_contribution: true)
expect(p2).to be_valid
p3 = create(:purchase, link:)
expect(p3.errors[:base].present?).to be(true)
expect(p3.error_code).to eq PurchaseErrorCode::PRODUCT_SOLD_OUT
end
it "doesn't allow purchase once sold out" do
product = create(:product, max_purchase_count: 1)
create(:purchase, link: product)
purchase_2 = create(:purchase, link: product, purchase_state: "in_progress")
expect(purchase_2.errors[:base].present?).to be(true)
expect(purchase_2.error_code).to eq PurchaseErrorCode::PRODUCT_SOLD_OUT
end
describe "subscriptions" do
before do
@product = create(:membership_product, subscription_duration: :monthly, max_purchase_count: 1)
@purchase = create(:purchase, link: @product, subscription: create(:subscription, link: @product), is_original_subscription_purchase: true)
end
it "does not count recurring charges towards the max_purchase_count" do
@recurring_charge = build(:purchase, is_original_subscription_purchase: false, subscription: create(:subscription, link: @product), link: @product)
expect(@recurring_charge).to be_valid
end
it "does count original_subscription_purchase towards max_purchase_count" do
@purchase = create(:purchase, link: @product, subscription: create(:subscription), is_original_subscription_purchase: true)
expect(@purchase.errors[:base].present?).to be(true)
expect(@purchase.error_code).to eq PurchaseErrorCode::PRODUCT_SOLD_OUT
end
end
end
describe "variants_available" do
before :each do
@product = create(:product)
@variant_category = create(:variant_category, link: @product)
@variant1 = create(:variant, variant_category: @variant_category, max_purchase_count: 2)
@variant2 = create(:variant, variant_category: @variant_category)
end
it "succeeds when all variants are available for the given quantities" do
purchase = create(:purchase, link: @product, variant_attributes: [@variant1, @variant2])
expect(purchase.errors).to be_blank
end
it "fails if at least one variant is not available for the given quantity" do
purchase = create(:purchase, link: @product, variant_attributes: [@variant1, @variant2], quantity: 3)
expect(purchase.errors.full_messages).to include "You have chosen a quantity that exceeds what is available."
end
it "fails if at least one variant is unavailable because it is deleted" do
@variant2.mark_deleted!
purchase = create(:purchase, link: @product, variant_attributes: [@variant1, @variant2])
expect(purchase.errors.full_messages).to include "Sold out, please go back and pick another option."
end
it "fails if at least one variant is unavailable because it is sold out" do
create(:purchase, link: @product, variant_attributes: [@variant1], quantity: 2)
purchase = create(:purchase, link: @product, variant_attributes: [@variant1, @variant2])
expect(purchase.errors.full_messages).to include "Sold out, please go back and pick another option."
end
context "when original_variant_attributes is set" do
it "succeeds even when an original variant is sold out or marked deleted" do
purchase = create(:purchase, link: @product, variant_attributes: [@variant1, @variant2], quantity: 2)
@variant1.update!(max_purchase_count: 2)
@variant2.mark_deleted!
purchase.original_variant_attributes = [@variant1, @variant2]
purchase.save
expect(purchase.errors).to be_blank
end
it "fails when at least one new variant is sold out" do
variant3 = create(:variant, variant_category: @variant_category, max_purchase_count: 1)
create(:purchase, link: @product, variant_attributes: [variant3])
purchase = build(:purchase, link: @product, variant_attributes: [@variant1, @variant2, variant3])
purchase.original_variant_attributes = [@variant1, @variant2]
purchase.save
expect(purchase.errors.full_messages).to include "Sold out, please go back and pick another option."
end
end
end
describe "#as_json" do
before do
@purchase = create(:purchase, chargeback_date: 1.minute.ago, full_name: "Sahil Lavingia", email: "sahil@gumroad.com")
end
it "has the right keys" do
%i[price gumroad_fee seller_id link_name timestamp daystamp chargedback paypal_refund_expired].each do |key|
expect(@purchase.as_json.key?(key)).to be(true)
end
expect(@purchase.as_json[:email]).to eq "sahil@gumroad.com"
expect(@purchase.as_json[:full_name]).to eq "Sahil Lavingia"
end
it "returns paypal_refund_expired as true for unrefundable PayPal purchases and false for others" do
@unrefundable_paypal_purchase = create(:purchase, created_at: 7.months.ago, card_type: CardType::PAYPAL)
expect(@purchase.as_json[:paypal_refund_expired]).to be(false)
expect(@unrefundable_paypal_purchase.as_json[:paypal_refund_expired]).to be(true)
end
it "has the right seller_id" do
seller = @purchase.link.user
expect(@purchase.as_json[:seller_id]).to eq(ObfuscateIds.encrypt(seller.id))
end
it "has the right gumroad_fee" do
expect(@purchase.as_json[:gumroad_fee]).to eq(93) # 10c (10%) + 50c + 3c (2.9% cc fee) + 30c (fixed cc fee)
@purchase.update!(price_cents: 500)
@purchase.send(:calculate_fees)
expect(@purchase.as_json[:gumroad_fee]).to eq(145) # 50c (10%) + 50c + 15c (2.9% cc fee) + 30c (fixed cc fee)
end
it "has the purchaser_id if one exists" do
expect(@purchase.as_json.key?(:purchaser_id)).to be(false)
purchaser = create(:user)
@purchase.update!(purchaser_id: purchaser.id)
expect(@purchase.as_json[:purchaser_id]).to eq(purchaser.external_id)
end
it "has the right daystamp" do
day = 1.day.ago
@purchase.seller.update_attribute(:timezone, "Pacific Time (US & Canada)")
@purchase.update_attribute(:created_at, day)
expect(@purchase.as_json[:daystamp]).to eq day.in_time_zone("Pacific Time (US & Canada)").to_fs(:long_formatted_datetime)
end
it "has the right iso2 code for the country" do
@purchase.update_attribute(:country, "United States")
expect(@purchase.as_json[:country_iso2]).to eq "US"
end
it "performs a safe country code lookup for a GeoIp2 country that isn't found in IsoCountryCodes" do
@purchase.update!(country: "South Korea")
expect(@purchase.as_json[:country]).to eq("South Korea")
expect(@purchase.as_json[:country_iso2]).to eq "KR"
end
it "returns country and state as is if they are set" do
@purchase.update!(country: "United States", state: "CA")
expect(@purchase.as_json[:country]).to eq("United States")
expect(@purchase.as_json[:state]).to eq("CA")
end
it "returns country and state based on ip_address if they don't exist" do
@purchase.update!(ip_address: "199.241.200.176")
expect(@purchase.country).to eq(nil)
expect(@purchase.state).to eq(nil)
expect(@purchase.as_json[:country]).to eq("United States")
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/ethiopia_bank_account_spec.rb | spec/models/ethiopia_bank_account_spec.rb | # frozen_string_literal: true
describe EthiopiaBankAccount do
describe "#bank_account_type" do
it "returns ET" do
expect(create(:ethiopia_bank_account).bank_account_type).to eq("ET")
end
end
describe "#country" do
it "returns ET" do
expect(create(:ethiopia_bank_account).country).to eq("ET")
end
end
describe "#currency" do
it "returns etb" do
expect(create(:ethiopia_bank_account).currency).to eq("etb")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:ethiopia_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAAETETXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:ethiopia_bank_account, account_number_last_four: "2345").account_number_visual).to eq("******2345")
end
end
describe "#validate_account_number" do
it "allows records that match the required account number regex" do
expect(build(:ethiopia_bank_account)).to be_valid
expect(build(:ethiopia_bank_account, account_number: "0000000012345678")).to be_valid
expect(build(:ethiopia_bank_account, account_number: "ET00000012345678")).to be_valid
et_bank_account = build(:ethiopia_bank_account, account_number: "000000001234")
expect(et_bank_account).to_not be_valid
expect(et_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
et_bank_account = build(:ethiopia_bank_account, account_number: "ET0000001234")
expect(et_bank_account).to_not be_valid
expect(et_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
et_bank_account = build(:ethiopia_bank_account, account_number: "00000000123456789")
expect(et_bank_account).to_not be_valid
expect(et_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
et_bank_account = build(:ethiopia_bank_account, account_number: "ET000000123456789")
expect(et_bank_account).to_not be_valid
expect(et_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/customer_email_info_spec.rb | spec/models/customer_email_info_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CustomerEmailInfo do
describe ".find_or_initialize_for_charge" do
let(:purchase) { create(:purchase) }
let(:charge) { create(:charge, purchases: [purchase]) }
context "when the record doesn't exist" do
it "initializes a new record" do
email_info = CustomerEmailInfo.find_or_initialize_for_charge(
charge_id: charge.id,
email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD
)
expect(email_info.persisted?).to be(false)
expect(email_info.email_name).to eq(SendgridEventInfo::RECEIPT_MAILER_METHOD)
expect(email_info.charge_id).to eq(charge.id)
expect(email_info.purchase_id).to be(nil)
end
end
context "when the record exists" do
let!(:expected_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 "finds the existing record" do
email_info = CustomerEmailInfo.find_or_initialize_for_charge(
charge_id: charge.id,
email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD
)
expect(email_info).to eq(expected_email_info)
expect(email_info.charge_id).to eq(charge.id)
expect(email_info.purchase_id).to be(nil)
end
end
end
describe ".find_or_initialize_for_purchase" do
let(:purchase) { create(:purchase) }
context "when the record doesn't exist" do
it "initializes a new record" do
email_info = CustomerEmailInfo.find_or_initialize_for_purchase(
purchase_id: purchase.id,
email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD
)
expect(email_info.persisted?).to be(false)
expect(email_info.email_name).to eq(SendgridEventInfo::RECEIPT_MAILER_METHOD)
expect(email_info.purchase_id).to eq(purchase.id)
expect(email_info.charge_id).to be(nil)
end
end
context "when the record exists" do
let!(:expected_email_info) do
create(:customer_email_info, email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD, purchase: purchase)
end
it "finds the existing record" do
email_info = CustomerEmailInfo.find_or_initialize_for_purchase(
purchase_id: purchase.id,
email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD
)
expect(email_info).to eq(expected_email_info)
expect(email_info.purchase_id).to eq(purchase.id)
expect(email_info.charge_id).to be(nil)
end
end
end
describe "state transitions" do
it "transitions to sent" do
email_info = create(:customer_email_info)
expect(email_info.email_name).to eq "receipt"
email_info.update_attribute(:delivered_at, Time.current)
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(:customer_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 sent" do
email_info = create(:customer_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
end
describe "#mark_bounced!" do
it "attempts to unsubscribe the buyer of the purchase" do
email_info = create(:customer_email_info_delivered)
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/sales_related_products_info_spec.rb | spec/models/sales_related_products_info_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SalesRelatedProductsInfo do
describe ".find_or_create_info" do
let(:sales_related_products_info) { create(:sales_related_products_info) }
context "when the info exists" do
it "returns the info" do
expect(described_class.find_or_create_info(sales_related_products_info.smaller_product_id, sales_related_products_info.larger_product_id)).to eq(sales_related_products_info)
expect(described_class.find_or_create_info(sales_related_products_info.larger_product_id, sales_related_products_info.smaller_product_id)).to eq(sales_related_products_info)
end
end
context "when the info does not exist" do
let(:product1) { create(:product) }
let(:product2) { create(:product) }
it "creates the info" do
expect do
described_class.find_or_create_info(product1.id, product2.id)
end.to change(described_class, :count).by(1)
sales_related_products_info = described_class.last
expect(sales_related_products_info.smaller_product_id).to eq(product1.id)
expect(sales_related_products_info.larger_product_id).to eq(product2.id)
end
end
end
describe ".update_sales_counts" do
it "upserts and increments/decrements the sales counts" do
products = create_list(:product, 4)
# use products[1] to check that the method handles smaller and larger ids correctly
create(:sales_related_products_info, smaller_product: products[1], larger_product: products[2], sales_count: 5)
described_class.update_sales_counts(product_id: products[1].id, related_product_ids: products.map(&:id) - [products[1].id], increment: true)
# created records
expect(described_class.find_by(smaller_product: products[0], larger_product: products[1]).sales_count).to eq(1)
expect(described_class.find_by(smaller_product: products[1], larger_product: products[3]).sales_count).to eq(1)
# updated record
expect(described_class.find_by(smaller_product: products[1], larger_product: products[2]).sales_count).to eq(6)
products << create(:product)
described_class.update_sales_counts(product_id: products[1].id, related_product_ids: products.map(&:id) - [products[1].id], increment: false)
# updated records
expect(described_class.find_by(smaller_product: products[0], larger_product: products[1]).sales_count).to eq(0)
expect(described_class.find_by(smaller_product: products[1], larger_product: products[2]).sales_count).to eq(5)
expect(described_class.find_by(smaller_product: products[1], larger_product: products[3]).sales_count).to eq(0)
# created record
expect(described_class.find_by(smaller_product: products[1], larger_product: products[4]).sales_count).to eq(0)
end
end
describe ".related_products" do
it "returns related products sorted in descending order by sales count" do
products = create_list(:product, 6)
create(:sales_related_products_info, smaller_product: products[0], larger_product: products[3], sales_count: 7)
create(:sales_related_products_info, smaller_product: products[1], larger_product: products[3], sales_count: 3)
create(:sales_related_products_info, smaller_product: products[1], larger_product: products[2], sales_count: 7)
create(:sales_related_products_info, smaller_product: products[2], larger_product: products[5], sales_count: 9)
create(:sales_related_products_info, smaller_product: products[2], larger_product: products[3], sales_count: 5)
create(:sales_related_products_info, smaller_product: products[2], larger_product: products[4], sales_count: 6)
rebuild_srpis_cache
# products[1] is first because it's related to products[3] (sales_count: 3) + products[2] (sales_count: 7) => 10
# products[5] is second because it's related to products[2] (sales_count: 9) => 9
# products[0] is third because it's related to products[3] (sales_count: 7) => 7
# products[4] is fourth because it's related to products[2] (sales_count: 6) => 6
expect(described_class.related_products([products[2].id, products[3].id])).to eq([
products[1], products[5], products[0], products[4]
])
# products[5] is first because it's related to products[2] (sales_count: 9) => 9
# products[1] is second because it's related to products[2] (sales_count: 7) => 7
# products[4] is third because it's related to products[2] (sales_count: 6) => 6
expect(described_class.related_products([products[2].id], limit: 3)).to eq([
products[5], products[1], products[4]
])
# product with no related products
expect(described_class.related_products([0])).to eq([])
# empty product_ids
expect(described_class.related_products([])).to eq([])
end
it "validates the arguments" do
expect do
described_class.related_products([1, "bad string", 2])
end.to raise_error(ArgumentError, /must be an array of integers/)
expect do
described_class.related_products([1], limit: "bad string")
end.to raise_error(ArgumentError, /must an integer/)
end
end
describe ".related_product_ids_and_sales_counts" do
it "validates the arguments" do
expect do
described_class.related_product_ids_and_sales_counts("bad string")
end.to raise_error(ArgumentError, "product_id must be an integer")
expect do
described_class.related_product_ids_and_sales_counts(1, limit: "bad string")
end.to raise_error(ArgumentError, "limit must be an integer")
end
it "returns a hash of related products and sales counts" do
# [ [smaller_product_id, larger_product_id, sales_count], ...]
data = [
[1, 2, 12],
[1, 3, 13],
[1, 4, 100],
[1, 5, 15],
[2, 4, 24],
[3, 4, 34],
[4, 5, 45],
[4, 6, 46],
[4, 7, 47],
]
data.each { described_class.insert!({ smaller_product_id: _1[0], larger_product_id: _1[1], sales_count: _1[2] }) }
result = SalesRelatedProductsInfo.related_product_ids_and_sales_counts(4, limit: 3)
expect(result).to eq(
1 => 100,
7 => 47,
6 => 46,
)
end
end
describe "validation" do
let!(:smaller_product) { create(:product) }
let!(:larger_product) { create(:product) }
context "when smaller_product_id is greater than larger_product_id" do
it "adds an error" do
expect(build(:sales_related_products_info, smaller_product: larger_product, larger_product: smaller_product)).not_to be_valid
end
end
context "when smaller_product_id is equal to larger_product_id" do
it "adds an error" do
expect(build(:sales_related_products_info, smaller_product:, larger_product: smaller_product)).not_to be_valid
end
end
context "when smaller_product_id is less than larger_product_id" do
it "doesn't add an error" do
expect(build(:sales_related_products_info, smaller_product:, larger_product:)).to be_valid
end
end
end
describe "scopes" do
describe ".for_product_id" do
it "returns matching records for a product id" do
record = create(:sales_related_products_info)
create(:sales_related_products_info)
expect(described_class.for_product_id(record.smaller_product_id)).to eq([record])
expect(described_class.for_product_id(record.larger_product_id)).to eq([record])
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/gabon_bank_account_spec.rb | spec/models/gabon_bank_account_spec.rb | # frozen_string_literal: true
describe GabonBankAccount do
describe "#bank_account_type" do
it "returns GA" do
expect(create(:gabon_bank_account).bank_account_type).to eq("GA")
end
end
describe "#country" do
it "returns GA" do
expect(create(:gabon_bank_account).country).to eq("GA")
end
end
describe "#currency" do
it "returns xaf" do
expect(create(:gabon_bank_account).currency).to eq("xaf")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:gabon_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAAGAGAXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:gabon_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789")
end
end
describe "#validate_bank_code" do
it "allows 8 or 11 characters only" do
expect(build(:gabon_bank_account, bank_number: "AAAAGAGA")).to be_valid # 8 chars
expect(build(:gabon_bank_account, bank_number: "AAAAGAGAXXX")).to be_valid # 11 chars
expect(build(:gabon_bank_account, bank_number: "AAAAGAG")).not_to be_valid # too short
expect(build(:gabon_bank_account, bank_number: "AAAAGAGAXXXX")).not_to be_valid # too long
end
end
describe "#validate_account_number" do
it "allows records that match the required account number regex" do
expect(build(:gabon_bank_account)).to be_valid
expect(build(:gabon_bank_account, account_number: "00012345678910111121314")).to be_valid
ga_bank_account = build(:gabon_bank_account, account_number: "GA012345678910111121314")
expect(ga_bank_account).to_not be_valid
expect(ga_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
ga_bank_account = build(:gabon_bank_account, account_number: "0000123456789012345678")
expect(ga_bank_account).to_not be_valid
expect(ga_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
ga_bank_account = build(:gabon_bank_account, account_number: "000012345678901234567890")
expect(ga_bank_account).to_not be_valid
expect(ga_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/event_spec.rb | spec/models/event_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Event do
describe "post view" do
before do
link = create(:product, name: "product name")
@post = create(:installment, link:)
@post_view_event = create(:post_view_event)
@installment_event = create(:installment_event, event_id: @post_view_event.id, installment_id: @post.id)
end
it "creates the post_view event with the right values" do
expect(@post_view_event.event_name).to eq "post_view"
expect(@installment_event.installment_id).to eq @post.id
expect(@installment_event.event_id).to eq @post_view_event.id
end
it "is counted for in the scopes" do
expect(Event.post_view.count).to eq 1
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/bhutan_bank_account_spec.rb | spec/models/bhutan_bank_account_spec.rb | # frozen_string_literal: true
describe BhutanBankAccount do
describe "#bank_account_type" do
it "returns BT" do
expect(create(:bhutan_bank_account).bank_account_type).to eq("BT")
end
end
describe "#country" do
it "returns BT" do
expect(create(:bhutan_bank_account).country).to eq("BT")
end
end
describe "#currency" do
it "returns btn" do
expect(create(:bhutan_bank_account).currency).to eq("btn")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:bhutan_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAABTBTXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:bhutan_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
expect(build(:bhutan_bank_account)).to be_valid
expect(build(:bhutan_bank_account, account_number: "0000123456789")).to be_valid
expect(build(:bhutan_bank_account, account_number: "0")).to be_valid
expect(build(:bhutan_bank_account, account_number: "00001234567891011")).to be_valid
bt_bank_account = build(:bhutan_bank_account, account_number: "0000123456789101112")
expect(bt_bank_account).to_not be_valid
expect(bt_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/mailer_info_spec.rb | spec/models/mailer_info_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe MailerInfo do
describe ".header_name" do
it "formats valid header names" do
expect(described_class.header_name(:email_provider)).to eq("X-GUM-Email-Provider")
expect(described_class.header_name(:mailer_class)).to eq("X-GUM-Mailer-Class")
end
it "raises error for invalid header names" do
expect { described_class.header_name(:invalid) }.to raise_error(ArgumentError, /Invalid header field/)
end
end
describe ".encrypt" do
it "delegates to Encryption" do
allow(MailerInfo::Encryption).to receive(:encrypt).with("test").and_return("encrypted")
expect(described_class.encrypt("test")).to eq("encrypted")
end
end
describe ".decrypt" do
it "delegates to Encryption" do
allow(MailerInfo::Encryption).to receive(:decrypt).with("encrypted").and_return("test")
expect(described_class.decrypt("encrypted")).to eq("test")
end
end
describe ".parse_resend_webhook_header" do
let(:headers) do
[
{ "name" => "X-GUM-Environment", "value" => "encrypted_env" },
{ "name" => "X-GUM-Mailer-Class", "value" => "encrypted_class" }
]
end
it "finds and decrypts header value" do
allow(described_class).to receive(:decrypt).with("encrypted_class").and_return("TestMailer")
expect(described_class.parse_resend_webhook_header(headers, :mailer_class)).to eq("TestMailer")
end
it "returns nil for missing header" do
expect(described_class.parse_resend_webhook_header(headers, :workflow_ids)).to be_nil
end
it "returns nil for nil headers" do
expect(described_class.parse_resend_webhook_header(nil, :mailer_class)).to be_nil
end
end
describe ".random_email_provider" do
it "delegates to Router" do
allow(MailerInfo::Router).to receive(:determine_email_provider).with(:gumroad).and_return("sendgrid")
expect(described_class.random_email_provider(:gumroad)).to eq("sendgrid")
end
end
describe ".random_delivery_method_options" do
let(:domain) { :gumroad }
let(:seller) { nil }
it "gets provider from Router and delegates to DeliveryMethod" do
allow(described_class).to receive(:random_email_provider).with(domain).and_return("sendgrid")
allow(MailerInfo::DeliveryMethod).to receive(:options).with(
domain: domain,
email_provider: "sendgrid",
seller: seller
).and_return({ address: "smtp.sendgrid.net" })
expect(described_class.random_delivery_method_options(domain:, seller:)).to eq({ address: "smtp.sendgrid.net" })
end
end
describe ".default_delivery_method_options" do
it "uses SendGrid as provider" do
allow(MailerInfo::DeliveryMethod).to receive(:options).with(
domain: :gumroad,
email_provider: MailerInfo::EMAIL_PROVIDER_SENDGRID
).and_return({ address: "smtp.sendgrid.net" })
expect(described_class.default_delivery_method_options(domain: :gumroad)).to eq({ address: "smtp.sendgrid.net" })
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_cached_value_spec.rb | spec/models/product_cached_value_spec.rb | # frozen_string_literal: true
describe ProductCachedValue do
describe "#create" do
it "is valid with a product" do
expect(build(:product_cached_value, product: create(:product))).to be_valid
end
it "is invalid without a product" do
expect(build(:product_cached_value, product: nil)).to_not be_valid
end
end
describe "#expire!" do
let(:product_cached_value) { create(:product_cached_value) }
it "sets expired to true" do
expect(product_cached_value.expired).to eq(false)
product_cached_value.expire!
expect(product_cached_value.expired).to eq(true)
end
end
describe "#assign_cached_values" do
let(:product_cached_value) { product.product_cached_values.create! }
context "when the product resembles a product" do
let(:product) { create(:product) }
before do
allow_any_instance_of(Link).to receive(:successful_sales_count).and_return(1.00)
allow_any_instance_of(Link).to receive(:remaining_for_sale_count).and_return(2.00)
allow_any_instance_of(Link).to receive(:total_usd_cents).and_return(100)
end
it "populates the attributes" do
expect(product_cached_value.successful_sales_count).to eq(1.00)
expect(product_cached_value.remaining_for_sale_count).to eq(2.00)
expect(product_cached_value.monthly_recurring_revenue).to eq(0)
expect(product_cached_value.revenue_pending).to eq(0)
expect(product_cached_value.total_usd_cents).to eq(100)
end
end
context "when the product resembles a membership" do
let(:product) { create(:product, duration_in_months: 1) }
before do
allow_any_instance_of(Link).to receive(:successful_sales_count).and_return(3.00)
allow_any_instance_of(Link).to receive(:remaining_for_sale_count).and_return(4.00)
allow_any_instance_of(Link).to receive(:monthly_recurring_revenue).and_return(9_999_999.99)
allow_any_instance_of(Link).to receive(:pending_balance).and_return(6)
allow_any_instance_of(Link).to receive(:total_usd_cents).and_return(200)
end
it "populates the attributes" do
expect(product_cached_value.successful_sales_count).to eq(3.00)
expect(product_cached_value.remaining_for_sale_count).to eq(4.00)
expect(product_cached_value.monthly_recurring_revenue).to eq(9_999_999.99)
expect(product_cached_value.revenue_pending).to eq(6)
expect(product_cached_value.total_usd_cents).to eq(200)
end
end
end
describe "scopes" do
before do
2.times { create(:product_cached_value) }
create(:product_cached_value, :expired)
end
describe ".fresh" do
it "returns an un-expired collection" do
expect(described_class.fresh.count).to eq(2)
end
end
describe ".expired" do
it "returns an expired collection" do
expect(described_class.expired.count).to eq(1)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/senegal_bank_account_spec.rb | spec/models/senegal_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SenegalBankAccount do
describe "#bank_account_type" do
it "returns senegal" do
expect(create(:senegal_bank_account).bank_account_type).to eq("SN")
end
end
describe "#country" do
it "returns SN" do
expect(create(:senegal_bank_account).country).to eq("SN")
end
end
describe "#currency" do
it "returns xof" do
expect(create(:senegal_bank_account).currency).to eq("xof")
end
end
describe "#routing_number" do
it "returns nil" do
expect(create(:senegal_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(:senegal_bank_account, account_number_last_four: "3035").account_number_visual).to eq("******3035")
end
end
describe "#validate_account_number" do
it "allows records that match the required account number regex" do
expect(build(:senegal_bank_account)).to be_valid
expect(build(:senegal_bank_account, account_number: "SN08SN0100152000048500003035")).to be_valid
expect(build(:senegal_bank_account, account_number: "SN62370400440532013001")).to be_valid
sn_bank_account = build(:senegal_bank_account, account_number: "012345678")
expect(sn_bank_account).to_not be_valid
expect(sn_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
sn_bank_account = build(:senegal_bank_account, account_number: "ABCDEFGHIJKLMNOPQRSTUV")
expect(sn_bank_account).to_not be_valid
expect(sn_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
sn_bank_account = build(:senegal_bank_account, account_number: "SN08SN01001520000485000030355")
expect(sn_bank_account).to_not be_valid
expect(sn_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
sn_bank_account = build(:senegal_bank_account, account_number: "SN08SN010015200004850")
expect(sn_bank_account).to_not be_valid
expect(sn_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/wishlist_product_spec.rb | spec/models/wishlist_product_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe WishlistProduct do
describe "validations" do
let(:wishlist) { create(:wishlist) }
let(:product) { create(:product) }
let(:wishlist_product) { described_class.new(wishlist:, product:) }
it "validates the product is unique in the wishlist" do
wishlist_product.save!
wishlist_product2 = described_class.new(wishlist:, product: wishlist_product.product)
expect(wishlist_product2).to be_invalid
expect(wishlist_product2.errors.full_messages.first).to eq "Product has already been taken"
end
context "for a non recurring product" do
it "validates recurrence is blank" do
wishlist_product.recurrence = BasePrice::Recurrence::MONTHLY
expect(wishlist_product).to be_invalid
expect(wishlist_product.errors.full_messages.first).to eq "Recurrence must be blank"
wishlist_product.recurrence = nil
expect(wishlist_product).to be_valid
end
end
context "for a recurring product" do
let(:product) { create(:product, :is_subscription) }
it "validates recurrence is a known value" do
wishlist_product.recurrence = BasePrice::Recurrence::MONTHLY
expect(wishlist_product).to be_valid
wishlist_product.recurrence = nil
expect(wishlist_product).to be_invalid
expect(wishlist_product.errors.full_messages.first).to eq "Recurrence is not included in the list"
wishlist_product.recurrence = "unknown"
expect(wishlist_product).to be_invalid
expect(wishlist_product.errors.full_messages.first).to eq "Recurrence is not included in the list"
end
it "allows different recurrence in the same wishlist" do
product = create(:subscription_product)
wishlist_product.update!(recurrence: BasePrice::Recurrence::MONTHLY)
wishlist_product2 = described_class.new(wishlist:, product:, recurrence: BasePrice::Recurrence::YEARLY)
expect(wishlist_product2).to be_valid
end
end
context "when the product does not support quantity" do
it "validates the quantity is always 1" do
wishlist_product.quantity = 4
expect(wishlist_product).to be_invalid
expect(wishlist_product.errors.full_messages.first).to eq "Quantity must be equal to 1"
wishlist_product.quantity = 1
expect(wishlist_product).to be_valid
end
end
context "when the product supports quantity" do
let(:product) { create(:product, :is_physical) }
it "validates the quantity is greater than zero" do
wishlist_product.quantity = 4
expect(wishlist_product).to be_valid
wishlist_product.quantity = -1
expect(wishlist_product).to be_invalid
expect(wishlist_product.errors.full_messages.first).to eq "Quantity must be greater than 0"
end
end
context "when the product is buy-only" do
it "validates rent is not set" do
wishlist_product.rent = true
expect(wishlist_product).to be_invalid
expect(wishlist_product.errors.full_messages.first).to eq "Rent must be blank"
wishlist_product.rent = false
expect(wishlist_product).to be_valid
end
end
context "when the product is rent-only" do
let(:product) { create(:product, purchase_type: :rent_only, rental_price_cents: 100) }
it "validates rent is set" do
wishlist_product.rent = false
expect(wishlist_product).to be_invalid
expect(wishlist_product.errors.full_messages.first).to eq "Rent can't be blank"
wishlist_product.rent = true
expect(wishlist_product).to be_valid
end
end
context "when the product is buy-or-rent" do
let(:product) { create(:product, purchase_type: :buy_and_rent, rental_price_cents: 100) }
it "allows rent to be set or unset" do
wishlist_product.rent = false
expect(wishlist_product).to be_valid
wishlist_product.rent = true
expect(wishlist_product).to be_valid
end
end
context "when the product is versioned" do
let(:product) { create(:product_with_digital_versions) }
it "validates variant is set" do
expect(wishlist_product).to_not be_valid
expect(wishlist_product.errors.full_messages.first).to eq("Wishlist product must have variant specified for versioned product")
wishlist_product.variant = product.alive_variants.first
expect(wishlist_product).to be_valid
end
it "allows different variants in the same wishlist" do
wishlist_product.update!(variant: product.variants.first)
wishlist_product2 = described_class.new(wishlist:, product:, variant: product.variants.last)
expect(wishlist_product2).to be_valid
end
end
context "when the variant doesn't belong to the product" do
before do
wishlist_product.variant = create(:variant)
end
it "adds an error" do
expect(wishlist_product).to_not be_valid
expect(wishlist_product.errors.full_messages.first).to eq("The wishlist product's variant must belong to its product")
end
end
context "when adding products to a wishlist" do
it "allows adding products up to the limit" do
create_list(:wishlist_product, WishlistProduct::WISHLIST_PRODUCT_LIMIT - 1, wishlist:)
new_product = build(:wishlist_product, wishlist:)
expect(new_product).to be_valid
end
it "prevents adding products beyond the limit" do
create_list(:wishlist_product, WishlistProduct::WISHLIST_PRODUCT_LIMIT, wishlist:)
new_product = build(:wishlist_product, wishlist:)
expect(new_product).to be_invalid
expect(new_product.errors.full_messages.first).to eq "A wishlist can have at most #{WishlistProduct::WISHLIST_PRODUCT_LIMIT} products"
end
it "allows adding products after deleting existing ones" do
create_list(:wishlist_product, WishlistProduct::WISHLIST_PRODUCT_LIMIT, wishlist:)
wishlist.wishlist_products.first.mark_deleted!
new_product = build(:wishlist_product, wishlist:)
expect(new_product).to be_valid
end
end
end
describe ".available_to_buy" do
let!(:valid_wishlist_product) { create(:wishlist_product) }
it "filters out products with a suspended user" do
create(:wishlist_product, product: create(:product, user: create(:tos_user)))
expect(described_class.available_to_buy).to contain_exactly valid_wishlist_product
end
it "filters out unpublished products" do
create(:wishlist_product, product: create(:product, purchase_disabled_at: Time.current))
expect(described_class.available_to_buy).to contain_exactly valid_wishlist_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/iceland_bank_account_spec.rb | spec/models/iceland_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe IcelandBankAccount do
describe "#bank_account_type" do
it "returns IS" do
expect(create(:iceland_bank_account).bank_account_type).to eq("IS")
end
end
describe "#country" do
it "returns IS" do
expect(create(:iceland_bank_account).country).to eq("IS")
end
end
describe "#currency" do
it "returns eur" do
expect(create(:iceland_bank_account).currency).to eq("eur")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:iceland_bank_account, account_number_last_four: "0339").account_number_visual).to eq("IS******0339")
end
end
describe "#validate_account_number" do
it "validates the IBAN format" do
expect(build(:iceland_bank_account)).to be_valid
expect(build(:iceland_bank_account, account_number: "IS1401592600765455107303")).not_to be_valid
expect(build(:iceland_bank_account, account_number: "IS14015926007654551073033911")).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/blocked_object_spec.rb | spec/models/blocked_object_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BlockedObject do
describe ".block!" do
describe "when blocked object doesn't exist" do
it "creates a new blocked object record" do
count = BlockedObject.count
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], "123.456.789.0", nil, expires_in: 1.hour)
expect(BlockedObject.all.count).to eq count + 1
expect(BlockedObject.find_by(object_value: "123.456.789.0").blocked?).to be(true)
end
end
describe "when blocked object exists" do
it "updates the existing record" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], "789.123.456.0", nil, expires_in: 1.hour)
BlockedObject.unblock!("789.123.456.0")
count = BlockedObject.count
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], "789.123.456.0", nil, expires_in: 1.hour)
expect(BlockedObject.count).to eq count
end
end
context "when :expires_in is present" do
it "blocks and sets the expiration date appropriately" do
count = BlockedObject.active.count
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], "789.124.456.0", nil, expires_in: 3.days)
expect(BlockedObject.active.count).to eq count + 1
expect(BlockedObject.last.expires_at).to_not be(nil)
end
it "is not active after the expiration date" do
count = BlockedObject.active.count
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], "789.125.456.0", nil, expires_in: -3.days)
expect(BlockedObject.active.count).to eq count
end
end
end
describe "#unblock!" do
let(:blocked_object) do
ip_address = "157.45.09.212"
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], ip_address, nil, expires_in: 1.hour)
BlockedObject.find_by(object_value: ip_address)
end
it "unblocks the blocked object" do
expect(blocked_object.blocked?).to be(true)
blocked_object.unblock!
expect(blocked_object.blocked?).to be(false)
end
end
describe ".unblock!" do
describe "when it isn't there" do
it "fails silently" do
expect(BlockedObject.find_by(object_value: "lol")).to be(nil)
expect(-> { BlockedObject.unblock!("lol") }).to_not raise_error
end
end
describe "when it is there" do
it "unblocks" do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], "456.789.123.0", nil, expires_in: 1.hour)
expect(BlockedObject.find_by(object_value: "456.789.123.0").blocked?).to be(true)
BlockedObject.unblock!("456.789.123.0")
expect(BlockedObject.find_by(object_value: "456.789.123.0").blocked?).to be(false)
end
end
end
describe ".charge_processor_fingerprint" do
let(:email) { "paypal@example.com" }
before do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], email, nil)
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:charge_processor_fingerprint], email, nil)
end
it "returns the list of blocked objects with object_type 'charge_processor_fingerprint'" do
expect(BlockedObject.charge_processor_fingerprint.count).to eq 1
blocked_object = BlockedObject.charge_processor_fingerprint.first
expect(blocked_object.object_type).to eq BLOCKED_OBJECT_TYPES[:charge_processor_fingerprint]
expect(blocked_object.object_value).to eq email
end
end
describe "expires_at validation" do
context "when object_type is ip_address" do
let(:object_type) { BLOCKED_OBJECT_TYPES[:ip_address] }
let(:object_value) { "192.168.1.1" }
context "when blocked_at is present" do
it "is invalid without expires_at" do
blocked_object = BlockedObject.new(
object_type: object_type,
object_value: object_value,
blocked_at: Time.current
)
expect(blocked_object).not_to be_valid
expect(blocked_object.errors[:expires_at]).to include("can't be blank")
end
it "is valid with expires_at" do
blocked_object = BlockedObject.new(
object_type: object_type,
object_value: object_value,
blocked_at: Time.current,
expires_at: Time.current + 1.hour
)
expect(blocked_object).to be_valid
end
end
context "when blocked_at is nil" do
it "is valid without expires_at" do
blocked_object = BlockedObject.new(
object_type: object_type,
object_value: object_value,
blocked_at: nil,
expires_at: nil
)
expect(blocked_object).to be_valid
end
it "is valid with expires_at" do
blocked_object = BlockedObject.new(
object_type: object_type,
object_value: object_value,
blocked_at: nil,
expires_at: Time.current + 1.hour
)
expect(blocked_object).to be_valid
end
end
end
context "when object_type is NOT ip_address" do
let(:object_type) { BLOCKED_OBJECT_TYPES[:email] }
let(:object_value) { "test@example.com" }
context "when blocked_at is present" do
it "is valid without expires_at" do
blocked_object = BlockedObject.new(
object_type: object_type,
object_value: object_value,
blocked_at: Time.current,
expires_at: nil
)
expect(blocked_object).to be_valid
end
it "is valid with expires_at" do
blocked_object = BlockedObject.new(
object_type: object_type,
object_value: object_value,
blocked_at: Time.current,
expires_at: Time.current + 1.hour
)
expect(blocked_object).to be_valid
end
end
context "when blocked_at is nil" do
it "is valid without expires_at" do
blocked_object = BlockedObject.new(
object_type: object_type,
object_value: object_value,
blocked_at: nil,
expires_at: nil
)
expect(blocked_object).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/vietnam_bank_account_spec.rb | spec/models/vietnam_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe VietnamBankAccount do
describe "#bank_account_type" do
it "returns Vietnam" do
expect(create(:vietnam_bank_account).bank_account_type).to eq("VN")
end
end
describe "#country" do
it "returns VN" do
expect(create(:vietnam_bank_account).country).to eq("VN")
end
end
describe "#currency" do
it "returns vnd" do
expect(create(:vietnam_bank_account).currency).to eq("vnd")
end
end
describe "#routing_number" do
it "returns valid for 8 characters" do
ba = create(:vietnam_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("01101100")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:vietnam_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789")
end
end
describe "#validate_bank_code" do
it "allows 8 numbers only" do
expect(build(:vietnam_bank_account, bank_code: "01101100")).to be_valid
expect(build(:vietnam_bank_account, bank_code: "AAAATWTX")).not_to be_valid
expect(build(:vietnam_bank_account, bank_code: "0110110")).not_to be_valid
expect(build(:vietnam_bank_account, bank_code: "011011000")).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/kenya_bank_account_spec.rb | spec/models/kenya_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe KenyaBankAccount do
describe "#bank_account_type" do
it "returns KE" do
expect(create(:kenya_bank_account).bank_account_type).to eq("KE")
end
end
describe "#country" do
it "returns KE" do
expect(create(:kenya_bank_account).country).to eq("KE")
end
end
describe "#currency" do
it "returns kes" do
expect(create(:kenya_bank_account).currency).to eq("kes")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:kenya_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("BARCKENXMDR")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:kenya_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789")
end
end
describe "#validate_bank_code" do
it "allows 8 to 11 characters only" do
expect(build(:kenya_bank_account, bank_code: "BARCKENX")).to be_valid
expect(build(:kenya_bank_account, bank_code: "BARCKENXMDR")).to be_valid
expect(build(:kenya_bank_account, bank_code: "BARCKEN")).not_to be_valid
expect(build(:kenya_bank_account, bank_code: "BARCKENXMDRX")).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/el_salvador_bank_account_spec.rb | spec/models/el_salvador_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ElSalvadorBankAccount do
describe "#bank_account_type" do
it "returns SV" do
expect(create(:el_salvador_bank_account).bank_account_type).to eq("SV")
end
end
describe "#country" do
it "returns SV" do
expect(create(:el_salvador_bank_account).country).to eq("SV")
end
end
describe "#currency" do
it "returns usd" do
expect(create(:el_salvador_bank_account).currency).to eq("usd")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:el_salvador_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAASVS1XXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:el_salvador_bank_account, account_number_last_four: "7890").account_number_visual).to eq("******7890")
end
end
describe "#validate_bank_code" do
it "allows 8 to 11 characters only" do
expect(build(:el_salvador_bank_account, bank_code: "AAAASVS1")).to be_valid
expect(build(:el_salvador_bank_account, bank_code: "AAAASVS1XXX")).to be_valid
expect(build(:el_salvador_bank_account, bank_code: "AAAASV")).not_to be_valid
expect(build(:el_salvador_bank_account, bank_code: "AAAASVS1XXXX")).not_to be_valid
end
end
describe "#validate_account_number" do
it "allows only valid format" do
expect(build(:el_salvador_bank_account, account_number: "SV44BCIE12345678901234567890")).to be_valid
expect(build(:el_salvador_bank_account, account_number: "SV44BCIE123456789012345678")).not_to be_valid
expect(build(:el_salvador_bank_account, account_number: "SV44BCIE123456789012345678901")).not_to be_valid
expect(build(:el_salvador_bank_account, account_number: "SV44BCIE1234567890123456789O")).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/madagascar_bank_account_spec.rb | spec/models/madagascar_bank_account_spec.rb | # frozen_string_literal: true
describe MadagascarBankAccount do
describe "#bank_account_type" do
it "returns Madagascar" do
expect(create(:madagascar_bank_account).bank_account_type).to eq("MG")
end
end
describe "#country" do
it "returns MG" do
expect(create(:madagascar_bank_account).country).to eq("MG")
end
end
describe "#currency" do
it "returns mga" do
expect(create(:madagascar_bank_account).currency).to eq("mga")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:madagascar_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("AAAAMGMGXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:madagascar_bank_account, account_number_last_four: "0123").account_number_visual).to eq("******0123")
end
end
describe "#validate_account_number" do
it "allows records that match the required account number regex" do
expect(build(:madagascar_bank_account)).to be_valid
expect(build(:madagascar_bank_account, account_number: "MG4800005000011234567890123")).to be_valid
mg_bank_account = build(:madagascar_bank_account, account_number: "MG12345")
expect(mg_bank_account).to_not be_valid
expect(mg_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
mg_bank_account = build(:madagascar_bank_account, account_number: "DE61109010140000071219812874")
expect(mg_bank_account).to_not be_valid
expect(mg_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
mg_bank_account = build(:madagascar_bank_account, account_number: "8937040044053201300000")
expect(mg_bank_account).to_not be_valid
expect(mg_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/swiss_bank_account_spec.rb | spec/models/swiss_bank_account_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SwissBankAccount do
describe "#bank_account_type" do
it "returns swiss" do
expect(create(:swiss_bank_account).bank_account_type).to eq("CH")
end
end
describe "#country" do
it "returns CH" do
expect(create(:swiss_bank_account).country).to eq("CH")
end
end
describe "#currency" do
it "returns chf" do
expect(create(:swiss_bank_account).currency).to eq("chf")
end
end
describe "#routing_number" do
it "returns nil" do
expect(create(:swiss_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(:swiss_bank_account, account_number_last_four: "3000").account_number_visual).to eq("CH******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(:swiss_bank_account)).to be_valid
expect(build(:swiss_bank_account, account_number: "CH1234567890123456789")).to be_valid
ch_bank_account = build(:swiss_bank_account, account_number: "CH12345")
expect(ch_bank_account).to_not be_valid
expect(ch_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
ch_bank_account = build(:swiss_bank_account, account_number: "DE9300762011623852957")
expect(ch_bank_account).to_not be_valid
expect(ch_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
ch_bank_account = build(:swiss_bank_account, account_number: "8937040044053201300000")
expect(ch_bank_account).to_not be_valid
expect(ch_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
ch_bank_account = build(:swiss_bank_account, account_number: "CHABCDE")
expect(ch_bank_account).to_not be_valid
expect(ch_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/computed_sales_analytics_day_spec.rb | spec/models/computed_sales_analytics_day_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe ComputedSalesAnalyticsDay do
describe ".read_data_from_keys" do
it "returns hash with sorted existing keys and parsed values" do
create(:computed_sales_analytics_day, key: "k2", data: { v: 2 }.to_json)
create(:computed_sales_analytics_day, key: "k0", data: { v: 0 }.to_json)
result = described_class.read_data_from_keys(["k0", "k1", "k2"])
expected_result = {
"k0" => { "v" => 0 },
"k1" => nil,
"k2" => { "v" => 2 }
}
expect(result.to_a).to eq(expected_result.to_a)
end
end
describe ".fetch_data_from_key" do
it "creates record if the key does not exist, returns existing data if it does" do
expect do
result = described_class.fetch_data_from_key("k0") { { "v" => 0 } }
expect(result).to eq({ "v" => 0 })
end.to change(described_class, :count)
expect do
result = described_class.fetch_data_from_key("k0") { { "v" => 1 } }
expect(result).to eq({ "v" => 0 })
end.not_to change(described_class, :count)
end
end
describe ".upsert_data_from_key" do
it "creates a record if it doesn't exist, update data if it does" do
expect do
described_class.upsert_data_from_key("k0", { "v" => 0 })
end.to change(described_class, :count)
expect(described_class.last.data).to eq({ "v" => 0 }.to_json)
expect do
described_class.upsert_data_from_key("k0", { "v" => 1 })
end.not_to change(described_class, :count)
expect(described_class.last.data).to eq({ "v" => 1 }.to_json)
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_spec.rb | spec/models/payment_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Payment do
describe "mark" do
it "sets the appropriate state" do
payment = create(:payment)
payment.mark("failed")
expect(payment.reload.state).to eq "failed"
payment = create(:payment)
payment.mark("cancelled")
expect(payment.reload.state).to eq "cancelled"
payment = create(:payment)
payment.mark("reversed")
expect(payment.reload.state).to eq "reversed"
payment = create(:payment)
payment.mark("returned")
expect(payment.reload.state).to eq "returned"
payment = create(:payment)
payment.mark("unclaimed")
expect(payment.reload.state).to eq "unclaimed"
payment = create(:payment)
payment.txn_id = "something"
payment.processor_fee_cents = 2
payment.mark("completed")
expect(payment.reload.state).to eq "completed"
end
it "raises an error on invalid state" do
payment = create(:payment)
expect do
payment.mark("badstate")
end.to raise_error(NoMethodError)
end
context "when the processor is PAYPAL" do
it "allows a transition from processing to unclaimed" do
payment = create(:payment, processor: PayoutProcessorType::PAYPAL)
payment.mark("unclaimed")
expect(payment.reload.state).to eq "unclaimed"
end
it "allows a transition from unclaimed to cancelled and marks balances as paid" do
creator = create(:user)
merchant_account = create(:merchant_account_paypal, user: creator)
balance = create(:balance, user: creator, state: "processing", merchant_account:)
payment = create(:payment_unclaimed, balances: [balance], processor: PayoutProcessorType::PAYPAL)
payment.mark("cancelled")
expect(payment.reload.state).to eq "cancelled"
expect(balance.reload.state).to eq "unpaid"
end
end
context "when the processor is STRIPE" do
it "prevents a transition from processing to unclaimed" do
payment = create(:payment, processor: PayoutProcessorType::STRIPE, stripe_connect_account_id: "acct_1234", stripe_transfer_id: "tr_1234")
payment.mark("unclaimed")
expect(payment.errors.full_messages.length).to eq(1)
expect(payment.errors.full_messages.first).to eq("State cannot transition via \"mark unclaimed\"")
expect(payment.reload.state).to eq "processing"
end
end
describe "when transitioning to completed" do
let(:payment) { create(:payment, processor: PayoutProcessorType::STRIPE, stripe_connect_account_id: "acct_1234", stripe_transfer_id: "tr_1234", processor_fee_cents: 100) }
it "generates default abandoned cart workflow for the user" do
expect(DefaultAbandonedCartWorkflowGeneratorService).to receive(:new).with(seller: payment.user).and_call_original
expect_any_instance_of(DefaultAbandonedCartWorkflowGeneratorService).to receive(:generate)
payment.mark_completed!
end
it "does not generate workflow if user is nil" do
payment.user = nil
expect(DefaultAbandonedCartWorkflowGeneratorService).not_to receive(:new)
payment.mark_completed!
end
end
end
describe "send_cannot_pay_email" do
let(:compliant_creator) { create(:user, user_risk_state: "compliant") }
let(:payment) { create(:payment, state: "processing", processor: PayoutProcessorType::PAYPAL, processor_fee_cents: 0, user: compliant_creator) }
it "sends the cannot pay email to the creator and sets the payout_date_of_last_payment_failure_email for user" do
expect do
payment.send_cannot_pay_email
end.to have_enqueued_mail(ContactingCreatorMailer, :cannot_pay).with(payment.id)
expect(compliant_creator.reload.payout_date_of_last_payment_failure_email.to_s).to eq(payment.payout_period_end_date.to_s)
end
it "does not send the cannot pay email if payout_date_of_last_payment_failure_email is same or newer than current payout date" do
compliant_creator.payout_date_of_last_payment_failure_email = payment.payout_period_end_date
compliant_creator.save!
expect do
payment.reload.send_cannot_pay_email
end.to_not have_enqueued_mail(ContactingCreatorMailer, :cannot_pay).with(payment.id)
expect(compliant_creator.reload.payout_date_of_last_payment_failure_email.to_s).to eq(payment.payout_period_end_date.to_s)
end
end
describe "send_payout_failure_email" do
let(:compliant_creator) { create(:user, user_risk_state: "compliant") }
let(:payment) { create(:payment, state: "processing", processor: PayoutProcessorType::PAYPAL, processor_fee_cents: 0, failure_reason: "account_closed", user: compliant_creator) }
it "sends the payout failure email to the creator and sets the payout_date_of_last_payment_failure_email for user" do
expect do
payment.send_payout_failure_email
end.to have_enqueued_mail(ContactingCreatorMailer, :cannot_pay).with(payment.id)
expect(compliant_creator.reload.payout_date_of_last_payment_failure_email.to_s).to eq(payment.payout_period_end_date.to_s)
end
it "does not send the payout failure email if failure_reason is cannot_pay" do
payment.failure_reason = Payment::FailureReason::CANNOT_PAY
payment.save!
expect do
payment.reload.send_payout_failure_email
end.to_not have_enqueued_mail(ContactingCreatorMailer, :cannot_pay).with(payment.id)
end
end
describe ".failed scope" do
it "responds" do
expect(Payment).to respond_to(:failed)
end
it "only returns failed payments" do
create(:payment)
create(:payment, state: :failed)
expect(Payment.failed.length).to be(1)
expect(Payment.failed.first.state).to eq("failed")
end
it "returns failed payments sorted descending by id" do
failed_payments = (1..5).map { create(:payment, state: :failed) }
sorted_ids = failed_payments.map(&:id).sort
expect(Payment.failed.map(&:id)).to eq(sorted_ids.reverse)
end
end
describe "emails" do
describe "mark returned" do
describe "if already completed" do
let(:payment) { create(:payment, state: "completed", processor: PayoutProcessorType::ACH, processor_fee_cents: 0) }
it "sends an email to the creator" do
expect do
payment.mark_returned!
end.to have_enqueued_mail(ContactingCreatorMailer, :payment_returned).with(payment.id)
end
end
describe "if not yet completed" do
let(:payment) { create(:payment, state: "processing", processor: PayoutProcessorType::ACH, processor_fee_cents: 0) }
it "does not send an email to the creator" do
expect do
payment.mark_returned!
end.to_not have_enqueued_mail(ContactingCreatorMailer, :payment_returned).with(payment.id)
end
end
end
describe "mark failed with no reason" do
let(:payment) { create(:payment, state: "processing", processor: PayoutProcessorType::ACH, processor_fee_cents: 0) }
it "does not send an email to the creator" do
expect do
payment.mark_failed!
end.to_not have_enqueued_mail(ContactingCreatorMailer, :cannot_pay).with(payment.id)
end
end
describe "mark failed with reason cannot pay" do
let(:creator) { create(:user) }
let(:payment) { create(:payment, state: "processing", processor: PayoutProcessorType::ACH, processor_fee_cents: 0, user: creator) }
it "sends an email to the creator" do
creator.mark_compliant!(author_id: creator.id)
expect do
payment.mark_failed!(Payment::FailureReason::CANNOT_PAY)
end.to have_enqueued_mail(ContactingCreatorMailer, :cannot_pay).with(payment.id)
end
end
end
describe "#humanized_failure_reason" do
context "when the processor is STRIPE" do
it "returns the value from failure_reason" do
payment = create(:payment_failed, processor: "STRIPE", failure_reason: "cannot_pay")
expect(payment.humanized_failure_reason).to eq("cannot_pay")
end
end
context "when the processor is PAYPAL" do
it "returns the full failure message" do
payment = create(:payment_failed, processor: "PAYPAL", failure_reason: "PAYPAL 9302")
expect(payment.humanized_failure_reason).to eq("PAYPAL 9302: Transaction was declined")
end
it "returns `nil` when the failure_reason value is absent" do
payment = create(:payment_failed, processor: "PAYPAL", failure_reason: "")
expect(payment.humanized_failure_reason).to eq(nil)
end
end
end
describe "#credit_amount_cents" do
it "does not include credits created for refund fee retention" do
creator = create(:user)
balance = create(:balance, user: creator)
purchase = create(:purchase, succeeded_at: 10.days.ago, link: create(:product, user: creator))
refund = create(:refund, purchase:, fee_cents: 100)
credit = create(:credit, user: creator, amount_cents: -100, fee_retention_refund: refund, balance:)
payment = create(:payment, balances: [balance])
expect(credit.fee_retention_refund).to eq(refund)
expect(credit.balance).to eq(balance)
expect(payment.credit_amount_cents).to eq(0)
end
end
describe "#sync_with_payout_processor" do
describe "when processor is PayPal" do
before do
@payment = create(:payment, processor: PayoutProcessorType::PAYPAL)
end
it "calls #sync_with_paypal if state is non-terminal" do
%w(creating processing unclaimed completed failed cancelled returned reversed).each do |payment_state|
if payment_state == "completed"
@payment.txn_id = "12345"
@payment.processor_fee_cents = 10
end
@payment.update!(state: payment_state)
if Payment::NON_TERMINAL_STATES.include?(payment_state)
expect_any_instance_of(Payment).to receive(:sync_with_paypal)
else
expect_any_instance_of(Payment).not_to receive(:sync_with_paypal)
end
@payment.sync_with_payout_processor
end
end
end
describe "when processor is Stripe" do
before do
@payment = create(:payment, processor: PayoutProcessorType::STRIPE, stripe_transfer_id: "12345", stripe_connect_account_id: "acct_12345")
end
it "does not call #sync_with_paypal for any payment state" do
%w(creating processing unclaimed completed failed cancelled returned reversed).each do |payment_state|
if payment_state == "completed"
@payment.txn_id = "12345"
@payment.processor_fee_cents = 10
end
@payment.update!(state: payment_state)
expect_any_instance_of(Payment).not_to receive(:sync_with_paypal)
@payment.sync_with_payout_processor
end
end
end
end
describe "#sync_with_paypal" do
describe "when the payout is not created in the split mode" do
it "fetches and sets the new payment state, txn_id, correlation_id, and fee from PayPal" do
payment = create(:payment, processor: PayoutProcessorType::PAYPAL, txn_id: "txn_12345", correlation_id: nil)
expected_response = { state: "completed", transaction_id: "txn_12345", correlation_id: "correlation_id_12345", paypal_fee: "-1.15" }
expect(PaypalPayoutProcessor).to(
receive(:search_payment_on_paypal).with(amount_cents: payment.amount_cents, transaction_id: payment.txn_id,
payment_address: payment.payment_address,
start_date: payment.created_at.beginning_of_day - 1.day,
end_date: payment.created_at.end_of_day + 1.day).and_return(expected_response))
expect do
payment.send(:sync_with_paypal)
end.to change { payment.reload.state }.from("processing").to("completed")
expect(payment.txn_id).to eq("txn_12345")
expect(payment.correlation_id).to eq("correlation_id_12345")
expect(payment.processor_fee_cents).to eq(115)
end
it "marks the payment as failed if no corresponding txn is found on PayPal" do
payment = create(:payment, processor_fee_cents: 10, txn_id: nil)
expect(PaypalPayoutProcessor).to(
receive(:search_payment_on_paypal).with(amount_cents: payment.amount_cents, transaction_id: payment.txn_id,
payment_address: payment.payment_address,
start_date: payment.created_at.beginning_of_day - 1.day,
end_date: payment.created_at.end_of_day + 1.day).and_return(nil))
expect do
expect do
payment.send(:sync_with_paypal)
end.to change { payment.reload.state }.from("processing").to("failed")
end.to change { payment.reload.failure_reason }.from(nil).to("Transaction not found")
end
it "does not change the payment if multiple txns are found on PayPal" do
payment = create(:payment, processor_fee_cents: 10, txn_id: nil, correlation_id: nil)
expect(PaypalPayoutProcessor).to(
receive(:search_payment_on_paypal).with(amount_cents: payment.amount_cents, transaction_id: payment.txn_id,
payment_address: payment.payment_address,
start_date: payment.created_at.beginning_of_day - 1.day,
end_date: payment.created_at.end_of_day + 1.day).and_raise(RuntimeError))
expect do
payment.send(:sync_with_paypal)
end.not_to change { payment.reload.state }
end
end
describe "when the payout is created in the split mode" do
let(:payment) do
# Payout was sent out
payment = create(:payment, processor_fee_cents: 10)
# IPN was received and one of the split parts was in the pending state
payment.was_created_in_split_mode = true
payment.split_payments_info = [
{ "unique_id" => "SPLIT_1-1", "state" => "completed", "correlation_id" => "fcf", "amount_cents" => 100, "errors" => [], "txn_id" => "02P" },
{ "unique_id" => "SPLIT_1-2", "state" => "pending", "correlation_id" => "6db", "amount_cents" => 50, "errors" => [], "txn_id" => "4LR" }
]
payment.save!
payment
end
it "fetches and sets the new payment status from PayPal for all split parts" do
expect(PaypalPayoutProcessor).to(
receive(:get_latest_payment_state_from_paypal).with(100,
"02P",
payment.created_at.beginning_of_day - 1.day,
"completed").and_return("completed"))
expect(PaypalPayoutProcessor).to(
receive(:get_latest_payment_state_from_paypal).with(50,
"4LR",
payment.created_at.beginning_of_day - 1.day,
"pending").and_return("completed"))
expect(PaypalPayoutProcessor).to receive(:update_split_payment_state).and_call_original
expect do
payment.send(:sync_with_paypal)
end.to change { payment.reload.state }.from("processing").to("completed")
end
it "adds an error if not all split parts statuses are same" do
expect(PaypalPayoutProcessor).to(
receive(:get_latest_payment_state_from_paypal).with(100,
"02P",
payment.created_at.beginning_of_day - 1.day,
"completed").and_return("completed"))
expect(PaypalPayoutProcessor).to(
receive(:get_latest_payment_state_from_paypal).with(50,
"4LR",
payment.created_at.beginning_of_day - 1.day,
"pending").and_return("pending"))
expect(PaypalPayoutProcessor).not_to receive(:update_split_payment_state)
payment.send(:sync_with_paypal)
expect(payment.errors.first.message).to eq("Not all split payout parts are in the same state for payout #{payment.id}. This needs to be handled manually.")
end
end
end
describe "#successful_sales" do
let(:user) { create(:user) }
let(:product) { create(:product, user: user) }
let(:balance) { create(:balance, user: user) }
let(:payment) { create(:payment, user: user, balances: [balance], payout_period_end_date: 3.days.ago) }
it "includes all successful sales" do
successful_sale = create(:purchase, seller: user, link: product, purchase_success_balance: balance)
refunded_sale = create(:purchase, :refunded, seller: user, link: product, purchase_success_balance: balance)
chargedback_sale = create(:purchase, seller: user, link: product, purchase_success_balance: balance, chargeback_date: 1.day.ago)
sales = payment.successful_sales
expect(sales).to include(successful_sale)
expect(sales).to include(refunded_sale)
expect(sales).to include(chargedback_sale)
expect(sales.length).to eq(3)
end
it "returns sales sorted by created_at desc" do
older_sale = create(:purchase, seller: user, link: product, purchase_success_balance: balance, created_at: 3.days.ago)
newer_sale = create(:purchase, seller: user, link: product, purchase_success_balance: balance, created_at: 1.day.ago)
middle_sale = create(:purchase, seller: user, link: product, purchase_success_balance: balance, created_at: 2.days.ago)
sales = payment.successful_sales
expect(sales).to eq([newer_sale, middle_sale, older_sale])
end
it "returns empty array when no successful sales" do
sales = payment.successful_sales
expect(sales).to be_empty
end
end
describe "#refunded_sales" do
let(:user) { create(:user) }
let(:product) { create(:product, user: user) }
let(:balance) { create(:balance, user: user) }
let(:payment) { create(:payment, user: user, balances: [balance], payout_period_end_date: 3.days.ago) }
it "includes only refunded sales from associated balances" do
successful_sale = create(:purchase, seller: user, link: product, purchase_success_balance: balance)
refunded_sale = create(:purchase, :refunded, seller: user, link: product, purchase_refund_balance: balance)
sales = payment.refunded_sales
expect(sales).to include(refunded_sale)
expect(sales).not_to include(successful_sale)
expect(sales.length).to eq(1)
end
it "returns sales sorted by created_at desc" do
older_refunded = create(:purchase, :refunded, seller: user, link: product, purchase_refund_balance: balance, created_at: 3.days.ago)
newer_refunded = create(:purchase, :refunded, seller: user, link: product, purchase_refund_balance: balance, created_at: 1.day.ago)
sales = payment.refunded_sales
expect(sales).to eq([newer_refunded, older_refunded])
end
it "returns empty array when no refunded sales" do
sales = payment.refunded_sales
expect(sales).to be_empty
end
end
describe "#disputed_sales" do
let(:user) { create(:user) }
let(:product) { create(:product, user: user) }
let(:balance) { create(:balance, user: user) }
let(:payment) { create(:payment, user: user, balances: [balance], payout_period_end_date: 3.days.ago) }
it "includes only chargedback sales from associated balances" do
successful_sale = create(:purchase, seller: user, link: product, purchase_success_balance: balance)
chargedback_sale = create(:purchase, seller: user, link: product, purchase_chargeback_balance: balance, chargeback_date: 1.day.ago)
sales = payment.disputed_sales
expect(sales).to include(chargedback_sale)
expect(sales).not_to include(successful_sale)
expect(sales.length).to eq(1)
end
it "returns sales sorted by created_at desc" do
older_chargeback = create(:purchase, seller: user, link: product, purchase_chargeback_balance: balance, chargeback_date: 3.days.ago, created_at: 3.days.ago)
newer_chargeback = create(:purchase, seller: user, link: product, purchase_chargeback_balance: balance, chargeback_date: 1.day.ago, created_at: 1.day.ago)
sales = payment.disputed_sales
expect(sales).to eq([newer_chargeback, older_chargeback])
end
it "returns empty array when no chargedback sales" do
sales = payment.disputed_sales
expect(sales).to be_empty
end
end
describe "#as_json" do
before do
allow(ObfuscateIds).to receive(:encrypt).and_return("mocked_external_id")
@payment = create(:payment,
amount_cents: 2500,
currency: "USD",
processor: PayoutProcessorType::STRIPE,
processor_fee_cents: 25)
end
it "has the right keys" do
%i[id amount currency status created_at processed_at payment_processor bank_account_visual paypal_email].each do |key|
expect(@payment.as_json.key?(key)).to be(true)
end
end
it "returns external_id for the id field" do
json = @payment.as_json
expect(json[:id]).to eq("mocked_external_id")
end
it "returns the correct values for basic fields" do
json = @payment.as_json
expect(json[:amount]).to eq("25.00")
expect(json[:currency]).to eq("USD")
expect(json[:status]).to eq(@payment.state)
expect(json[:created_at]).to eq(@payment.created_at)
expect(json[:payment_processor]).to eq(PayoutProcessorType::STRIPE)
end
it "returns correct formatted amount" do
@payment.update!(amount_cents: 12345)
expect(@payment.as_json[:amount]).to eq("123.45")
@payment.update!(amount_cents: 100)
expect(@payment.as_json[:amount]).to eq("1.00")
@payment.update!(amount_cents: 99)
expect(@payment.as_json[:amount]).to eq("0.99")
end
context "when payment is not completed" do
it "returns nil for processed_at in processing state" do
@payment.update!(state: Payment::PROCESSING)
expect(@payment.as_json[:processed_at]).to be_nil
end
it "returns nil for processed_at in failed state" do
@payment.update!(state: Payment::FAILED)
expect(@payment.as_json[:processed_at]).to be_nil
end
it "returns nil for processed_at in creating state" do
@payment.update!(state: Payment::CREATING)
expect(@payment.as_json[:processed_at]).to be_nil
end
end
context "when payment is completed" do
it "returns correct processed_at timestamp" do
# Set required fields for state transition
@payment.update!(
txn_id: "test_txn_123",
processor_fee_cents: 25,
stripe_transfer_id: "tr_123",
stripe_connect_account_id: "acct_123"
)
@payment.mark_completed!
json = @payment.as_json
expect(json[:processed_at]).to eq(@payment.updated_at)
expect(json[:status]).to eq(Payment::COMPLETED)
end
end
it "works with different payment processors" do
paypal_payment = create(:payment, processor: PayoutProcessorType::PAYPAL)
expect(paypal_payment.as_json[:payment_processor]).to eq(PayoutProcessorType::PAYPAL)
stripe_payment = create(:payment, processor: PayoutProcessorType::STRIPE)
expect(stripe_payment.as_json[:payment_processor]).to eq(PayoutProcessorType::STRIPE)
end
it "works with different currencies" do
eur_payment = create(:payment, currency: "EUR", amount_cents: 5000)
expect(eur_payment.as_json[:currency]).to eq("EUR")
expect(eur_payment.as_json[:amount]).to eq("50.00")
end
it "handles zero amount correctly" do
@payment.update!(amount_cents: 0)
expect(@payment.as_json[:amount]).to eq("0.00")
end
context "bank_account_visual field" do
it "includes bank_account_visual when payment has bank account" do
bank_account = create(:ach_account, user: @payment.user)
bank_account.update!(account_number_last_four: "1234")
@payment.update!(bank_account: bank_account)
json = @payment.as_json
expect(json[:bank_account_visual]).to eq("******1234")
end
it "returns nil when payment has no bank account" do
json = @payment.as_json
expect(json[:bank_account_visual]).to be_nil
end
end
context "paypal_email field" do
it "includes paypal_email when payment has payment_address" do
@payment.update!(payment_address: "seller@example.com")
json = @payment.as_json
expect(json[:paypal_email]).to eq("seller@example.com")
end
it "returns nil when payment has no payment_address" do
json = @payment.as_json
expect(json[:paypal_email]).to be_nil
end
end
context "with include_sales option" do
let(:user) { create(:user) }
let(:product) { create(:product, user: user) }
let(:balance) { create(:balance, user: user) }
let(:payment) { create(:payment, user: user, balances: [balance]) }
before do
allow(ObfuscateIds).to receive(:encrypt).and_return("mocked_external_id")
end
context "when include_sales is true" do
it "includes sales, refunded_sales, and disputed_sales ids" do
successful_sale = create(:purchase, seller: user, link: product, purchase_success_balance: balance)
refunded_sale = create(:purchase, :refunded, seller: user, link: product, purchase_refund_balance: balance)
chargedback_sale = create(:purchase, seller: user, link: product, purchase_chargeback_balance: balance, chargeback_date: 1.day.ago)
json = payment.as_json(include_sales: true)
expect(json[:sales]).to be_an(Array)
expect(json[:refunded_sales]).to be_an(Array)
expect(json[:disputed_sales]).to be_an(Array)
expect(json[:sales].length).to eq(1)
expect(json[:refunded_sales].length).to eq(1)
expect(json[:disputed_sales].length).to eq(1)
expect(json[:sales].first).to be_a(String)
expect(json[:sales].first).to eq(successful_sale.external_id)
expect(json[:refunded_sales].first).to be_a(String)
expect(json[:refunded_sales].first).to eq(refunded_sale.external_id)
expect(json[:disputed_sales].first).to be_a(String)
expect(json[:disputed_sales].first).to eq(chargedback_sale.external_id)
end
it "includes empty arrays when no sales of each type exist" do
json = payment.as_json(include_sales: true)
expect(json[:sales]).to eq([])
expect(json[:refunded_sales]).to eq([])
expect(json[:disputed_sales]).to eq([])
end
end
context "when include_sales is false" do
it "does not include sales keys in the response" do
json = payment.as_json(include_sales: false)
expect(json).not_to have_key(:sales)
expect(json).not_to have_key(:refunded_sales)
expect(json).not_to have_key(:disputed_sales)
end
end
context "when include_sales option is not provided" do
it "does not include sales keys in the response" do
json = payment.as_json
expect(json).not_to have_key(:sales)
expect(json).not_to have_key(:refunded_sales)
expect(json).not_to have_key(:disputed_sales)
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/staff_picked_product_spec.rb | spec/models/staff_picked_product_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RefundPolicy do
describe "validations" do
it "validates presence" do
staff_picked_product = StaffPickedProduct.new
expect(staff_picked_product.valid?).to be false
expect(staff_picked_product.errors.details[:product].first[:error]).to eq :blank
end
context "when there is a record for a given product" do
let(:product) { create(:product, :staff_picked) }
it "cannot create record with same product" do
new_record = StaffPickedProduct.new(product:)
expect(new_record.valid?).to be false
expect(new_record.errors.details[:product].first[:error]).to eq :taken
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/installment_spec.rb | spec/models/installment_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Installment do
include Rails.application.routes.url_helpers
before do
@creator = create(:named_user, :with_avatar)
@installment = @post = create(:installment, call_to_action_text: "CTA", call_to_action_url: "https://www.example.com", seller: @creator)
end
describe "scopes" do
describe ".visible_on_profile" do
it "returns only non-workflow audience type published posts that are shown on profile" do
create(:installment, :published, installment_type: Installment::FOLLOWER_TYPE, seller: @creator, shown_on_profile: true)
create(:installment, :published, installment_type: Installment::AUDIENCE_TYPE, seller: @creator)
create(:installment, :published, installment_type: Installment::AUDIENCE_TYPE, workflow: create(:workflow))
create(:installment, :published, installment_type: Installment::AUDIENCE_TYPE, seller: @creator, shown_on_profile: true, deleted_at: 1.day.ago)
post = create(:installment, :published, installment_type: Installment::AUDIENCE_TYPE, seller: @creator, shown_on_profile: true)
expect(described_class.visible_on_profile).to eq([post])
end
end
end
describe "#is_downloadable?" do
it "returns false if post has no files" do
expect(@installment.is_downloadable?).to eq(false)
end
it "returns false if post has only stream-only files" do
@installment.product_files << create(:streamable_video, stream_only: true)
expect(@installment.is_downloadable?).to eq(false)
end
it "returns true if post has files that are not stream-only" do
@installment.product_files << create(:readable_document)
@installment.product_files << create(:streamable_video, stream_only: true)
expect(@installment.is_downloadable?).to eq(true)
end
end
describe "#send_installment_from_workflow_for_member_cancellation" do
before do
@creator1 = create(:user)
@product1 = create(:subscription_product, user: @creator1)
@subscription1 = create(:subscription, link: @product1, cancelled_at: 2.days.ago, deactivated_at: 1.day.ago)
@subscription2 = create(:subscription, link: @product1, cancelled_at: 2.days.ago, deactivated_at: 1.day.ago)
@workflow1 = create(:workflow, seller: @creator1, link: @product1, workflow_trigger: "member_cancellation")
@published_installment = create(:published_installment, link: @product1, workflow: @workflow1, workflow_trigger: "member_cancellation")
@sale1 = create(:purchase, is_original_subscription_purchase: true, link: @product1, subscription: @subscription1, email: "test@gmail.com", created_at: 1.week.ago, price_cents: 100)
@sale2 = create(:purchase, is_original_subscription_purchase: true, link: @product1, subscription: @subscription2, email: "test2@gmail.com", created_at: 2.weeks.ago, price_cents: 100)
end
it "sends a subscription_cancellation_installment email for the cancellation" do
expect(PostSendgridApi).to receive(:process).with(
post: @published_installment,
recipients: [{ email: @sale1.email, purchase: @sale1, subscription: @subscription1 }],
cache: {}
)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription1.id)
# PostSendgridApi creates this, but is mocked in specs
create(:creator_contacting_customers_email_info_sent, purchase: @sale1, installment: @published_installment, email_name: "subscription_cancellation_installment")
expect(PostSendgridApi).to receive(:process).with(
post: @published_installment,
recipients: [{ email: @sale2.email, purchase: @sale2, subscription: @subscription2 }],
cache: anything
)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription2.id)
end
it "does not send an email for non member cancellation installments" do
@published_installment.update!(workflow_trigger: nil)
expect(PostSendgridApi).not_to receive(:process)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription1.id)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription2.id)
end
it "does not send an email for alive subscriptions" do
@subscription1.update!(cancelled_at: nil, deactivated_at: nil)
expect(PostSendgridApi).to receive(:process).with(
post: @published_installment,
recipients: [{ email: @sale2.email, purchase: @sale2, subscription: @subscription2 }],
cache: anything
)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription1.id)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription2.id)
end
it "does not send an email if sale's can_contact is set to false" do
@sale1.update!(can_contact: false)
expect(PostSendgridApi).to receive(:process).with(
post: @published_installment,
recipients: [{ email: @sale2.email, purchase: @sale2, subscription: @subscription2 }],
cache: anything
)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription1.id)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription2.id)
end
it "does not send an email if sale is chargebacked" do
@sale1.update!(chargeback_date: 1.days.ago)
expect(PostSendgridApi).to receive(:process).with(
post: @published_installment,
recipients: [{ email: @sale2.email, purchase: @sale2, subscription: @subscription2 }],
cache: anything
)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription1.id)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription2.id)
end
it "does not send an email if the customer has already received a cancellation email for this installment from the creator" do
# create 2 products made by the same creator, and two subscriptions by the same customer
product = create(:subscription_product, user: @creator1)
subscription = create(:subscription, link: product, cancelled_at: 2.days.ago, deactivated_at: 1.day.ago)
product2 = create(:subscription_product, user: @creator1)
subscription2 = create(:subscription, link: product2, cancelled_at: 2.days.ago, deactivated_at: 1.day.ago)
sale = create(:purchase, is_original_subscription_purchase: true, link: product, subscription:, email: "test@gmail.com", created_at: 1.week.ago, price_cents: 100)
create(:purchase, is_original_subscription_purchase: true, link: product2, subscription: subscription2, email: "test@gmail.com", created_at: 1.week.ago, price_cents: 100)
workflow = create(:seller_workflow, seller: @creator1, workflow_trigger: "member_cancellation")
installment = create(:published_installment, workflow:, workflow_trigger: "member_cancellation")
# Assume an email's been sent for `subscription`. PostSendgridApi creates this, but is mocked in specs
create(:creator_contacting_customers_email_info_sent, purchase: sale, installment:, email_name: "subscription_cancellation_installment")
# Because an email was sent for `subscription`, subscription2's email shouldn't be sent.
expect(PostSendgridApi).not_to receive(:process)
installment.send_installment_from_workflow_for_member_cancellation(subscription2.id)
end
it "does not send an email if the workflow does not apply to the purchase" do
creator = create(:user)
product = create(:subscription_product, user: creator)
workflow = create(:workflow, seller: creator, link: product, workflow_trigger: "member_cancellation")
@published_installment.update!(link: product, workflow:)
expect(PostSendgridApi).not_to receive(:process)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription1.id)
@published_installment.send_installment_from_workflow_for_member_cancellation(@subscription2.id)
end
end
describe "#truncated_description" do
before do
@installment.update!(message: "<h3>I'm a Title.</h3><p>I'm a body. I've got all sorts of punctuation.</p>")
end
it "does not escape characters and adds space between paragraphs" do
expect(@installment.truncated_description).to eq "I'm a Title. I'm a body. I've got all sorts of punctuation."
end
end
describe "#message_with_inline_syntax_highlighting_and_upsells" do
let(:product) { create(:product, user: @creator, price_cents: 1000) }
context "with code blocks" do
before do
message = <<~HTML
<p>hello, <code>world</code>!</p>
<pre class="codeblock-lowlight"><code>// bad
var a = 1;
var b = 2;
// good
const a = 1;
const b = 2;</code></pre>
<p>Ruby code:</p>
<pre class="codeblock-lowlight"><code class="language-ruby">def hello_world
puts "Hello, World!"
end</code></pre>
<p>TypeScript code:</p>
<pre class="codeblock-lowlight"><code class="language-typescript">function greet(name: string): void {
console.log(`Hello, ${name}!`);
}</code></pre>
<p>Bye!</p>
HTML
@installment.update!(message:)
end
it "returns message with inline syntax highlighting the code snippets" do
expect(@installment.message_with_inline_syntax_highlighting_and_upsells).to eq(%(<p>hello, <code>world</code>!</p>
<pre style="white-space: revert; overflow: auto; border: 1px solid currentColor; border-radius: 4px; background-color: #fff;"><code style="max-width: unset; border-width: 0; width: 100vw; background-color: #fff;">// bad
var a = 1;
var b = 2;
// good
const a = 1;
const b = 2;</code></pre>
<p>Ruby code:</p>
<pre style="white-space: revert; overflow: auto; border: 1px solid currentColor; border-radius: 4px; background-color: #fff;"><code style="max-width: unset; border-width: 0; width: 100vw; background-color: #fff;"><span style="color: #9d0006">def</span> <span style="color: #282828;background-color: #fff">hello_world</span>
<span style="color: #282828;background-color: #fff">puts</span> <span style="color: #79740e;font-style: italic">"Hello, World!"</span>
<span style="color: #9d0006">end</span></code></pre>
<p>TypeScript code:</p>
<pre style="white-space: revert; overflow: auto; border: 1px solid currentColor; border-radius: 4px; background-color: #fff;"><code style="max-width: unset; border-width: 0; width: 100vw; background-color: #fff;"><span style="color: #af3a03">function</span> <span style="color: #282828;background-color: #fff">greet</span><span style="color: #282828">(</span><span style="color: #282828;background-color: #fff">name</span><span style="color: #282828">:</span> <span style="color: #9d0006">string</span><span style="color: #282828">):</span> <span style="color: #9d0006">void</span> <span style="color: #282828">{</span>
<span style="color: #282828;background-color: #fff">console</span><span style="color: #282828">.</span><span style="color: #282828;background-color: #fff">log</span><span style="color: #282828">(</span><span style="color: #79740e;font-style: italic">`Hello, </span><span style="color: #282828">${</span><span style="color: #282828;background-color: #fff">name</span><span style="color: #282828">}</span><span style="color: #79740e;font-style: italic">!`</span><span style="color: #282828">);</span>
<span style="color: #282828">}</span></code></pre>
<p>Bye!</p>
))
end
end
context "with upsell cards" do
before do
message = <<~HTML
<p>Check out these products:</p>
<upsell-card id="#{upsell.external_id}"></upsell-card>
<p>Great deals!</p>
HTML
@installment.update!(message:)
end
let(:offer_code) { create(:offer_code, user: @creator, products: [product], amount_cents: 200) }
let(:upsell) { create(:upsell, product:, seller: @creator, offer_code:) }
it "renders both regular and discounted upsell cards" do
result = @installment.message_with_inline_syntax_highlighting_and_upsells
expect(result).to eq(%(<p>Check out these products:</p>
<div class="item">
<div class="product-checkout-cell">
<div class="figure">
<img alt="The Works of Edgar Gumstein" src="/assets/native_types/thumbnails/digital-d4b2a661e31ec353551a8dae9996b1e75b1e629e363d683aaa5fd2fb1213311c.png">
</div>
<div class="section">
<div class="content">
<div class="section">
<h4><a href="http://app.test.gumroad.com:31337/checkout?accepted_offer_id=#{CGI.escape(upsell.external_id)}&product=#{product.unique_permalink}">The Works of Edgar Gumstein</a></h4>
</div>
<div class="section">
<s style="display: inline;">$10</s>
$8
</div>
</div>
</div>
</div>
</div>
<p>Great deals!</p>
))
end
end
context "with media embeds" do
it "replaces media embed iframe with a link to the media thumbnail" do
@installment.update!(message: %(<div class="tiptap__raw" data-title="Q4 2024 Antiwork All Hands" data-url="https://www.youtube.com/watch?v=drMMDclhgsc" data-thumbnail="https://i.ytimg.com/vi/drMMDclhgsc/maxresdefault.jpg"><div><div style="left: 0; width: 100%; height: 0; position: relative; padding-bottom: 56.25%;"><iframe src="//cdn.iframe.ly/api/iframe?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdrMMDclhgsc&key=31708e31359468f73bc5b03e9dcab7da" style="top: 0; left: 0; width: 100%; height: 100%; position: absolute; border: 0;" allowfullscreen="" scrolling="no" allow="accelerometer *; clipboard-write *; encrypted-media *; gyroscope *; picture-in-picture *; web-share *;"></iframe></div></div></div>))
expect(@installment.message_with_inline_syntax_highlighting_and_upsells).to eq(%(<p><a href="https://www.youtube.com/watch?v=drMMDclhgsc" target="_blank" rel="noopener noreferrer"><img src="https://i.ytimg.com/vi/drMMDclhgsc/maxresdefault.jpg" alt="Q4 2024 Antiwork All Hands"></a></p>))
end
it "replaces media embed iframe with a link to the media's title if thumbnail is missing" do
@installment.update!(message: %(<div class="tiptap__raw" data-title="Ben Holmes on Twitter / X" data-url="https://twitter.com/BHolmesDev/status/1858141344008405459">\n<div class="iframely-embed" style="max-width: 550px;"><div class="iframely-responsive" style="padding-bottom: 56.25%;"><a href="https://twitter.com/BHolmesDev/status/1858141344008405459" data-iframely-url="//cdn.iframe.ly/api/iframe?url=https%3A%2F%2Fx.com%2Fbholmesdev%2Fstatus%2F1858141344008405459%3Fs%3D46&key=31708e31359468f73bc5b03e9dcab7da"></a></div></div>\n<script async="" src="//cdn.iframe.ly/embed.js" charset="utf-8"></script>\n</div>))
expect(@installment.message_with_inline_syntax_highlighting_and_upsells).to eq(%(<p><a href="https://twitter.com/BHolmesDev/status/1858141344008405459" target="_blank" rel="noopener noreferrer">Ben Holmes on Twitter / X</a></p>))
end
end
end
describe "#message_with_inline_abandoned_cart_products" do
let(:workflow) { create(:abandoned_cart_workflow, seller: @creator) }
let(:installment) { workflow.installments.first }
before do
installment.update!(message: "<p>hello, <code>world</code>!<p>We saved the following items in your cart, so when you're ready to buy, simply <a href='#{checkout_index_url(host: UrlService.domain_with_protocol)}'>complete checking out</a>.</p><product-list-placeholder />")
end
context "when products are missing" do
it "returns the message as it is" do
expect(installment.message_with_inline_abandoned_cart_products(products: [])).to eq(installment.message)
end
end
context "when products are present" do
let!(:products) { create_list(:product, 4, user: @creator) }
it "returns the message with the products" do
checkout_url = checkout_index_url(host: UrlService.domain_with_protocol)
message = installment.message_with_inline_abandoned_cart_products(products: workflow.abandoned_cart_products)
expect(message).to include(@creator.avatar_url)
parsed_message = Nokogiri::HTML(message)
expect(message).to include(%(<a target="_blank" href="#{@creator.profile_url}">#{@creator.display_name}</a>))
products.take(3) do |product|
expect(parsed_message.at_css("a[target='_blank'][href='#{product.long_url}']").text).to eq(product.name)
end
expect(message).to_not include("Product 4")
expect(message).to_not include("<product-list-placeholder />")
expect(parsed_message.at_css("a[href='#{checkout_url}']").text).to eq("complete checking out")
expect(parsed_message.at_css("a[href='#{checkout_url}'][target='_blank']").text).to eq("and 1 more product")
expect(parsed_message.at_css("a.button.primary[href='#{checkout_url}'][target='_blank']").text).to eq("Complete checkout")
end
context "when a custom checkout_url is provided" do
it "returns the message with the custom checkout_url" do
checkout_url = checkout_index_url(host: UrlService.domain_with_protocol, cart_id: "abc123")
message = installment.message_with_inline_abandoned_cart_products(products: workflow.abandoned_cart_products, checkout_url:)
expect(message).to include("cart_id=abc123")
parsed_message = Nokogiri::HTML(message)
expect(parsed_message.at_css("a[href='#{checkout_url}']").text).to eq("complete checking out")
expect(parsed_message.at_css("a[href='#{checkout_url}'][target='_blank']").text).to eq("and 1 more product")
expect(parsed_message.at_css("a.button.primary[href='#{checkout_url}'][target='_blank']").text).to eq("Complete checkout")
end
end
end
end
describe "#generate_url_redirect_for_subscription" do
before do
@subscription = create(:subscription, link: @installment.link)
end
it "creates a new url_redirect" do
@installment.generate_url_redirect_for_subscription(@subscription)
expect((@installment.url_redirect(@subscription).instance_of? UrlRedirect)).to be(true)
end
end
describe "#url_redirect" do
before do
@subscription = create(:subscription, link: @installment.link)
@installment.generate_url_redirect_for_subscription(@subscription)
end
it "returns correct url_redirect" do
url_redirect = @installment.url_redirect(@subscription)
expect(url_redirect.subscription).to eq @subscription
expect(url_redirect.installment).to eq @installment
end
end
describe "#follower_or_audience_url_redirect" do
it "returns a url_redirect without an associated purchase object" do
post = create(:post)
expect(post.follower_or_audience_url_redirect).to eq(nil)
UrlRedirect.create!(installment: post, subscription: create(:subscription))
UrlRedirect.create!(installment: post, purchase: create(:purchase))
url_redirect = UrlRedirect.create!(installment: post)
UrlRedirect.create!(installment: post, purchase: create(:purchase), subscription: create(:subscription))
expect(post.reload.follower_or_audience_url_redirect).to eq(url_redirect)
end
end
describe "#download_url" do
before do
@product_file = create(:product_file, installment: @installment, link: nil)
@subscriber = create(:user)
@subscription = create(:subscription, link: @installment.link, user: @subscriber)
@purchase = create(:purchase, is_original_subscription_purchase: true, link: @installment.link, subscription: @subscription, price_cents: 100, purchaser: @subscriber)
@purchase_url_redirect = @installment.generate_url_redirect_for_purchase(@purchase)
end
it "returns the purchase url redirect if it cannot find a url redirect using the subscription" do
expect(@installment.download_url(@subscription, @purchase)).to eq @purchase_url_redirect.url.sub("/r/", "/d/")
end
it "creates a new url redirect if none exists for installment with files" do
user = create(:user)
subscription = create(:subscription, link: @installment.link, user:)
purchase = create(:purchase, is_original_subscription_purchase: true, link: @installment.link, subscription:, price_cents: 100, purchaser: user)
expect(@installment.download_url(subscription, purchase)).to be_present
end
it "creates a new url redirect if none exists for installment with files even for installments with send_emails=false" do
@installment.send_emails = false
@installment.shown_on_profile = true
@installment.save!
user = create(:user)
subscription = create(:subscription, link: @installment.link, user:)
purchase = create(:purchase, is_original_subscription_purchase: true, link: @installment.link, subscription:, price_cents: 100, purchaser: user)
expect(@installment.download_url(subscription, purchase)).to be_present
end
it "does not return a download url if the installment is going to a follower and has no files" do
@installment.product_files.map(&:mark_deleted)
expect(@installment.download_url(nil, nil)).to eq nil
end
end
describe "#invalidate_cache" do
before do
@installment = create(:installment, customer_count: 4)
end
it "invalidates the cache and read the updated value" do
3.times { CreatorEmailOpenEvent.create!(installment_id: @installment.id) }
# Read once and set the cache
expect(@installment.unique_open_count).to eq 3
4.times { CreatorEmailOpenEvent.create!(installment_id: @installment.id) }
new_unique_open_count = @installment.unique_open_count
# It should remain 3 as the cache isn't invalidated
expect(new_unique_open_count).to eq 3
@installment.invalidate_cache(:unique_open_count)
expect(@installment.unique_open_count).to eq 7
end
end
describe "#displayed_name" do
it "returns the installment name" do
@installment.update_attribute(:name, "welcome")
expect(@installment.displayed_name).to eq("welcome")
end
it "returns the message as the name without html tags" do
@installment.update_attribute(:name, "")
@installment.update_attribute(:message, "<p>welcome</p>")
expect(@installment.displayed_name).to eq("welcome")
end
end
describe "#eligible_purchase_for_user" do
it "returns the user's purchase that passes filters for the post and hence is eligible to view the attached content" do
creator = create(:user)
buyer = create(:user)
product = create(:product, user: creator)
category = create(:variant_category, title: "Tier", link: product)
standard_variant = create(:variant, variant_category: category, name: "Standard")
premium_variant = create(:variant, variant_category: category, name: "Premium")
product_post = create(:installment, link: product)
standard_variant_post = create(:variant_installment, link: product, base_variant: standard_variant)
premium_variant_post = create(:variant_installment, link: product, base_variant: premium_variant)
seller_post = create(:seller_installment, seller: creator)
audience_post = create(:audience_installment, seller: creator)
follower_post = create(:follower_installment, seller: creator)
other_product_purchase = create(:purchase, link: create(:product, user: creator), purchaser: buyer)
product_purchase = create(:purchase, link: product, purchaser: buyer)
standard_variant_purchase = create(:purchase, link: product, purchaser: buyer)
standard_variant_purchase.variant_attributes << standard_variant
premium_variant_purchase = create(:purchase, link: product, purchaser: buyer)
premium_variant_purchase.variant_attributes << premium_variant
expect(product_post.eligible_purchase_for_user(buyer)).to eq(product_purchase)
expect(standard_variant_post.eligible_purchase_for_user(buyer)).to eq(standard_variant_purchase)
expect(premium_variant_post.eligible_purchase_for_user(buyer)).to eq(premium_variant_purchase)
expect(seller_post.eligible_purchase_for_user(buyer)).to eq(other_product_purchase)
expect(audience_post.eligible_purchase_for_user(buyer)).to be(nil)
expect(follower_post.eligible_purchase_for_user(buyer)).to be(nil)
expect(follower_post.eligible_purchase_for_user(nil)).to be(nil)
end
end
describe "#targeted_at_purchased_item?" do
let(:variant) { create(:variant) }
let(:product) { variant.link }
let(:purchase) { create(:purchase, link: product, variant_attributes: [variant]) }
context "product installment" do
it "returns true if it is targeted at the purchased product" do
post = build(:installment, link: product)
expect(post.targeted_at_purchased_item?(purchase)).to eq true
end
it "returns false if it is not targeted at the purchased product" do
post = build(:installment)
expect(post.targeted_at_purchased_item?(purchase)).to eq false
end
end
context "variant installment" do
it "returns true if it is targeted at the purchased variant" do
post = build(:variant_installment, base_variant: variant)
expect(post.targeted_at_purchased_item?(purchase)).to eq true
end
it "returns false if it is not targeted at the purchased variant" do
post = build(:variant_installment)
expect(post.targeted_at_purchased_item?(purchase)).to eq false
end
end
context "other installment" do
it "returns true if bought_products includes the purchased product" do
seller_post = build(:seller_installment, bought_products: [product.unique_permalink])
follower_post = build(:follower_installment, bought_products: [product.unique_permalink])
audience_post = build(:audience_installment, bought_products: [product.unique_permalink])
expect(seller_post.targeted_at_purchased_item?(purchase)).to eq true
expect(follower_post.targeted_at_purchased_item?(purchase)).to eq true
expect(audience_post.targeted_at_purchased_item?(purchase)).to eq true
end
it "returns true if bought_variants includes the purchased variant" do
seller_post = build(:seller_installment, bought_variants: [variant.external_id])
follower_post = build(:follower_installment, bought_variants: [variant.external_id])
audience_post = build(:audience_installment, bought_variants: [variant.external_id])
expect(seller_post.targeted_at_purchased_item?(purchase)).to eq true
expect(follower_post.targeted_at_purchased_item?(purchase)).to eq true
expect(audience_post.targeted_at_purchased_item?(purchase)).to eq true
end
it "returns false if neither bought_products nor bought_variants are present" do
seller_post = build(:seller_installment)
follower_post = build(:follower_installment)
audience_post = build(:audience_installment)
expect(seller_post.targeted_at_purchased_item?(purchase)).to eq false
expect(follower_post.targeted_at_purchased_item?(purchase)).to eq false
expect(audience_post.targeted_at_purchased_item?(purchase)).to eq false
end
it "returns false if bought_products does not include the purchased product" do
other_product = create(:product)
seller_post = build(:seller_installment, bought_products: [other_product.unique_permalink])
follower_post = build(:follower_installment, bought_products: [other_product.unique_permalink])
audience_post = build(:audience_installment, bought_products: [other_product.unique_permalink])
expect(seller_post.targeted_at_purchased_item?(purchase)).to eq false
expect(follower_post.targeted_at_purchased_item?(purchase)).to eq false
expect(audience_post.targeted_at_purchased_item?(purchase)).to eq false
end
it "returns false if bought_variants does not include the purchased variant" do
other_variant = create(:variant)
seller_post = build(:seller_installment, bought_variants: [other_variant.external_id])
follower_post = build(:follower_installment, bought_variants: [other_variant.external_id])
audience_post = build(:audience_installment, bought_variants: [other_variant.external_id])
expect(seller_post.targeted_at_purchased_item?(purchase)).to eq false
expect(follower_post.targeted_at_purchased_item?(purchase)).to eq false
expect(audience_post.targeted_at_purchased_item?(purchase)).to eq false
end
end
end
describe "#passes_member_cancellation_checks?" do
before do
@creator = create(:user, name: "dude")
@product = create(:subscription_product, user: @creator)
@subscription = create(:subscription, link: @product)
@sale = create(:purchase, is_original_subscription_purchase: true, link: @product, subscription: @subscription)
@installment = create(:installment, name: "My first installment", link: @product, workflow_trigger: "member_cancellation")
end
it "returns true if the workflow trigger is not a member cancellation" do
@installment.update!(workflow_trigger: nil)
expect(@installment.passes_member_cancellation_checks?(@sale)).to eq(true)
end
it "returns false if purchase is nil" do
expect(@installment.passes_member_cancellation_checks?(nil)).to eq(false)
end
it "returns false if the email hasn't been sent for the member cancellation" do
expect(@installment.passes_member_cancellation_checks?(@sale)).to eq(false)
end
it "returns true if the email has been sent for the member cancellation" do
create(:creator_contacting_customers_email_info_sent, purchase: @sale, installment: @installment)
expect(@installment.passes_member_cancellation_checks?(@sale)).to eq(true)
end
end
describe "#full_url" do
before do
@post = create(:audience_installment)
end
context "when slug is not present" do
it "returns nil" do
@post.update_column(:slug, "")
expect(@post.full_url).to be_nil
end
end
context "when purchase_id is present" do
it "returns the subdomain URL of the post" do
target_url = Rails.application.routes.url_helpers.custom_domain_view_post_url(
host: @post.user.subdomain_with_protocol,
slug: @post.slug,
purchase_id: 1234
)
expect(@post.full_url(purchase_id: 1234)).to eq target_url
end
end
context "when purchase_id is not present" do
it "returns the subdomain URL of the post" do
target_url = Rails.application.routes.url_helpers.custom_domain_view_post_url(
host: @post.user.subdomain_with_protocol,
slug: @post.slug
)
expect(@post.full_url).to eq target_url
end
end
end
describe "#display_type" do
subject(:display_type) { installment.display_type }
context "when post published" do
let(:installment) { create(:published_installment) }
it "returns 'published'" do
expect(display_type).to eq("published")
end
end
context "when post is scheduled" do
let(:installment) { create(:scheduled_installment) }
it "returns 'scheduled'" do
expect(display_type).to eq("scheduled")
end
end
context "when post is a draft" do
let(:installment) { create(:installment) }
it "returns 'draft'" do
expect(display_type).to eq("draft")
end
end
end
describe "#eligible_purchase?" do
context "when purchase is nil" do
subject(:installment) { create(:published_installment) }
it "returns false" do
expect(installment.eligible_purchase?(nil)).to eq(false)
end
end
context "when installment does not need purchase to access content" do
subject(:installment) { create(:published_installment, installment_type: "audience") }
it "returns true" do
expect(installment.eligible_purchase?(nil)).to eq(true)
end
end
context "when installment is a product post" do
let(:product) { create(:product) }
subject(:installment) { create(:product_installment, link: product, published_at: 1.day.ago) }
context "when purchased product is a post's product" do
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/serbia_bank_account_spec.rb | spec/models/serbia_bank_account_spec.rb | # frozen_string_literal: true
describe SerbiaBankAccount do
describe "#bank_account_type" do
it "returns Serbia" do
expect(create(:serbia_bank_account).bank_account_type).to eq("RS")
end
end
describe "#country" do
it "returns RS" do
expect(create(:serbia_bank_account).country).to eq("RS")
end
end
describe "#currency" do
it "returns rsd" do
expect(create(:serbia_bank_account).currency).to eq("rsd")
end
end
describe "#routing_number" do
it "returns valid for 11 characters" do
ba = create(:serbia_bank_account)
expect(ba).to be_valid
expect(ba.routing_number).to eq("TESTSERBXXX")
end
end
describe "#account_number_visual" do
it "returns the visual account number" do
expect(create(:serbia_bank_account, account_number_last_four: "9123").account_number_visual).to eq("RS******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(:serbia_bank_account)).to be_valid
expect(build(:serbia_bank_account, account_number: "RS35105008123123123173")).to be_valid
rs_bank_account = build(:serbia_bank_account, account_number: "MA12345")
expect(rs_bank_account).to_not be_valid
expect(rs_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
rs_bank_account = build(:serbia_bank_account, account_number: "DE61109010140000071219812874")
expect(rs_bank_account).to_not be_valid
expect(rs_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
rs_bank_account = build(:serbia_bank_account, account_number: "89370400044053201300000")
expect(rs_bank_account).to_not be_valid
expect(rs_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.")
rs_bank_account = build(:serbia_bank_account, account_number: "CRABCDE")
expect(rs_bank_account).to_not be_valid
expect(rs_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/seller_profile_spec.rb | spec/models/seller_profile_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SellerProfile do
describe "#custom_styles" do
subject { create(:seller_profile, highlight_color: "#009a49", font: "Roboto Mono", background_color: "#000000") }
it "has CSS for background color, accent color, and font" do
expect(subject.custom_styles).to include("--accent: 0 154 73;--contrast-accent: 255 255 255")
expect(subject.custom_styles).to include("--filled: 0 0 0")
expect(subject.custom_styles).to include("--body-bg: #000000")
expect(subject.custom_styles).to include("--color: 255 255 255")
expect(subject.custom_styles).to include("--font-family: \"Roboto Mono\", \"ABC Favorit\", monospace")
end
it "rebuilds CSS when custom style attribute is saved" do
subject.update_attribute(:highlight_color, "#ff90e8")
expect(Rails.cache.exist?(subject.custom_style_cache_name)).to eq(false)
expect(subject.custom_styles).to include("--accent: 255 144 232;--contrast-accent: 0 0 0")
subject.update_attribute(:background_color, "#fff")
expect(Rails.cache.exist?(subject.custom_style_cache_name)).to eq(false)
expect(subject.custom_styles).to include("--filled: 255 255 255")
expect(subject.custom_styles).to include("--color: 0 0 0")
subject.update_attribute(:font, "ABC Favorit")
expect(Rails.cache.exist?(subject.custom_style_cache_name)).to eq(false)
expect(subject.custom_styles).to include("--font-family: \"ABC Favorit\", \"ABC Favorit\", sans-serif")
expect(Rails.cache.exist?(subject.custom_style_cache_name)).to eq(true)
end
end
describe "#font_family" do
subject { create(:seller_profile) }
it "returns the active font, then ABC Favorit and a generic fallback" do
expect(subject.font_family).to eq(%("ABC Favorit", "ABC Favorit", sans-serif))
end
it "returns a serif fallback for a serif font" do
subject.update!(font: "Domine")
expect(subject.font_family).to eq(%("Domine", "ABC Favorit", serif))
end
it "returns a monospace fallback for a monospace font" do
subject.update!(font: "Roboto Mono")
expect(subject.font_family).to eq(%("Roboto Mono", "ABC Favorit", monospace))
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.