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/albania_bank_account_spec.rb
spec/models/albania_bank_account_spec.rb
# frozen_string_literal: true describe AlbaniaBankAccount do describe "#bank_account_type" do it "returns AL" do expect(create(:albania_bank_account).bank_account_type).to eq("AL") end end describe "#country" do it "returns AL" do expect(create(:albania_bank_account).country).to eq("AL") end end describe "#currency" do it "returns all" do expect(create(:albania_bank_account).currency).to eq("all") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:albania_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAAALTXXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:albania_bank_account, account_number_last_four: "4567").account_number_visual).to eq("AL******4567") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/norway_bank_account_spec.rb
spec/models/norway_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe NorwayBankAccount do describe "#bank_account_type" do it "returns NO" do expect(create(:norway_bank_account).bank_account_type).to eq("NO") end end describe "#country" do it "returns NO" do expect(create(:norway_bank_account).country).to eq("NO") end end describe "#currency" do it "returns nok" do expect(create(:norway_bank_account).currency).to eq("nok") end end describe "#routing_number" do it "returns nil" do expect(create(:norway_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(:norway_bank_account, account_number_last_four: "7947").account_number_visual).to eq("******7947") 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(:norway_bank_account)).to be_valid expect(build(:norway_bank_account, account_number: "NO9386011117947")).to be_valid no_bank_account = build(:norway_bank_account, account_number: "NO938601111") expect(no_bank_account).to_not be_valid expect(no_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") no_bank_account = build(:norway_bank_account, account_number: "NOABCDEFGHIJKLM") expect(no_bank_account).to_not be_valid expect(no_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") no_bank_account = build(:norway_bank_account, account_number: "NO9386011117947123") expect(no_bank_account).to_not be_valid expect(no_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") no_bank_account = build(:norway_bank_account, account_number: "129386011117947") expect(no_bank_account).to_not be_valid expect(no_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/oauth_application_spec.rb
spec/models/oauth_application_spec.rb
# frozen_string_literal: true require "spec_helper" describe OauthApplication do describe "validity" do before do @user = create(:user) end it "does not validate name uniqueness" do create(:oauth_application, owner: @user, name: :foo) expect(build(:oauth_application, owner: @user, name: :foo)).to be_valid end it "allows 2 applications to be created with the same name" do create(:oauth_application, owner: @user, name: :foo) create(:oauth_application, owner: @user, name: :foo) expect(OauthApplication.count).to eq 2 end it "allows applications to be created with affiliate_basis_points in an acceptable range" do create(:oauth_application, owner: @user, name: :foo, affiliate_basis_points: 1) create(:oauth_application, owner: @user, name: :foo, affiliate_basis_points: 6999) expect(OauthApplication.count).to eq 2 end it "does not allow applications to be created with invalid affiliate_basis_points" do invalid_app_1 = build(:oauth_application, owner: @user, name: :foo, affiliate_basis_points: -1) expect(invalid_app_1).to be_invalid invalid_app_2 = build(:oauth_application, owner: @user, name: :foo, affiliate_basis_points: 7001) expect(invalid_app_2).to be_invalid end end describe "#validate_file" do it "saves with no icons attached" do oauth_application = create(:oauth_application) expect(oauth_application.save).to eq(true) expect(oauth_application.errors.full_messages).to be_empty end it "saves with a valid icon type attached" do oauth_application = create(:oauth_application) oauth_application.file.attach(fixture_file_upload("smilie.png")) expect(oauth_application.save).to eq(true) expect(oauth_application.errors.full_messages).to be_empty end it "errors with invalid icon type attached" do oauth_application = create(:oauth_application) oauth_application.file.attach(fixture_file_upload("test-svg.svg")) expect(oauth_application.save).to eq(false) expect(oauth_application.errors.full_messages).to eq(["Invalid image type for icon, please try again."]) end end describe "Doorkeeper scopes" do before do @oauth_application = create(:oauth_application) end let(:doorkeeper_scopes) { Doorkeeper.configuration.scopes.map(&:to_sym) } let(:default_scopes) { Doorkeeper.configuration.default_scopes.map(&:to_sym) } let(:public_scopes) { Doorkeeper.configuration.public_scopes.map(&:to_sym) } let(:private_scopes) { %i[refund_sales mobile_api creator_api helper_api unfurl] } it "all public scopes are included in Doorkeeper's scopes" do public_scopes.each do |scope| expect(doorkeeper_scopes).to include(scope) end end it "all private scopes are included in Doorkeeper's scopes" do private_scopes.each do |scope| expect(doorkeeper_scopes).to include(scope) end end it "defines private scopes as neither public nor default" do expect(private_scopes).to match_array(doorkeeper_scopes - public_scopes - default_scopes) end it "includes public scopes in user-created applications" do public_scopes.each do |scope| expect(@oauth_application.scopes).to include(scope.to_s) end end it "does not include default scopes in user-created applications" do default_scopes.each do |scope| expect(@oauth_application.scopes).not_to include(scope.to_s) end end it "does not include private scopes in user-created applications" do private_scopes.each do |scope| expect(@oauth_application.scopes).not_to include(scope.to_s) end end end describe "#get_or_generate_access_token" do before do @oauth_application = create(:oauth_application) end it "generates new access token if none exist" do expect do access_token = @oauth_application.get_or_generate_access_token expect(access_token.scopes).to eq(Doorkeeper.configuration.public_scopes) end.to change(Doorkeeper::AccessToken, :count).by(1) end it "generates new access token if existing ones are revoked" do @oauth_application.get_or_generate_access_token Doorkeeper::AccessToken.revoke_all_for(@oauth_application.id, @oauth_application.owner) expect(@oauth_application.access_tokens.count).to eq(1) expect do access_token = @oauth_application.get_or_generate_access_token expect(access_token.revoked?).to be_falsey end.to change(Doorkeeper::AccessToken, :count).by(1) end it "returns an existing non-revoked access token if one exists" do @oauth_application.get_or_generate_access_token expect do @oauth_application.get_or_generate_access_token end.to_not change(Doorkeeper::AccessToken, :count) end context "when no access grant exists" do it "creates an access grant automatically" do expect(@oauth_application.access_grants.count).to eq(0) expect do @oauth_application.get_or_generate_access_token end.to change(Doorkeeper::AccessGrant, :count).by(1) expect(@oauth_application.access_grants.last.expires_in).to eq(60.years) end end context "when access grant already exists" do before do @oauth_application.get_or_generate_access_token # this will generate the access grant end it "does not create another access grant" do expect(@oauth_application.access_grants.count).to eq(1) expect do @oauth_application.get_or_generate_access_token end.to_not change(Doorkeeper::AccessGrant, :count) end end end describe "#mark_deleted!" do before do @oauth_application = create(:oauth_application) @oauth_application.get_or_generate_access_token create(:resource_subscription, oauth_application: @oauth_application) end it "marks connected resource subscription as deleted" do expect do @oauth_application.mark_deleted! end.to change { ResourceSubscription.alive.count }.by(-1) expect(@oauth_application.resource_subscriptions.alive.count).to eq(0) end it "revokes access grants" do expect do @oauth_application.mark_deleted! end.to change { @oauth_application.access_grants.where(revoked_at: nil).count }.by(-1) expect(@oauth_application.access_grants).to all be_revoked end it "revokes access tokens" do expect do @oauth_application.mark_deleted! end.to change { @oauth_application.access_tokens.where(revoked_at: nil).count }.by(-1) expect(@oauth_application.access_tokens).to all be_revoked end end describe "#revoke_access_for" do before do @oauth_application = create(:oauth_application) @subscriber_1 = create(:user) create("doorkeeper/access_token", application: @oauth_application, resource_owner_id: @subscriber_1.id, scopes: "view_sales") create(:resource_subscription, oauth_application: @oauth_application, user: @subscriber_1) @subscriber_2 = create(:user) create("doorkeeper/access_token", application: @oauth_application, resource_owner_id: @subscriber_2.id, scopes: "view_sales") create(:resource_subscription, oauth_application: @oauth_application, user: @subscriber_2) end it "revokes user's access" do expect do @oauth_application.revoke_access_for(@subscriber_1) end.to change { Doorkeeper::AccessToken.where(revoked_at: nil).count }.by(-1) expect(OauthApplication.authorized_for(@subscriber_1).count).to eq(0) expect(OauthApplication.authorized_for(@subscriber_2).count).to eq(1) end it "removes resource subscriptions for the user" do expect do @oauth_application.revoke_access_for(@subscriber_1) end.to change { ResourceSubscription.alive.count }.by(-1) expect(@oauth_application.resource_subscriptions.where(user: @subscriber_1).alive.count).to eq(0) expect(@oauth_application.resource_subscriptions.where(user: @subscriber_2).alive.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/bank_account_spec.rb
spec/models/bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe BankAccount do describe "routing_number" do let(:australian_bank_account) { build(:australian_bank_account) } it "returns the decrypted account number" do expect(australian_bank_account.send(:account_number_decrypted)).to eq("1234567") end end describe "#supports_instant_payouts?" do let(:bank_account) { create(:ach_account) } context "when stripe connect and external account IDs are not present" do it "returns false" do expect(bank_account.supports_instant_payouts?).to be false end end context "when stripe connect and external account IDs are present" do before do bank_account.update!( stripe_connect_account_id: "acct_123", stripe_external_account_id: "ba_456" ) end context "when external account supports instant payouts" do before do external_account = double(available_payout_methods: ["instant"]) allow(Stripe::Account).to receive(:retrieve_external_account) .with("acct_123", "ba_456") .and_return(external_account) end it "returns true" do expect(bank_account.supports_instant_payouts?).to be true end end context "when external account does not support instant payouts" do before do external_account = double(available_payout_methods: ["standard"]) allow(Stripe::Account).to receive(:retrieve_external_account) .with("acct_123", "ba_456") .and_return(external_account) end it "returns false" do expect(bank_account.supports_instant_payouts?).to be false end end context "when stripe API call fails" do before do allow(Stripe::Account).to receive(:retrieve_external_account) .and_raise(Stripe::StripeError.new) end it "returns false" do expect(bank_account.supports_instant_payouts?).to be false end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/oman_bank_account_spec.rb
spec/models/oman_bank_account_spec.rb
# frozen_string_literal: true describe OmanBankAccount do describe "#bank_account_type" do it "returns OM" do expect(create(:oman_bank_account).bank_account_type).to eq("OM") end end describe "#country" do it "returns OM" do expect(create(:oman_bank_account).country).to eq("OM") end end describe "#currency" do it "returns omr" do expect(create(:oman_bank_account).currency).to eq("omr") end end describe "#routing_number" do it "returns valid for 8 to 11 characters" do expect(create(:oman_bank_account, bank_code: "AAAAOMOM")).to be_valid expect(create(:oman_bank_account, bank_code: "AAAAOMOMX")).to be_valid expect(create(:oman_bank_account, bank_code: "AAAAOMOMXX")).to be_valid expect(create(:oman_bank_account, bank_code: "AAAAOMOMXXX")).to be_valid end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:oman_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789") end end describe "#validate_account_number" do it "allows records that are valid Omani IBANs" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:oman_bank_account, account_number: "OM030001234567890123456")).to be_valid expect(build(:oman_bank_account, account_number: "OM810180000001299123456")).to be_valid end it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:oman_bank_account)).to be_valid expect(build(:oman_bank_account, account_number: "123456")).to be_valid expect(build(:oman_bank_account, account_number: "000123456789")).to be_valid expect(build(:oman_bank_account, account_number: "1234567890123456")).to be_valid end it "rejects records that are invalid Omani IBANs" do allow(Rails.env).to receive(:production?).and_return(true) # all values are incorrect om_bank_account = build(:oman_bank_account, account_number: "OM000000000000000000000") expect(om_bank_account).not_to be_valid expect(om_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") # incorrect check digits om_bank_account = build(:oman_bank_account, account_number: "OM060001234567890123456") expect(om_bank_account).not_to be_valid expect(om_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") # incorrect country code om_bank_account = build(:oman_bank_account, account_number: "FR1420041010050500013M02606") expect(om_bank_account).not_to be_valid expect(om_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end it "rejects records that do not match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) om_bank_account = build(:oman_bank_account, account_number: "12345") expect(om_bank_account).not_to be_valid expect(om_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") om_bank_account = build(:oman_bank_account, account_number: "12345678901234567") expect(om_bank_account).not_to be_valid expect(om_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") om_bank_account = build(:oman_bank_account, account_number: "ABCDEF") expect(om_bank_account).not_to be_valid expect(om_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/comment_spec.rb
spec/models/comment_spec.rb
# frozen_string_literal: true require "spec_helper" describe Comment do describe "validations" do describe "content length" do context "when content is within the configured character limit" do subject(:comment) { build(:comment, commentable: create(:published_installment), content: "a" * 10_000) } it "marks the comment as valid" do expect(comment).to be_valid end end context "when content is bigger than the configured character limit" do subject(:comment) { build(:comment, commentable: create(:published_installment), content: "a" * 10_001) } it "marks the comment as invalid" do expect(comment).to be_invalid expect(comment.errors.full_messages).to match_array(["Content is too long (maximum is 10000 characters)"]) end end end describe "content_cannot_contain_adult_keywords" do context "when content contains an adult keyword" do context "when the author is not a team member" do subject(:comment) { build(:comment, commentable: create(:published_installment), content: "nsfw content") } it "marks the comment as invalid" do expect(comment).to be_invalid expect(comment.errors.full_messages).to match_array(["Adult keywords are not allowed"]) end end context "when the author is a team member" do subject(:comment) { build(:comment, commentable: create(:published_installment), content: "nsfw content", author: create(:user, is_team_member: true)) } it "marks the comment as valid" do expect(comment).to be_valid end end context "when author name is iffy" do subject(:comment) { build(:comment, commentable: create(:published_installment), author: nil, content: "nsfw content", author_name: "iffy") } it "marks the comment as valid" do expect(comment).to be_valid end end end context "when content does not contain adult keywords" do subject(:comment) { build(:comment, commentable: create(:published_installment)) } it "marks the comment as valid" do expect(comment).to be_valid end end end describe "depth numericality" do let(:commentable) { create(:published_installment) } let(:root_comment) { create(:comment, commentable:) } let(:reply1) { create(:comment, parent: root_comment, commentable:) } let(:reply_at_depth_2) { create(:comment, parent: reply1, commentable:) } let(:reply_at_depth_3) { create(:comment, parent: reply_at_depth_2, commentable:) } let(:reply_at_depth_4) { create(:comment, parent: reply_at_depth_3, commentable:) } context "when a comment exceeds maximum allowed depth" do subject(:reply_at_depth_5) { build(:comment, parent: reply_at_depth_4, commentable:) } it "marks the comment as invalid" do expect(reply_at_depth_5).to be_invalid expect(reply_at_depth_5.errors.full_messages).to match_array(["Depth must be less than or equal to 4"]) end end context "when depth is set manually" do subject(:comment) { build(:comment, commentable:, parent: root_comment, ancestry_depth: 3) } it "marks the comment as valid and sets the depth according to its actual position in its ancestry tree" do expect(comment).to be_valid expect(comment.depth).to eq(1) end end end end describe "callbacks" do describe "before_save" do describe "#trim_extra_newlines" do subject(:comment) { build(:comment, commentable: create(:published_installment)) } it "trims unnecessary additional newlines" do comment.content = "\n Here are things -\n\n1. One\n2. Two\n\t2.1 Two.One\n\t\t2.1.1 Two.One.One\n\t\t2.1.2 Two.One.Two\n\t\t\t2.1.2.1 Two.One.Two.One\n\t2.2 Two.Two\n3. Three\n\n\n\n\nWhat do you think?\n\n " expect do comment.save! end.to change { comment.content }.to("Here are things -\n\n1. One\n2. Two\n\t2.1 Two.One\n\t\t2.1.1 Two.One.One\n\t\t2.1.2 Two.One.Two\n\t\t\t2.1.2.1 Two.One.Two.One\n\t2.2 Two.Two\n3. Three\n\nWhat do you think?") end end end describe "after_commit" do describe "#notify_seller_of_new_comment" do let(:seller) { create(:named_seller) } let(:commentable) { create(:published_installment, seller:) } let(:comment) { build(:comment, commentable:, comment_type: Comment::COMMENT_TYPE_USER_SUBMITTED) } context "when a new comment is added" do context "when it is not a user submitted comment" do before do comment.comment_type = :flagged end it "does not send a notification to the seller" do expect do comment.save! end.to_not have_enqueued_mail(CommentMailer, :notify_seller_of_new_comment) end end context "when it is not a root comment" do before do comment.parent = create(:comment, commentable:) end it "does not send a notification to the seller" do expect do comment.save! end.to_not have_enqueued_mail(CommentMailer, :notify_seller_of_new_comment) end end context "when it is authored by the seller" do before do comment.author = seller end it "does not send a notification to the seller" do expect do comment.save! end.to_not have_enqueued_mail(CommentMailer, :notify_seller_of_new_comment) end end context "when the seller has opted out of comments email notifications" do before do seller.update!(disable_comments_email: true) end it "does not send a notification to the seller" do expect do comment.save! end.to_not have_enqueued_mail(CommentMailer, :notify_seller_of_new_comment) end end it "emails the seller" do expect do comment.save! end.to have_enqueued_mail(CommentMailer, :notify_seller_of_new_comment) end end context "when a comment gets updated" do let(:comment) { create(:comment, commentable:) } it "does not send a notification to the seller" do comment.update!(content: "new content") end end end end end describe "#mark_subtree_deleted!" do let(:commentable) { create(:published_installment) } let(:root_comment) { create(:comment, commentable:) } let!(:reply1) { create(:comment, parent: root_comment, commentable:) } let!(:reply2) { create(:comment, parent: root_comment, commentable:) } let!(:reply_at_depth_2) { create(:comment, parent: reply1, commentable:) } let!(:reply_at_depth_3) { create(:comment, parent: reply_at_depth_2, commentable:, deleted_at: 1.minute.ago) } let!(:reply_at_depth_4) { create(:comment, parent: reply_at_depth_3, commentable:) } it "soft deletes the comment along with its descendants" do expect do expect do expect do expect do reply1.mark_subtree_deleted! end.to change { reply1.reload.alive? }.from(true).to(false) .and change { reply_at_depth_2.reload.alive? }.from(true).to(false) .and change { reply_at_depth_4.reload.alive? }.from(true).to(false) end.to_not change { root_comment.reload.alive? } end.to_not change { reply2.reload.alive? } end.to_not change { reply_at_depth_3.reload.alive? } expect(root_comment.was_alive_before_marking_subtree_deleted).to be_nil expect(reply1.was_alive_before_marking_subtree_deleted).to be_nil expect(reply2.was_alive_before_marking_subtree_deleted).to be_nil expect(reply_at_depth_2.was_alive_before_marking_subtree_deleted).to eq(true) expect(reply_at_depth_3.was_alive_before_marking_subtree_deleted).to be_nil expect(reply_at_depth_4.was_alive_before_marking_subtree_deleted).to eq(true) end end describe "#mark_subtree_undeleted!" do let(:commentable) { create(:published_installment) } let(:root_comment) { create(:comment, commentable:) } let!(:reply1) { create(:comment, parent: root_comment, commentable:) } let!(:reply2) { create(:comment, parent: root_comment, commentable:) } let!(:reply_at_depth_2) { create(:comment, parent: reply1, commentable:) } let!(:reply_at_depth_3) { create(:comment, parent: reply_at_depth_2, commentable:) } before do reply1.mark_subtree_deleted! end it "marks the comment and its descendants undeleted" do expect do expect do expect do reply1.mark_subtree_undeleted! end.to change { reply1.reload.alive? }.from(false).to(true) .and change { reply_at_depth_2.reload.alive? }.from(false).to(true) .and change { reply_at_depth_3.reload.alive? }.from(false).to(true) end.to_not change { root_comment.reload.alive? } end.to_not change { reply2.reload.alive? } expect(Comment.all.map(&:was_alive_before_marking_subtree_deleted).uniq).to match_array([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/product_files_archive_spec.rb
spec/models/product_files_archive_spec.rb
# frozen_string_literal: true require "spec_helper" describe ProductFilesArchive do describe "callbacks" do it "saves `digest` when transitioning to the 'in_progress' state" do product = create(:product_with_files) product_files_archive = product.product_files_archives.create!(product_files: product.product_files) expect do product_files_archive.mark_in_progress end.to change { product_files_archive.reload.digest.present? }.to(true) end end describe "#belongs_to_product_or_installment_or_variant" do before do @product = create(:product) @variant = create(:variant) @installment = create(:installment) end def assert_no_errors(archive) expect(archive.valid?).to eq true expect(archive.errors.full_messages).to eq([]) end def assert_errors(archive) expect(archive.valid?).to eq false expect(archive.errors.full_messages).to include(/A product files archive needs to belong to an installment, a product or a variant/) end it "raises no errors if only one of link/variant/installment is present" do assert_no_errors(build(:product_files_archive, link: @product)) assert_no_errors(build(:product_files_archive, variant: @variant, link: nil)) assert_no_errors(build(:product_files_archive, installment: @installment, link: nil)) end it "raises an error if there are no associations or more associations than expected" do assert_errors(build(:product_files_archive, link: nil)) assert_errors(build(:product_files_archive, link: @product, installment: @installment)) assert_errors(build(:product_files_archive, link: nil, variant: @variant, installment: @installment)) assert_errors(build(:product_files_archive, variant: @variant, link: @product)) assert_errors(build(:product_files_archive, link: @product, variant: @variant, installment: @installment)) end end describe ".latest_ready_entity_archive" do it "returns the correct entity archive" do product = create(:product) file1 = create(:product_file, display_name: "File 1") file2 = create(:product_file, display_name: "File 2") file3 = create(:product_file, display_name: "File 3") file4 = create(:product_file, display_name: "File 4") product.product_files = [file1, file2, file3, file4] description = [ { "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 1", "uid" => SecureRandom.uuid }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } }, ] }, { "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 2", "uid" => SecureRandom.uuid }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file3.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file4.external_id, "uid" => SecureRandom.uuid } }, ] }] create(:rich_content, entity: product, description:) archive1 = product.product_files_archives.create!(product_files: [file1, file2]) archive1.mark_in_progress! expect(product.product_files_archives.latest_ready_entity_archive).to eq(nil) archive1.mark_ready! expect(product.product_files_archives.latest_ready_entity_archive).to eq(archive1) archive2 = product.product_files_archives.create!(product_files: [file1, file2]) expect(product.product_files_archives.latest_ready_entity_archive).to eq(archive1) archive1.mark_deleted! expect(product.product_files_archives.latest_ready_entity_archive).to eq(nil) archive2.mark_in_progress! expect(product.product_files_archives.latest_ready_entity_archive).to eq(nil) archive2.mark_ready! expect(product.product_files_archives.latest_ready_entity_archive).to eq(archive2) end end describe ".latest_ready_folder_archive" do it "returns the correct folder archive" do product = create(:product) file1 = create(:product_file, display_name: "File 1") file2 = create(:product_file, display_name: "File 2") file3 = create(:product_file, display_name: "File 3") file4 = create(:product_file, display_name: "File 4") product.product_files = [file1, file2, file3, file4] folder1_id = SecureRandom.uuid folder2_id = SecureRandom.uuid description = [{ "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 1", "uid" => folder1_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } }, ] }, { "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 2", "uid" => folder2_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file3.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file4.external_id, "uid" => SecureRandom.uuid } }, ] }] create(:rich_content, entity: product, description:) archive1 = product.product_files_archives.create!(folder_id: folder1_id, product_files: [file1, file2]) archive2 = product.product_files_archives.create!(folder_id: folder2_id, product_files: [file3, file4]) archive1.mark_in_progress! expect(product.product_files_archives.latest_ready_folder_archive(folder1_id)).to eq(nil) archive1.mark_ready! expect(product.product_files_archives.latest_ready_folder_archive(folder1_id)).to eq(archive1) archive2.mark_in_progress! expect(product.product_files_archives.latest_ready_folder_archive(folder2_id)).to eq(nil) archive2.mark_ready! expect(product.product_files_archives.latest_ready_folder_archive(folder2_id)).to eq(archive2) archive2.mark_deleted! expect(product.product_files_archives.latest_ready_folder_archive(folder2_id)).to eq(nil) new_archive2 = product.product_files_archives.create!(folder_id: folder2_id, product_files: [file3, file4]) new_archive2.mark_in_progress! expect(product.product_files_archives.latest_ready_folder_archive(folder2_id)).to eq(nil) new_archive2.mark_ready! expect(product.product_files_archives.latest_ready_folder_archive(folder2_id)).to eq(new_archive2) end end describe "#folder_archive?" do it "only returns true for folder archives" do product = create(:product) file1 = create(:product_file, display_name: "File 1") file2 = create(:product_file, display_name: "File 2") file3 = create(:product_file, display_name: "File 3") file4 = create(:product_file, display_name: "File 4") file5 = create(:product_file, display_name: "File 5") product.product_files = [file1, file2, file3, file4, file5] folder1_id = SecureRandom.uuid folder2_id = SecureRandom.uuid page1_description = [{ "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 1", "uid" => folder1_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } }, ] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Ignore me" }] }] page2_description = [{ "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 2", "uid" => folder2_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file3.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file4.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file5.external_id, "uid" => SecureRandom.uuid } }, ] }] create(:rich_content, entity: product, description: page1_description) create(:rich_content, entity: product, description: page2_description) folder1_archive = product.product_files_archives.create!(folder_id: folder1_id, product_files: [file1, file2]) folder2_archive = product.product_files_archives.create!(folder_id: folder2_id, product_files: [file3, file4, file5]) entity_archive = product.product_files_archives.create!(product_files: [file3, file4, file5]) post = create(:installment, product_files: [create(:product_file), create(:product_file)]) installment_archive = post.product_files_archives.create!(product_files: post.product_files) variant = create(:variant, product_files: [create(:product_file), create(:product_file)]) variant_archive = variant.product_files_archives.create(product_files: variant.product_files) expect(folder1_archive.folder_archive?).to eq(true) expect(folder2_archive.folder_archive?).to eq(true) expect(entity_archive.folder_archive?).to eq(false) expect(installment_archive.folder_archive?).to eq(false) expect(variant_archive.folder_archive?).to eq(false) end end describe "#files_digest" do context "when there is no rich content" do it "returns the correct digest" do product = create(:product) folder_1 = create(:product_folder, link: product, name: "folder 1") folder_2 = create(:product_folder, link: product, name: "folder 2") file_1 = create(:product_file, link: product, description: "pencil", url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png", folder_id: folder_1.id) file_2 = create(:product_file, link: product, description: "manual", url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/manual.pdf", folder_id: folder_2.id) file_3 = create(:product_file, link: product, description: "file without a folder", url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/manual.pdf", folder_id: nil) archive = product.product_files_archives.create!(product_files: product.product_files) expect { archive.mark_in_progress }.to change { archive.reload.digest.present? }.to(true) expect(archive.digest).to eq(Digest::SHA1.hexdigest([ "#{file_1.folder.external_id}/#{file_1.folder.name}/#{file_1.external_id}/#{file_1.name_displayable}", "#{file_2.folder.external_id}/#{file_2.folder.name}/#{file_2.external_id}/#{file_2.name_displayable}", "#{file_3.external_id}/#{file_3.name_displayable}"].sort.join("\n"))) archive_copy = product.product_files_archives.create!(product_files: product.product_files) expect { archive_copy.mark_in_progress }.to change { archive_copy.reload.digest.present? }.to(true) # Ensure digests produce consistent results expect(archive.digest).to eq(archive_copy.digest) end end context "entity archives" do it "returns the same digest when nothing has changed" do product = create(:product_with_files) archive1 = product.product_files_archives.create!(product_files: product.product_files) expect { archive1.mark_in_progress }.to change { archive1.reload.digest.present? }.to(true) archive2 = product.product_files_archives.create!(product_files: product.product_files) expect { archive2.mark_in_progress }.to change { archive2.reload.digest.present? }.to(true) expect(archive1.digest).to eq(archive2.digest) end it "returns the correct digest" do product = create(:product) file1 = create(:product_file, display_name: "File 1") file2 = create(:product_file, display_name: "File 2") file3 = create(:product_file, display_name: "File 3") file4 = create(:product_file, display_name: "File 4") file5 = create(:product_file, display_name: "File 5") product.product_files = [file1, file2, file3, file4, file5] folder1_id = SecureRandom.uuid folder2_id = SecureRandom.uuid page1_description = [{ "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 1", "uid" => folder1_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } }, ] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Ignore me" }] }] page2_description = [{ "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 2", "uid" => folder2_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file3.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file4.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file5.external_id, "uid" => SecureRandom.uuid } }, ] }] page1 = create(:rich_content, title: "Page 1", entity: product, description: page1_description) page2 = create(:rich_content, title: "Page 2", entity: product, description: page2_description) archive = product.product_files_archives.create!(product_files: [file1, file2, file3, file4, file5]) expect { archive.mark_in_progress }.to change { archive.reload.digest.present? }.to(true) expect(archive.digest).to eq(Digest::SHA1.hexdigest([ "#{page1.external_id}/Page 1/#{folder1_id}/folder 1/#{file1.external_id}/File 1", "#{page1.external_id}/Page 1/#{folder1_id}/folder 1/#{file2.external_id}/File 2", "#{page2.external_id}/Page 2/#{folder2_id}/folder 2/#{file3.external_id}/File 3", "#{page2.external_id}/Page 2/#{folder2_id}/folder 2/#{file4.external_id}/File 4", "#{page2.external_id}/Page 2/#{folder2_id}/folder 2/#{file5.external_id}/File 5"].sort.join("\n"))) archive2 = product.product_files_archives.create!(product_files: [file1, file2, file3, file4, file5]) expect { archive2.mark_in_progress }.to change { archive2.reload.digest.present? }.to(true) # Ensure digests produce consistent results expect(archive.digest).to eq(archive2.digest) end end context "folder archives" do it "returns the correct digests" do product = create(:product) file1 = create(:product_file, display_name: "File 1") file2 = create(:product_file, display_name: "File 2") file3 = create(:product_file, display_name: "File 3") file4 = create(:product_file, display_name: "File 4") file5 = create(:product_file, display_name: "File 5") product.product_files = [file1, file2, file3, file4, file5] folder1_id = SecureRandom.uuid folder2_id = SecureRandom.uuid description = [{ "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 1", "uid" => folder1_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } }, ] }, { "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 2", "uid" => folder2_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file3.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file4.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file5.external_id, "uid" => SecureRandom.uuid } }, ] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Ignore me" }] }] create(:rich_content, entity: product, description:) archive1 = product.product_files_archives.create!(folder_id: folder1_id, product_files: [file1, file2]) expect { archive1.mark_in_progress }.to change { archive1.reload.digest.present? }.to(true) expect(archive1.digest).to eq(Digest::SHA1.hexdigest(["#{folder1_id}/folder 1/#{file1.external_id}/File 1", "#{folder1_id}/folder 1/#{file2.external_id}/File 2"].sort.join("\n"))) archive2 = product.product_files_archives.create!(folder_id: folder2_id, product_files: [file3, file4, file5]) expect { archive2.mark_in_progress }.to change { archive2.reload.digest.present? }.to(true) expect(archive2.digest).to eq(Digest::SHA1.hexdigest(["#{folder2_id}/folder 2/#{file3.external_id}/File 3", "#{folder2_id}/folder 2/#{file4.external_id}/File 4", "#{folder2_id}/folder 2/#{file5.external_id}/File 5"].sort.join("\n"))) # Ensure digests produce consistent results archive1_copy = product.product_files_archives.create!(folder_id: folder1_id, product_files: [file1, file2]) expect { archive1_copy.mark_in_progress }.to change { archive1_copy.reload.digest.present? }.to(true) expect(archive1.digest).to eq(archive1_copy.digest) archive2_copy = product.product_files_archives.create!(folder_id: folder2_id, product_files: [file3, file4, file5]) expect { archive2_copy.mark_in_progress }.to change { archive2_copy.reload.digest.present? }.to(true) expect(archive2.digest).to eq(archive2_copy.digest) end end end context "scopes" do before do post = create(:installment) post.product_files = [create(:product_file), create(:product_file)] post.save! installment_archive = post.product_files_archives.create installment_archive.product_files = post.product_files installment_archive.save! variant = create(:variant) variant.product_files = [create(:product_file), create(:product_file)] variant.save! variant_archive = variant.product_files_archives.create variant_archive.product_files = variant.product_files variant_archive.save! product = create(:product) file1 = create(:product_file) file2 = create(:product_file) product.product_files = [file1, file2] product.save! folder1_id = SecureRandom.uuid create(:rich_content, entity: product, description: [ { "type" => "fileEmbedGroup", "attrs" => { "name" => "Folder 1", "uid" => folder1_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } }, ] } ]) product.product_files_archives.create!(product_files: product.product_files) product.product_files_archives.create!(folder_id: folder1_id, product_files: [file1, file2]) end describe ".entity_archives" do it "only returns entity archives" do expect(ProductFilesArchive.entity_archives.count).to eq(3) expect(ProductFilesArchive.entity_archives.any?(&:folder_archive?)).to eq(false) end end describe ".folder_archives" do it "only returns folder archives" do expect(ProductFilesArchive.folder_archives.count).to eq(1) expect(ProductFilesArchive.folder_archives.first.folder_archive?).to eq(true) end end end it "has an initial status of queueing" do expect(build(:product_files_archive).send(:product_files_archive_state)).to eq("queueing") end it "is create-able through a link" do link = create(:product) link.product_files << create(:product_file) link.product_files << create(:product_file) link.save product_files_archive = link.product_files_archives.create product_files_archive.product_files = link.product_files product_files_archive.save expect(product_files_archive.product_files.count).to eq(2) expect(product_files_archive.class.name).to eq("ProductFilesArchive") expect(product_files_archive.product_files_archive_state).to eq("queueing") expect(product_files_archive.link).to be(link) expect(product_files_archive.installment).to be_nil expect(product_files_archive.product_files.to_a).to eq(link.product_files.to_a) expect(product_files_archive.variant).to be_nil end it "is create-able through an installment" do post = create(:installment) post.product_files << create(:product_file) post.product_files << create(:product_file) post.product_files << create(:product_file) post.save product_files_archive = post.product_files_archives.create product_files_archive.product_files = post.product_files product_files_archive.save expect(product_files_archive.product_files.count).to eq(3) expect(product_files_archive.class.name).to eq("ProductFilesArchive") expect(product_files_archive.product_files_archive_state).to eq("queueing") expect(product_files_archive.installment).to be(post) expect(product_files_archive.link).to be_nil expect(product_files_archive.product_files.to_a).to eq(post.product_files.to_a) expect(product_files_archive.variant).to be_nil end it "is create-able through a variant" do variant = create(:variant) variant.product_files << create(:product_file) variant.product_files << create(:product_file) variant.save! product_files_archive = variant.product_files_archives.create product_files_archive.product_files = variant.product_files product_files_archive.save! expect(product_files_archive.product_files.count).to eq(2) expect(product_files_archive.class.name).to eq("ProductFilesArchive") expect(product_files_archive.product_files_archive_state).to eq("queueing") expect(product_files_archive.variant).to be(variant) expect(product_files_archive.installment).to be_nil expect(product_files_archive.link).to be_nil expect(product_files_archive.product_files.to_a).to eq(variant.product_files.to_a) end it "schedules an UpdateProductFilesArchiveWorker job" do link = create(:product) link.product_files << create(:product_file) link.product_files << create(:product_file) link.save product_files_archive = link.product_files_archives.create product_files_archive.product_files = link.product_files product_files_archive.save! expect(UpdateProductFilesArchiveWorker).to have_enqueued_sidekiq_job(product_files_archive.id) end describe "#has_cdn_url?" do it "returns a truthy value when the CDN URL is in a specific format" do product_files_archive = create(:product_files_archive) expect(product_files_archive.has_cdn_url?).to be_truthy end it "returns a falsey value when the CDN URL is not in the regular Gumroad format" do product_files_archive = build(:product_files_archive, url: "https:/unknown.com/manual.pdf") expect(product_files_archive.has_cdn_url?).to be_falsey end end context "when s3 directory is empty" do it "has unique s3_key for the same product" do product = create(:product) product_files_archives = create_list(:product_files_archive, 2, link: product) s3_double = double allow(s3_double).to receive(:list_objects).times.and_return([]) allow(Aws::S3::Client).to receive(:new).and_return(s3_double) expect(product_files_archives.first.s3_key).not_to eq(product_files_archives.last.s3_key) end end describe "#s3_directory_uri" do it "is unique for different archives of the same product" do product = create(:product) archives = create_list(:product_files_archive, 2, link: product) expect(archives.first.s3_directory_uri).not_to eq(archives.last.s3_directory_uri) end end describe "#set_url_if_not_present" do it "sets the url if not present" do product = create(:product) product_files_archive = create(:product_files_archive_without_url, link: product) product_files_archive.set_url_if_not_present expect(product_files_archive.url).to start_with("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments_zipped/") expect(product_files_archive.url.split("/").last).to eq("The_Works_of_Edgar_Gumstein.zip") end end describe "#construct_url" do it "uses the entity name for an entity archive" do product = create(:product, name: "Product name") entity_archive = create(:product_files_archive_without_url, link: product) entity_archive.set_url_if_not_present expect(entity_archive.url).to start_with("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments_zipped/") expect(entity_archive.url.split("/").last).to eq("Product_name.zip") end it "uses the folder name for a folder archive" do product = create(:product) file1 = create(:product_file) file2 = create(:product_file) product.product_files = [file1, file2] folder_id = SecureRandom.uuid create(:rich_content, entity: product, description: [ { "type" => "fileEmbedGroup", "attrs" => { "name" => "Folder 1", "uid" => folder_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } }, ] } ]) folder_archive = create(:product_files_archive_without_url, link: product, folder_id:, product_files: [file1, file2]) folder_archive.set_url_if_not_present expect(folder_archive.url).to start_with("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments_zipped/") expect(folder_archive.url.split("/").last).to eq("Folder_1.zip") end end describe "#needs_updating?" do before do @product = create(:product) @product_file1 = create(:product_file, display_name: "First file") @product_file2 = create(:product_file, display_name: "Second file") @product_file3 = create(:product_file, display_name: "Third file") @product_file4 = create(:product_file, display_name: "Fourth file") @product_file5_name = "Fifth file" @product_file5 = create(:product_file, display_name: @product_file5_name) @product.product_files = [@product_file1, @product_file2, @product_file3, @product_file4, @product_file5] @product.save! folder1_uid = SecureRandom.uuid @page1 = create(:rich_content, entity: @product, description: [ { "type" => "fileEmbed", "attrs" => { "id" => @product_file1.external_id, "uid" => "64e84875-c795-567c-d2dd-96336ab093d5" } }, ]) @page2 = create(:rich_content, entity: @product, title: "Page 2", description: [ { "type" => "fileEmbedGroup", "attrs" => { "name" => "", "uid" => folder1_uid }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => @product_file2.external_id, "uid" => "0c042930-2df1-4583-82ef-a63172138683" } }, ] }, { "type" => "fileEmbedGroup", "attrs" => { "name" => "" }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => @product_file3.external_id, "uid" => "0c042930-2df1-4583-82ef-a6317213868f" } }, ] }, ]) @page3 = create(:rich_content, entity: @product, description: [ { "type" => "fileEmbedGroup", "attrs" => { "name" => "Folder 3" }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => @product_file4.external_id, "uid" => "0c042930-2df1-4583-82ef-a6317213868w" } }, { "type" => "fileEmbed", "attrs" => { "id" => @product_file5.external_id, "uid" => "0c042930-2df1-4583-82ef-a63172138681" } }, ] }, ]) @product_files_archive = @product.product_files_archives.create @product_files_archive.product_files = @product.product_files @product_files_archive.mark_in_progress! @product_files_archive.mark_ready! @folder1_archive = @product.product_files_archives.create(folder_id: folder1_uid) @folder1_archive.product_files = [@product_file2, @product_file3] @folder1_archive.mark_in_progress! @folder1_archive.mark_ready! @files = @product_files_archive.product_files.archivable end it "returns false when the files and folders in the rich content are unchanged" do expect(@product_files_archive.needs_updating?(@files)).to be(false) end it "returns true when a file changes but the filename stays the same" do folder_id = SecureRandom.uuid archive = @product.product_files_archives.create(folder_id:, product_files: [@product_file4, @product_file5]) archive.mark_in_progress! archive.mark_ready! description = [ { "type" => "fileEmbedGroup", "attrs" => { "name" => "Folder 3", "uid" => folder_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => @product_file4.external_id, "uid" => "0c042930-2df1-4583-82ef-a6317213868w" } }, { "type" => "fileEmbed", "attrs" => { "id" => create(:product_file, link: @product, display_name: @product_file5_name).external_id, "uid" => SecureRandom.uuid } }, ] }, ] @page3.update!(description:) @product_file5.mark_deleted! expect(ProductFilesArchive.find(archive.id).needs_updating?(@product.product_files.alive)).to be(true) end it "returns true when a file is renamed" do @product_file1.update!(display_name: "New file name") expect(@product_files_archive.reload.needs_updating?(@files)).to be(true) end it "returns true when a page containing files is renamed" do @page1.update!(title: "New title") expect(@product_files_archive.reload.needs_updating?(@files)).to be(true) end it "returns true when a page containing files is deleted" do @page1.mark_deleted! expect(@product_files_archive.reload.needs_updating?(@files)).to be(true) end it "returns true when a page is added containing files" do @product_file6 = create(:product_file, display_name: "Sixth file") @product.product_files << @product_file6 @product_files_archive.product_files << @product_file6 create(:rich_content, entity: @product, description: [ { "type" => "fileEmbed", "attrs" => { "id" => @product_file6.external_id, "uid" => "64e84875-c795-567c-d2dd-96336ab093fg" } }, ]) expect(@product_files_archive.reload.needs_updating?(@product_files_archive.product_files.not_external_link.not_stream_only.in_order)).to be(true) end it "returns false when a page is added without files" do create(:rich_content, entity: @product, description: [ { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "This is a paragraph" }] }, ]) expect(@product_files_archive.reload.needs_updating?(@files)).to be(false) end it "returns true when a file group's name is changed" do @page3.description.first["attrs"] = { "name" => "New folder name", "uid" => SecureRandom.uuid } @page3.save! expect(@product_files_archive.reload.needs_updating?(@files)).to be(true) end it "returns true when a file group is deleted" do @page3.description.delete_at(0) @page3.save! expect(@product_files_archive.reload.needs_updating?(@files)).to be(true) end it "returns true when a file group is added" do @product_file6 = create(:product_file, display_name: "Sixth file") @product.product_files << @product_file6 @product_files_archive.product_files << @product_file6 @page3.description << { "type" => "fileEmbedGroup", "attrs" => { "name" => "New folder", "uid" => SecureRandom.uuid }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => @product_file6.external_id, "uid" => SecureRandom.uuid } }, ] } @page3.save! expect(@product_files_archive.reload.needs_updating?(@files)).to be(true) end it "returns true when a file is added to a file group" do @product_file6 = create(:product_file, display_name: "Sixth file") @product.product_files << @product_file6 @product_files_archive.product_files << @product_file6 @page3.description.first["content"] << { "type" => "fileEmbed", "attrs" => { "id" => @product_file6.external_id, "uid" => SecureRandom.uuid } } @page3.save! expect(@product_files_archive.reload.needs_updating?(@files)).to be(true) end it "returns true when a file is removed from a file group" do @page3.description.first["content"].delete_at(0) @page3.save!
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/korea_bank_account_spec.rb
spec/models/korea_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe KoreaBankAccount do describe "#bank_account_type" do it "returns korea" do expect(create(:korea_bank_account).bank_account_type).to eq("KR") end end describe "#country" do it "returns KR" do expect(create(:korea_bank_account).country).to eq("KR") end end describe "#currency" do it "returns krw" do expect(create(:korea_bank_account).currency).to eq("krw") end end describe "#routing_number" do it "returns valid for 11 digits" do ba = create(:korea_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("SGSEKRSLXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:korea_bank_account, account_number_last_four: "8912").account_number_visual).to eq("******8912") end end describe "#validate_bank_code" do it "allows 8 to 11 characters only" do expect(build(:korea_bank_account, bank_code: "TESTKR00")).to be_valid expect(build(:korea_bank_account, bank_code: "BANKKR001")).to be_valid expect(build(:korea_bank_account, bank_code: "CASHKR00123")).to be_valid expect(build(:korea_bank_account, bank_code: "ABCD")).not_to be_valid expect(build(:korea_bank_account, bank_code: "1234")).not_to be_valid expect(build(:korea_bank_account, bank_code: "TESTKR0")).not_to be_valid expect(build(:korea_bank_account, bank_code: "TESTKR001234")).not_to be_valid end end describe "#validate_account_number" do it "allows records that match the required account number regex" do expect(build(:korea_bank_account, account_number: "00123456789")).to be_valid expect(build(:korea_bank_account, account_number: "0000123456789")).to be_valid expect(build(:korea_bank_account, account_number: "000000123456789")).to be_valid kr_bank_account = build(:korea_bank_account, account_number: "ABCDEFGHIJKL") expect(kr_bank_account).to_not be_valid expect(kr_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") kr_bank_account = build(:korea_bank_account, account_number: "8937040044053201300000") expect(kr_bank_account).to_not be_valid expect(kr_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") kr_bank_account = build(:korea_bank_account, account_number: "12345") expect(kr_bank_account).to_not be_valid expect(kr_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/community_notification_setting_spec.rb
spec/models/community_notification_setting_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe CommunityNotificationSetting do subject(:notification_setting) { build(:community_notification_setting) } describe "associations" do it { is_expected.to belong_to(:user) } it { is_expected.to belong_to(:seller).class_name("User") } end describe "validations" do it { is_expected.to validate_uniqueness_of(:user_id).scoped_to(:seller_id) } it { is_expected.to define_enum_for(:recap_frequency) .with_values(daily: "daily", weekly: "weekly") .backed_by_column_of_type(:string) .with_prefix(:recap_frequency) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/mauritius_bank_account_spec.rb
spec/models/mauritius_bank_account_spec.rb
# frozen_string_literal: true describe MauritiusBankAccount do describe "#bank_account_type" do it "returns MU" do expect(create(:mauritius_bank_account).bank_account_type).to eq("MU") end end describe "#country" do it "returns MA" do expect(create(:mauritius_bank_account).country).to eq("MU") end end describe "#currency" do it "returns mad" do expect(create(:mauritius_bank_account).currency).to eq("mur") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:mauritius_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAAMUMUXYZ") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:mauritius_bank_account, account_number_last_four: "9123").account_number_visual).to eq("MU******9123") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/dispute_evidence_spec.rb
spec/models/dispute_evidence_spec.rb
# frozen_string_literal: true require "spec_helper" describe DisputeEvidence do let(:dispute_evidence) do DisputeEvidence.create!( dispute: create(:dispute), purchased_at: "", customer_purchase_ip: "", customer_email: " joe@example.com", customer_name: " Joe Doe ", billing_address: " 123 Sample St, San Francisco, CA, 12343, United States ", shipping_address: " 123 Sample St, San Francisco, CA, 12343, United States ", shipped_at: "", shipping_carrier: " USPS ", shipping_tracking_number: " 1234567890 ", uncategorized_text: " Sample evidence text ", product_description: " Sample product description ", resolved_at: "", reason_for_winning: " Sample reason for winning ", cancellation_rebuttal: " Sample cancellation rebuttal ", refund_refusal_explanation: " Sample refund refusal explanation ", ) end describe "stripped_fields" do it "strips fields" do expect(dispute_evidence.purchased_at).to be(nil) expect(dispute_evidence.customer_purchase_ip).to be(nil) expect(dispute_evidence.customer_email).to eq("joe@example.com") expect(dispute_evidence.customer_name).to eq("Joe Doe") expect(dispute_evidence.billing_address).to eq("123 Sample St, San Francisco, CA, 12343, United States") expect(dispute_evidence.shipping_address).to eq("123 Sample St, San Francisco, CA, 12343, United States") expect(dispute_evidence.shipped_at).to be(nil) expect(dispute_evidence.shipping_carrier).to eq("USPS") expect(dispute_evidence.shipping_tracking_number).to eq("1234567890") expect(dispute_evidence.uncategorized_text).to eq("Sample evidence text") expect(dispute_evidence.resolved_at).to be(nil) expect(dispute_evidence.product_description).to eq("Sample product description") expect(dispute_evidence.reason_for_winning).to eq("Sample reason for winning") expect(dispute_evidence.cancellation_rebuttal).to eq("Sample cancellation rebuttal") expect(dispute_evidence.refund_refusal_explanation).to eq("Sample refund refusal explanation") end end describe "policy fields" do before do dispute_evidence.dispute = dispute dispute_evidence.policy_disclosure = "Sample policy disclosure" dispute_evidence.policy_image.attach( Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "smilie.png"), "image/png") ) dispute_evidence.save! end context "when the product is not membership" do let(:dispute) { create(:dispute_formalized) } it "it assigns data to refund_policy_* fields" do expect(dispute_evidence.refund_policy_disclosure).to eq("Sample policy disclosure") expect(dispute_evidence.cancellation_policy_disclosure).to be(nil) expect(dispute_evidence.refund_policy_image.attached?).to be(true) expect(dispute_evidence.cancellation_policy_image.attached?).to be(false) end end context "when the product is membership" do let(:dispute) { create(:dispute_formalized, purchase: create(:membership_purchase)) } it "it assigns data to cancellation_policy_* fields" do expect(dispute_evidence.cancellation_policy_disclosure).to eq("Sample policy disclosure") expect(dispute_evidence.refund_policy_disclosure).to be(nil) expect(dispute_evidence.cancellation_policy_image.attached?).to be(true) expect(dispute_evidence.refund_policy_image.attached?).to be(false) end end context "when the product is a legacy subscription" do let(:dispute) do product = create(:subscription_product) subscription = create(:subscription, link: product, created_at: 3.days.ago) purchase = create(:purchase, is_original_subscription_purchase: true, link: product, subscription:) create(:dispute_formalized, purchase:) end it "it assigns data to cancellation_policy_* fields" do expect(dispute_evidence.cancellation_policy_disclosure).to eq("Sample policy disclosure") expect(dispute_evidence.refund_policy_disclosure).to be(nil) expect(dispute_evidence.cancellation_policy_image.attached?).to be(true) expect(dispute_evidence.refund_policy_image.attached?).to be(false) end end end describe "validations" do describe "customer_communication_file_size and all_files_size_within_limit" do context "when the file size is too big" do before do dispute_evidence.customer_communication_file.attach( Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "big_file.txt"), "image/jpeg") ) end it "returns error" do expect(dispute_evidence.valid?).to eq(false) expect(dispute_evidence.errors[:base]).to eq( [ "The file exceeds the maximum size allowed.", "Uploaded files exceed the maximum size allowed by Stripe." ] ) end end end describe "customer_communication_file_type" do context "when the content type is not allowed" do before do dispute_evidence.customer_communication_file.attach( Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "blah.txt"), "text/plain") ) end it "returns error" do expect(dispute_evidence.valid?).to eq(false) expect(dispute_evidence.errors[:base]).to eq(["Invalid file type."]) end end end it "validates length of reason_for_winning" do dispute_evidence.reason_for_winning = "a" * 3_001 expect(dispute_evidence.valid?).to eq(false) expect(dispute_evidence.errors[:reason_for_winning]).to eq(["is too long (maximum is 3000 characters)"]) end it "validates length of refund_refusal_explanation" do dispute_evidence.refund_refusal_explanation = "a" * 3_001 expect(dispute_evidence.valid?).to eq(false) expect(dispute_evidence.errors[:refund_refusal_explanation]).to eq(["is too long (maximum is 3000 characters)"]) end it "validates length of cancellation_rebuttal" do dispute_evidence.cancellation_rebuttal = "a" * 3_001 expect(dispute_evidence.valid?).to eq(false) expect(dispute_evidence.errors[:cancellation_rebuttal]).to eq(["is too long (maximum is 3000 characters)"]) end end describe "#hours_left_to_submit_evidence" do context "when seller hasn't been contacted" do before do dispute_evidence.update_as_not_seller_contacted! end it "returns 0" do expect(dispute_evidence.hours_left_to_submit_evidence).to eq(0) end end context "when seller has been contacted" do before do dispute_evidence.update!(seller_contacted_at: 3.hours.ago) end it "returns correct value" do expect(dispute_evidence.hours_left_to_submit_evidence).to eq(DisputeEvidence::SUBMIT_EVIDENCE_WINDOW_DURATION_IN_HOURS - 3) end end end describe "#customer_communication_file_max_size" do before do dispute_evidence.receipt_image.attach( Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "smilie.png"), "image/png") ) end it "returns correct value" do expect(dispute_evidence.customer_communication_file_max_size < DisputeEvidence::STRIPE_MAX_COMBINED_FILE_SIZE).to be(true) expect(dispute_evidence.customer_communication_file_max_size).to eq( DisputeEvidence::STRIPE_MAX_COMBINED_FILE_SIZE - dispute_evidence.receipt_image.byte_size.to_i ) end end describe "#policy_image_max_size" do before do dispute_evidence.receipt_image.attach( Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "smilie.png"), "image/png") ) end it "returns correct value" do expect(dispute_evidence.policy_image_max_size < DisputeEvidence::STRIPE_MAX_COMBINED_FILE_SIZE).to be(true) expect(dispute_evidence.policy_image_max_size).to eq( DisputeEvidence::STRIPE_MAX_COMBINED_FILE_SIZE - dispute_evidence.receipt_image.byte_size.to_i - DisputeEvidence::MINIMUM_RECOMMENDED_CUSTOMER_COMMUNICATION_FILE_SIZE ) end end describe "#for_subscription_purchase?" do let!(:charge) do charge = create(:charge) charge.purchases << create(:purchase) charge.purchases << create(:purchase) charge.purchases << create(:purchase) charge end let!(:dispute_evidence) do DisputeEvidence.create!( dispute: create(:dispute_formalized_on_charge, charge: charge), purchased_at: "", customer_purchase_ip: "", customer_email: " joe@example.com", customer_name: " Joe Doe ", billing_address: " 123 Sample St, San Francisco, CA, 12343, United States ", shipping_address: " 123 Sample St, San Francisco, CA, 12343, United States ", shipped_at: "", shipping_carrier: " USPS ", shipping_tracking_number: " 1234567890 ", uncategorized_text: " Sample evidence text ", product_description: " Sample product description ", resolved_at: "" ) end it "returns false if charge does not include any subscription purchase" do expect(dispute_evidence.for_subscription_purchase?).to be false end it "returns true if charge includes a subscription purchase" do charge.purchases << create(:membership_purchase) expect(dispute_evidence.for_subscription_purchase?).to be true end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/taiwan_bank_account_spec.rb
spec/models/taiwan_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe TaiwanBankAccount do describe "#bank_account_type" do it "returns Taiwan" do expect(create(:taiwan_bank_account).bank_account_type).to eq("TW") end end describe "#country" do it "returns TW" do expect(create(:taiwan_bank_account).country).to eq("TW") end end describe "#currency" do it "returns twd" do expect(create(:taiwan_bank_account).currency).to eq("twd") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:taiwan_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAATWTXXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:taiwan_bank_account, account_number_last_four: "4567").account_number_visual).to eq("******4567") end end describe "#validate_bank_code" do it "allows 8 to 11 characters only" do expect(build(:taiwan_bank_account, bank_code: "AAAATWTXXXX")).to be_valid expect(build(:taiwan_bank_account, bank_code: "AAAATWTX")).to be_valid expect(build(:taiwan_bank_account, bank_code: "AAAATWT")).not_to be_valid expect(build(:taiwan_bank_account, bank_code: "AAAATWTXXXXX")).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/discord_integration_spec.rb
spec/models/discord_integration_spec.rb
# frozen_string_literal: true require "spec_helper" describe DiscordIntegration do it "creates the correct json details" do integration = create(:discord_integration) DiscordIntegration::INTEGRATION_DETAILS.each do |detail| expect(integration.respond_to?(detail)).to eq true end end it "saves details correctly" do integration = create(:discord_integration) expect(integration.type).to eq(Integration.type_for(Integration::DISCORD)) expect(integration.server_id).to eq("0") expect(integration.server_name).to eq("Gaming") expect(integration.username).to eq("gumbot") expect(integration.keep_inactive_members).to eq(false) end describe "#as_json" do it "returns the correct json object" do integration = create(:discord_integration) expect(integration.as_json).to eq({ keep_inactive_members: false, name: "discord", integration_details: { "server_id" => "0", "server_name" => "Gaming", "username" => "gumbot", } }) end end describe ".is_enabled_for" do it "returns true if a discord integration is enabled on the product" do product = create(:product, active_integrations: [create(:discord_integration)]) purchase = create(:purchase, link: product) expect(DiscordIntegration.is_enabled_for(purchase)).to eq(true) end it "returns false if a discord integration is not enabled on the product" do product = create(:product, active_integrations: [create(:circle_integration)]) purchase = create(:purchase, link: product) expect(DiscordIntegration.is_enabled_for(purchase)).to eq(false) end it "returns false if a deleted discord integration exists on the product" do product = create(:product, active_integrations: [create(:discord_integration)]) purchase = create(:purchase, link: product) product.product_integrations.first.mark_deleted! expect(DiscordIntegration.is_enabled_for(purchase)).to eq(false) end end describe ".discord_user_id_for" do it "returns discord_user_id for a purchase with an enabled discord integration" do purchase_integration = create(:discord_purchase_integration) expect(DiscordIntegration.discord_user_id_for(purchase_integration.purchase)).to eq("user-0") end it "returns nil for a purchase without an enabled discord integration" do purchase = create(:purchase, link: create(:product, active_integrations: [create(:circle_integration)])) expect(DiscordIntegration.discord_user_id_for(purchase)).to be_nil end it "returns nil for a purchase without an active discord integration" do purchase_integration = create(:discord_purchase_integration, deleted_at: 1.day.ago) expect(DiscordIntegration.discord_user_id_for(purchase_integration.purchase)).to be_nil end it "returns nil for a purchase with a deleted discord integration" do purchase_integration = create(:discord_purchase_integration) purchase_integration.purchase.link.product_integrations.first.mark_deleted! expect(DiscordIntegration.discord_user_id_for(purchase_integration.purchase)).to be_nil end end describe "#disconnect!" do let(:server_id) { "0" } let(:request_header) { { "Authorization" => "Bot #{DISCORD_BOT_TOKEN}" } } let(:discord_integration) { create(:discord_integration, server_id:) } it "disconnects bot from server if server id is valid" do WebMock.stub_request(:delete, "#{Discordrb::API.api_base}/users/@me/guilds/#{server_id}"). with(headers: request_header). to_return(status: 204) expect(discord_integration.disconnect!).to eq(true) end it "fails if bot is not added to server" do WebMock.stub_request(:delete, "#{Discordrb::API.api_base}/users/@me/guilds/#{server_id}"). with(headers: request_header). to_return(status: 404, body: { code: Discordrb::Errors::UnknownMember.code }.to_json) expect(discord_integration.disconnect!).to eq(false) end it "returns true if the server has been deleted" do WebMock.stub_request(:delete, "#{Discordrb::API.api_base}/users/@me/guilds/#{server_id}"). with(headers: request_header). to_return(status: 404, body: { code: Discordrb::Errors::UnknownServer.code }.to_json) expect(discord_integration.disconnect!).to eq(true) end end describe "#same_connection?" do let(:discord_integration) { create(:discord_integration) } let(:same_connection_discord_integration) { create(:discord_integration) } let(:other_discord_integration) { create(:discord_integration, server_id: "1") } it "returns true if both integrations have the same server id" do expect(discord_integration.same_connection?(same_connection_discord_integration)).to eq(true) end it "returns false if both integrations have different server ids" do expect(discord_integration.same_connection?(other_discord_integration)).to eq(false) end it "returns false if both integrations have different types" do same_connection_discord_integration.update(type: "NotDiscordIntegration") expect(discord_integration.same_connection?(same_connection_discord_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/armenia_bank_account_spec.rb
spec/models/armenia_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe ArmeniaBankAccount do describe "#bank_account_type" do it "returns AM" do expect(create(:armenia_bank_account).bank_account_type).to eq("AM") end end describe "#country" do it "returns AM" do expect(create(:armenia_bank_account).country).to eq("AM") end end describe "#currency" do it "returns amd" do expect(create(:armenia_bank_account).currency).to eq("amd") end end describe "#routing_number" do it "returns valid for 8 to 11 characters" do ba = create(:armenia_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAAAMNNXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:armenia_bank_account, account_number_last_four: "4567").account_number_visual).to eq("******4567") end end describe "#validate_bank_code" do it "allows 8 to 11 characters only" do expect(build(:armenia_bank_account, bank_code: "AAAAAMNNXXX")).to be_valid expect(build(:armenia_bank_account, bank_code: "AAAAAMNN")).to be_valid expect(build(:armenia_bank_account, bank_code: "AAAAAMNNXXXX")).not_to be_valid expect(build(:armenia_bank_account, bank_code: "AAAAAMN")).not_to be_valid end end describe "#validate_account_number" do it "allows 11 to 16 digits only" do expect(build(:armenia_bank_account, account_number: "00001234567")).to be_valid expect(build(:armenia_bank_account, account_number: "0000123456789012")).to be_valid expect(build(:armenia_bank_account, account_number: "0000123456")).not_to be_valid expect(build(:armenia_bank_account, account_number: "00001234567890123")).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/mexico_bank_account_spec.rb
spec/models/mexico_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe MexicoBankAccount do describe "#bank_account_type" do it "returns mexico" do expect(create(:mexico_bank_account).bank_account_type).to eq("MX") end end describe "#country" do it "returns MX" do expect(create(:mexico_bank_account).country).to eq("MX") end end describe "#currency" do it "returns mxn" do expect(create(:mexico_bank_account).currency).to eq("mxn") end end describe "#routing_number" do it "returns nil" do expect(create(:mexico_bank_account).routing_number).to be nil end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:mexico_bank_account, account_number_last_four: "7897").account_number_visual).to eq("******7897") 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(:mexico_bank_account)).to be_valid expect(build(:mexico_bank_account, account_number: "000000001234567897")).to be_valid mx_bank_account = build(:mexico_bank_account, account_number: "MX12345") expect(mx_bank_account).to_not be_valid expect(mx_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") mx_bank_account = build(:mexico_bank_account, account_number: "DE61109010140000071219812874") expect(mx_bank_account).to_not be_valid expect(mx_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") mx_bank_account = build(:mexico_bank_account, account_number: "8937040044053201300000") expect(mx_bank_account).to_not be_valid expect(mx_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") mx_bank_account = build(:mexico_bank_account, account_number: "MXABCDE") expect(mx_bank_account).to_not be_valid expect(mx_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/cote_d_ivoire_bank_account_spec.rb
spec/models/cote_d_ivoire_bank_account_spec.rb
# frozen_string_literal: true describe CoteDIvoireBankAccount do describe "#bank_account_type" do it "returns CI" do expect(create(:cote_d_ivoire_bank_account).bank_account_type).to eq("CI") end end describe "#country" do it "returns CI" do expect(create(:cote_d_ivoire_bank_account).country).to eq("CI") end end describe "#currency" do it "returns xof" do expect(create(:cote_d_ivoire_bank_account).currency).to eq("xof") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:cote_d_ivoire_bank_account, account_number_last_four: "0589").account_number_visual).to eq("CI******0589") end end describe "#routing_number" do it "returns nil" do expect(create(:cote_d_ivoire_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/product_page_view_spec.rb
spec/models/product_page_view_spec.rb
# frozen_string_literal: true require "spec_helper" describe ProductPageView do it "can have documents added to its index" do document_id = SecureRandom.uuid EsClient.index( index: described_class.index_name, id: document_id, body: { "product_id" => 123, "seller_id" => 456, "timestamp" => Time.utc(2021, 10, 20, 1, 2, 3) }.to_json ) document = EsClient.get(index: described_class.index_name, id: document_id).fetch("_source") expect(document).to eq( "product_id" => 123, "seller_id" => 456, "timestamp" => "2021-10-20T01:02:03Z" ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/credit_spec.rb
spec/models/credit_spec.rb
# frozen_string_literal: true require "spec_helper" describe Credit do describe "create_for_credit!" do let(:user) { create(:user) } let(:merchant_account) { create(:merchant_account, user:) } it "assigns to the Gumroad Stripe merchant account" do credit = Credit.create_for_credit!(user:, amount_cents: 1000, crediting_user: User.first) expect(credit.merchant_account).to eq(MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id)) end it "updates the unpaid_balance_cents for users after creation" do balance_before_credit = user.unpaid_balance_cents credit = Credit.create_for_credit!(user:, amount_cents: 1000, crediting_user: User.first) balance_after_credit = user.reload.unpaid_balance_cents expect(balance_after_credit).to eq(balance_before_credit + credit.amount_cents) end it "creates a balance record after credit" do credit = Credit.create_for_credit!(user:, amount_cents: 1000, crediting_user: User.first) expect(credit.balance).to eq(Balance.last) end it "creates a comment after credit" do comment_count_before_credit = user.comments.count Credit.create_for_credit!(user:, amount_cents: 1000, crediting_user: User.first) expect(user.reload.comments.count).to eq(comment_count_before_credit + 1) expect(user.reload.comments.last.content).to include("issued $10 credit") end it "applies the credit to the oldest unpaid balance" do old_balance = create(:balance, user:, date: 10.days.ago) balance_before_credit = user.unpaid_balance_cents credit = Credit.create_for_credit!(user:, amount_cents: 1000, crediting_user: User.first) balance_after_credit = user.reload.unpaid_balance_cents expect(balance_after_credit).to eq(balance_before_credit + credit.amount_cents) expect(credit.balance).to eq(old_balance) end it "applies the credit to an unpaid balance for the Gumroad Stripe merchant account" do credit = Credit.create_for_credit!(user:, amount_cents: 1000, crediting_user: User.first) expect(credit.balance.merchant_account).to eq(MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id)) end end describe "create_for_dispute_won!" do let(:user) { create(:user) } let(:merchant_account) { create(:merchant_account, user:) } let(:purchase) { create(:purchase) } let(:dispute) { create(:dispute, purchase:) } let(:balance_transaction_issued_amount) do BalanceTransaction::Amount.new( currency: Currency::USD, gross_cents: 100_00, net_cents: 88_90 ) end let(:balance_transaction_holding_amount) do BalanceTransaction::Amount.new( currency: Currency::USD, gross_cents: 200_00, net_cents: 177_80 ) end it "assigns the purchase of the dispute as the chargebacked purchase" do credit = Credit.create_for_dispute_won!(user:, merchant_account:, dispute:, chargedback_purchase: purchase, balance_transaction_issued_amount:, balance_transaction_holding_amount:) expect(credit.chargebacked_purchase).to eq(purchase) end it "updates the unpaid_balance_cents for users after creation" do balance_before_credit = user.unpaid_balance_cents credit = Credit.create_for_dispute_won!(user:, merchant_account:, dispute:, chargedback_purchase: purchase, balance_transaction_issued_amount:, balance_transaction_holding_amount:) balance_after_credit = user.reload.unpaid_balance_cents expect(balance_after_credit).to eq(balance_before_credit + credit.amount_cents) end it "creates a balance record after credit" do credit = Credit.create_for_dispute_won!(user:, merchant_account:, dispute:, chargedback_purchase: purchase, balance_transaction_issued_amount:, balance_transaction_holding_amount:) expect(credit.balance).to eq(Balance.last) end it "creates a comment after credit" do comment_count_before_credit = user.comments.count Credit.create_for_dispute_won!(user:, merchant_account:, dispute:, chargedback_purchase: purchase, balance_transaction_issued_amount:, balance_transaction_holding_amount:) expect(user.reload.comments.count).to eq(comment_count_before_credit + 1) expect(user.reload.comments.last.content).to include("issued $88.90 credit") end it "applies the credit to the oldest unpaid balance" do old_balance = create(:balance, user:, merchant_account:, date: 10.days.ago) balance_before_credit = user.unpaid_balance_cents credit = Credit.create_for_dispute_won!(user:, merchant_account:, dispute:, chargedback_purchase: purchase, balance_transaction_issued_amount:, balance_transaction_holding_amount:) balance_after_credit = user.reload.unpaid_balance_cents expect(balance_after_credit).to eq(balance_before_credit + credit.amount_cents) expect(credit.balance).to eq(old_balance) end it "applies the credit to an unpaid balance for the creator's merchant account" do credit = Credit.create_for_dispute_won!(user:, merchant_account:, dispute:, chargedback_purchase: purchase, balance_transaction_issued_amount:, balance_transaction_holding_amount:) expect(credit.balance.merchant_account).to eq(merchant_account) end end describe "create_for_returned_payment_difference!" do let(:user) { create(:user) } let(:merchant_account) { create(:merchant_account, user:) } let(:returned_payment) { create(:payment_returned) } let(:difference_amount_cents) { raise NotImplementedError } let(:credit) do Credit.create_for_returned_payment_difference!( user:, merchant_account:, returned_payment:, difference_amount_cents: ) end describe "when the difference is positive" do let(:difference_amount_cents) { 1_00 } it "is for a zero amount" do expect(credit.amount_cents).to eq(0) end it "assigns the returned payment" do expect(credit.returned_payment).to eq(returned_payment) end it "creates a balance transaction with a zero issued amount" do expect(credit.balance_transaction.issued_amount_gross_cents).to eq(0) expect(credit.balance_transaction.issued_amount_net_cents).to eq(0) end it "creates a balance transaction with the difference as the holding amount" do expect(credit.balance_transaction.holding_amount_gross_cents).to eq(difference_amount_cents) expect(credit.balance_transaction.holding_amount_net_cents).to eq(difference_amount_cents) end it "does not update the balances amount_cents" do balance = create(:balance, user:, merchant_account:, date: 10.days.ago) expect { credit }.not_to change { balance.reload.amount_cents } expect(credit.balance).to eq(balance) end it "updates the balances holding_amount_cents" do balance = create(:balance, user:, merchant_account:, date: 10.days.ago) expect { credit }.to change { balance.reload.holding_amount_cents } expect(credit.balance).to eq(balance) end it "does not update the unpaid_balance_cents for users after creation" do expect { credit }.not_to change { user.reload.unpaid_balance_cents } end it "creates a comment after credit" do expect { credit }.to change { user.reload.comments.count }.by(1) end it "creates a command after credit with the returned payment id" do credit user.reload expect(user.comments.last.content).to include("issued adjustment due to currency conversion differences when payment #{returned_payment.id} returned") expect(user.comments.last.author_name).to eq("AutoCredit Returned Payment (#{returned_payment.id})") end it "applies the credit to the oldest unpaid balance" do old_balance_1 = create(:balance, user:, merchant_account:, date: 20.days.ago) old_balance_2 = create(:balance, user:, merchant_account:, date: 10.days.ago) expect(credit.balance).to eq(old_balance_1) expect(credit.balance).not_to eq(old_balance_2) end it "applies the credit to the unpaid balance for the creator's merchant account" do old_balance_1 = create(:balance, user:, merchant_account: create(:merchant_account), date: 20.days.ago) old_balance_2 = create(:balance, user:, merchant_account:, date: 10.days.ago) expect(credit.balance).to eq(old_balance_2) expect(credit.balance).not_to eq(old_balance_1) end end describe "when the difference is negative" do let(:difference_amount_cents) { -1_00 } it "is for a zero amount" do expect(credit.amount_cents).to eq(0) end it "assigns the returned payment" do expect(credit.returned_payment).to eq(returned_payment) end it "creates a balance transaction with a zero issued amount" do expect(credit.balance_transaction.issued_amount_gross_cents).to eq(0) expect(credit.balance_transaction.issued_amount_net_cents).to eq(0) end it "creates a balance transaction with the difference as the holding amount" do expect(credit.balance_transaction.holding_amount_gross_cents).to eq(difference_amount_cents) expect(credit.balance_transaction.holding_amount_net_cents).to eq(difference_amount_cents) end it "does not update the balances amount_cents" do balance = create(:balance, user:, merchant_account:, date: 10.days.ago) expect { credit }.not_to change { balance.reload.amount_cents } expect(credit.balance).to eq(balance) end it "updates the balances holding_amount_cents" do balance = create(:balance, user:, merchant_account:, date: 10.days.ago) expect { credit }.to change { balance.reload.holding_amount_cents } expect(credit.balance).to eq(balance) end it "does not update the unpaid_balance_cents for users after creation" do expect { credit }.not_to change { user.reload.unpaid_balance_cents } end it "creates a comment after credit" do expect { credit }.to change { user.reload.comments.count }.by(1) end it "creates a command after credit with the returned payment id" do credit user.reload expect(user.comments.last.content).to include("issued adjustment due to currency conversion differences when payment #{returned_payment.id} returned") expect(user.comments.last.author_name).to eq("AutoCredit Returned Payment (#{returned_payment.id})") end it "applies the credit to the oldest unpaid balance" do old_balance_1 = create(:balance, user:, merchant_account:, date: 20.days.ago) old_balance_2 = create(:balance, user:, merchant_account:, date: 10.days.ago) expect(credit.balance).to eq(old_balance_1) expect(credit.balance).not_to eq(old_balance_2) end it "applies the credit to the unpaid balance for the creator's merchant account" do old_balance_1 = create(:balance, user:, merchant_account: create(:merchant_account), date: 20.days.ago) old_balance_2 = create(:balance, user:, merchant_account:, date: 10.days.ago) expect(credit.balance).to eq(old_balance_2) expect(credit.balance).not_to eq(old_balance_1) end end end describe "create_for_refund_fee_retention!", :vcr do let!(:creator) { create(:user) } let!(:merchant_account) { create(:merchant_account_stripe, user: creator) } let!(:purchase) { create(:purchase, succeeded_at: 3.days.ago, link: create(:product, user: creator), merchant_account:) } let!(:refund) { create(:refund, purchase:, fee_cents: 100) } it "assigns the refund as fee_retention_refund" do expect(Stripe::Transfer).to receive(:create).and_call_original credit = Credit.create_for_refund_fee_retention!(refund:) expect(credit.fee_retention_refund).to eq(refund) end it "updates the unpaid_balance_cents for the seller" do expect(Stripe::Transfer).to receive(:create).and_call_original expect(creator.unpaid_balance_cents).to eq(0) credit = Credit.create_for_refund_fee_retention!(refund:) expect(credit.amount_cents).to eq(-33) expect(creator.reload.unpaid_balance_cents).to eq(-33) end it "creates a balance record after credit" do expect(Stripe::Transfer).to receive(:create).and_call_original credit = Credit.create_for_refund_fee_retention!(refund:) expect(credit.balance).to eq(Balance.last) end it "applies the credit to the oldest unpaid balance and not the unpaid balance from purchase date" do oldest_balance = create(:balance, user: creator, amount_cents: 1000, merchant_account:, date: purchase.succeeded_at.to_date - 2.days) create(:balance, user: creator, amount_cents: 2000, merchant_account:, date: purchase.succeeded_at.to_date) expect(Stripe::Transfer).to receive(:create).and_call_original expect(creator.unpaid_balance_cents).to eq(3000) credit = Credit.create_for_refund_fee_retention!(refund:) expect(credit.amount_cents).to eq(-33) expect(credit.balance).to eq(oldest_balance) expect(credit.balance.merchant_account).to eq(merchant_account) expect(credit.balance_transaction.issued_amount_net_cents).to eq(-33) expect(credit.balance_transaction.holding_amount_net_cents).to eq(-33) expect(creator.reload.unpaid_balance_cents).to eq(2967) # 3000 - 33 end describe "Gumroad-controlled non-US Stripe account sales" do it "applies the credit to the oldest unpaid balance and not the unpaid balance from purchase date" do travel_to(Time.at(1681734634).utc) do non_us_stripe_account = create(:merchant_account, charge_processor_merchant_id: "acct_1LrgA6S47qdHFIIY", country: "AU", currency: "aud", user: creator) purchase = create(:purchase, succeeded_at: 3.days.ago, link: create(:product, user: creator), merchant_account: non_us_stripe_account) refund = create(:refund, purchase:, fee_cents: 100) oldest_balance = create(:balance, user: creator, merchant_account: non_us_stripe_account, amount_cents: 1000, holding_currency: "aud", date: purchase.succeeded_at.to_date - 2.days) create(:balance, user: creator, merchant_account: non_us_stripe_account, amount_cents: 2000, holding_currency: "aud", date: purchase.succeeded_at.to_date) expect(Stripe::Transfer).to receive(:create_reversal).and_call_original expect(creator.unpaid_balance_cents).to eq(3000) credit = Credit.create_for_refund_fee_retention!(refund:) expect(credit.amount_cents).to eq(-33) expect(credit.balance).to eq(oldest_balance) expect(credit.balance.merchant_account).to eq(non_us_stripe_account) expect(credit.balance_transaction.issued_amount_net_cents).to eq(-33) expect(credit.balance_transaction.holding_amount_net_cents).to eq(-52) expect(creator.reload.unpaid_balance_cents).to eq(2967) # 3000 - 33 end end end describe "PayPal Connect sales" do let(:purchase) do create(:purchase, succeeded_at: 3.days.ago, link: create(:product, user: creator), charge_processor_id: "paypal", merchant_account: create(:merchant_account_paypal, user: creator)) end let(:refund) { create(:refund, purchase:, fee_cents: 100) } context "when the Gumroad tax and affiliate credit are present" do it "returns a positive credit for the affiliate commission and taxes" do purchase.update!(gumroad_tax_cents: 10, affiliate_credit_cents: 15) credit = Credit.create_for_refund_fee_retention!(refund:) expect(credit.amount_cents).to eq(25) expect(credit.fee_retention_refund).to eq(refund) expect(credit.balance.merchant_account).to eq(MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id)) expect(credit.balance_transaction.issued_amount_net_cents).to eq(25) expect(credit.balance_transaction.holding_amount_net_cents).to eq(25) expect(creator.reload.unpaid_balance_cents).to eq(25) end end context "when the Gumroad tax and affiliate credit are not present" do it "does nothing and returns" do expect(Credit).not_to receive(:new) expect(Credit.create_for_refund_fee_retention!(refund:)).to be nil end end end describe "Stripe Connect sales" do let(:purchase) do create(:purchase, succeeded_at: 3.days.ago, link: create(:product, user: creator), charge_processor_id: "stripe", merchant_account: create(:merchant_account_stripe_connect)) end let(:refund) { create(:refund, purchase:, fee_cents: 100) } context "when the Gumroad tax and affiliate credit are present" do it "returns a positive credit for the affiliate commission and taxes" do purchase.update!(gumroad_tax_cents: 10, affiliate_credit_cents: 15) credit = Credit.create_for_refund_fee_retention!(refund:) expect(credit.amount_cents).to eq(25) expect(credit.fee_retention_refund).to eq(refund) expect(credit.balance.merchant_account).to eq(MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id)) expect(credit.balance_transaction.issued_amount_net_cents).to eq(25) expect(credit.balance_transaction.holding_amount_net_cents).to eq(25) expect(creator.reload.unpaid_balance_cents).to eq(25) end end context "when the Gumroad tax and affiliate credit are not present" do it "does nothing and returns" do expect(Credit).not_to receive(:new) expect(Credit.create_for_refund_fee_retention!(refund:)).to be nil end end end it "does not create a comment after credit" do expect do Credit.create_for_refund_fee_retention!(refund:) end.not_to change { refund.purchase.seller.comments.count } end end describe "create_for_balance_change_on_stripe_account!" do let!(:creator) { create(:user) } let!(:merchant_account) { create(:merchant_account, user: creator) } before do stub_const("GUMROAD_ADMIN_ID", create(:admin_user).id) end it "updates the unpaid_balance_cents for the seller" do balance_before_credit = creator.unpaid_balance_cents expect do Credit.create_for_balance_change_on_stripe_account!(amount_cents_holding_currency: -1000, merchant_account:) end.to change { creator.credits.count }.by(1) balance_after_credit = creator.reload.unpaid_balance_cents credit = Credit.last expect(credit.amount_cents).to eq(-1000) expect(credit.merchant_account_id).to eq(merchant_account.id) expect(balance_after_credit).to eq(balance_before_credit + credit.amount_cents) end it "creates a balance record after credit" do credit = Credit.create_for_balance_change_on_stripe_account!(amount_cents_holding_currency: -1000, merchant_account: create(:merchant_account), amount_cents_usd: -900) expect(credit.balance).to eq(Balance.last) expect(credit.balance.holding_amount_cents).to eq(-1000) expect(credit.balance.amount_cents).to eq(-900) expect(credit.balance.holding_currency).to eq(credit.merchant_account.currency) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/new_zealand_bank_account_spec.rb
spec/models/new_zealand_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe NewZealandBankAccount do describe "#bank_account_type" do it "returns new zealand" do expect(create(:new_zealand_bank_account).bank_account_type).to eq("NZ") end end describe "#country" do it "returns NZ" do expect(create(:new_zealand_bank_account).country).to eq("NZ") end end describe "#currency" do it "returns nzd" do expect(create(:new_zealand_bank_account).currency).to eq("nzd") end end describe "#routing_number" do it "returns nil" do expect(create(:new_zealand_bank_account).routing_number).to be nil end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:new_zealand_bank_account, account_number_last_four: "0010").account_number_visual).to eq("******0010") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do expect(build(:new_zealand_bank_account, account_number: "1100000000000010")).to be_valid expect(build(:new_zealand_bank_account, account_number: "1123456789012345")).to be_valid expect(build(:new_zealand_bank_account, account_number: "112345678901234")).to be_valid ch_bank_account = build(:new_zealand_bank_account, account_number: "NZ12345") 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(:new_zealand_bank_account, account_number: "11000000000000") 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(:new_zealand_bank_account, account_number: "CHABCDEFGHIJKLMNZ") 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/product_file_spec.rb
spec/models/product_file_spec.rb
# frozen_string_literal: true require "spec_helper" describe ProductFile do describe ".archivable" do it "only includes archivable files" do create(:streamable_video) create(:readable_document) create(:listenable_audio) create(:non_readable_document) create(:external_link) create(:streamable_video, stream_only: true) create(:product_file, filetype: "link", url: "https://www.gumroad.com") create(:product_file, filetype: "link", url: "https://www.twitter.com") expect(ProductFile.archivable.count).to eq(4) end end describe "#has_alive_duplicate_files?" do let!(:file_1) { create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/some-file.pdf") } let!(:file_2) { create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/some-file.pdf") } it "returns true if there's an alive record with the same url" do file_1.mark_deleted expect(file_1.has_alive_duplicate_files?).to eq(true) expect(file_2.has_alive_duplicate_files?).to eq(true) end it "returns false if there's no other alive record with the same url" do file_1.mark_deleted file_2.mark_deleted expect(file_1.has_alive_duplicate_files?).to eq(false) expect(file_2.has_alive_duplicate_files?).to eq(false) end end describe "#can_send_to_kindle?" do context "when file size is above the limit" do it "returns false" do product_file = create(:readable_document, size: 20_480_001) expect(product_file.can_send_to_kindle?).to eq false end end context "when the file size is nil" do it "returns false" do product_file = create(:readable_document, size: nil) expect(product_file.can_send_to_kindle?).to eq false end end context "when the file format is not supported by kindle" do it "returns false" do product_file = create(:streamable_video, size: 10_000) expect(product_file.can_send_to_kindle?).to eq false end end context "when the file format is supported by kindle" do it "returns true for pdf files" do product_file = create(:pdf_product_file, size: 10_000) expect(product_file.can_send_to_kindle?).to eq true end it "returns true for epub files" do product_file = create(:epub_product_file, size: 10_000) expect(product_file.can_send_to_kindle?).to eq true end end end describe "#must_be_pdf_stamped?" do it "returns false for a non-pdf file" do product_file = create(:non_readable_document) expect(product_file.must_be_pdf_stamped?).to eq(false) end it "returns false for a pdf file with pdf stamping disabled" do product_file = create(:readable_document, pdf_stamp_enabled: false) expect(product_file.must_be_pdf_stamped?).to eq(false) end it "returns false for a pdf file with pdf stamping enabled" do product_file = create(:readable_document, pdf_stamp_enabled: true) expect(product_file.must_be_pdf_stamped?).to eq(true) end end describe "#archivable?" do it "returns true only for archivable files" do archivable = [ create(:readable_document), create(:non_streamable_video), create(:streamable_video), create(:readable_document, stream_only: true), create(:non_readable_document), create(:listenable_audio) ] non_archivable = [ create(:streamable_video, stream_only: true), create(:product_file, filetype: "link", url: "http://gumroad.com") ] expect(archivable.all?(&:archivable?)).to eq(true) expect(non_archivable.any?(&:archivable?)).to eq(false) end end describe "#stream_only?" do it "returns false for non-video file" do product_file = create(:readable_document) expect(product_file.stream_only?).to eq(false) end it "returns false for non-streamable video file" do product_file = create(:non_streamable_video) expect(product_file.stream_only?).to eq(false) end it "returns false for streamable video file not marked as stream_only" do product_file = create(:streamable_video) expect(product_file.stream_only?).to eq(false) end it "returns false for non-video file marked as stream_only" do product_file = create(:readable_document, stream_only: true) expect(product_file.stream_only?).to eq(false) end it "returns true for streamable video file marked as stream_only" do product_file = create(:streamable_video, stream_only: true) expect(product_file.stream_only?).to eq(true) end end describe "file group and analyze" do it "enqueues analyze after file creation" do product_file = create(:readable_document) expect(AnalyzeFileWorker).to have_enqueued_sidekiq_job(product_file.id, ProductFile.name) expect(product_file.reload.pdf?).to be(true) end it "allows file size larger than max int" do product_file = create(:readable_document, size: 10_000_000_000) expect(product_file.reload.size).to eq 10_000_000_000 end context "external link as a file" do it "skips analyze" do create(:product_file, filetype: "link", url: "https://www.gumroad.com") expect(AnalyzeFileWorker.jobs.size).to eq(0) end it "detects correct file group" do product_file = create(:product_file, filetype: "link", url: "https://www.gumroad.com") expect(product_file.filegroup).to eq("link") end it "returns the URL as the name of the file if it is blank" do product_file = create(:product_file, filetype: "link", url: "https://www.gumroad.com") expect(product_file.display_name).to be_nil expect(product_file.name_displayable).to eq(product_file.url) end end it "preserves s3 key for files containing percent and ampersand in filename" do product_file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test file %26 & ) %29.txt") expect(product_file.s3_key).to eq "specs/test file %26 & ) %29.txt" end it "saves subtitle files correctly" do product_file = create(:product_file) subtitle_data = [ { "language" => "English", "url" => "english.vtt" }, { "language" => "Français", "url" => "french.vtt" }, { "language" => "Español", "url" => "spanish.vtt" } ] product_file.save_subtitle_files!(subtitle_data) product_file.subtitle_files.each do |file| expect(file.language).to eq subtitle_data.find { _1["url"] == file.url }["language"] end end it "deletes all subtitle files correctly" do product_file = create(:product_file) subtitle_file = create(:subtitle_file, product_file:) product_file.subtitle_files.append(subtitle_file) product_file.delete_all_subtitle_files! expect(product_file.subtitle_files.alive.length).to eq 0 end it "handles edits to subtitle files correctly" do product_file = create(:product_file) subtitle_file = create(:subtitle_file, product_file:) product_file.subtitle_files.append(subtitle_file) subtitle_file = create(:subtitle_file, url: "french.vtt", product_file:) product_file.subtitle_files.append(subtitle_file) subtitle_data = [ { "language" => "Français", "url" => "french.vtt" }, { "language" => "Español", "url" => "spanish.vtt" } ] product_file.save_subtitle_files!(subtitle_data) product_file.subtitle_files.alive.each do |file| expect(file.language).to eq subtitle_data.find { _1["url"] == file.url }["language"] end expect(product_file.subtitle_files.alive.length).to eq 2 end describe "invalid file urls" do it "does not create files with invalid urls" do invalid_product_file = build(:product_file, url: "undefined") expect(invalid_product_file).to_not be_valid invalid_product_file.save expect(invalid_product_file.errors.full_messages.first).to eq "Please provide a valid file URL." end it "does not create files with invalid external links" do invalid_product_file = build(:product_file, url: "gum.road", filetype: "link") expect(invalid_product_file.valid?).to eq(false) expect(invalid_product_file.errors.full_messages).to include("gum.road is not a valid URL.") end end describe "renaming" do before do @product_file = create(:readable_document) end it "schedules renaming of S3 file if display_name updated" do @product_file.update!(description: "chapter one of the book") expect(RenameProductFileWorker).to_not have_enqueued_sidekiq_job(@product_file.id) @product_file.update!(display_name: "trillion-dollar-company") expect(RenameProductFileWorker).to have_enqueued_sidekiq_job(@product_file.id) end it "does not schedule rename in S3 if display_name updated for an external link file" do product_file = create(:product_file, filetype: "link", url: "https://gumroad.com") product_file.update!(display_name: "trillion-dollar-company") expect(RenameProductFileWorker).to_not have_enqueued_sidekiq_job(product_file.id) end it "renames files and preserves the Content-Type", :sidekiq_inline do expect(MultipartTransfer).to receive(:transfer_to_s3).with(/billion-dollar-company-chapter-0.pdf/, destination_filename: "dog.pdf", existing_s3_object: instance_of(@product_file.s3_object.class)).and_call_original @product_file.update!(display_name: "dog") @product_file.reload expect(@product_file.url).to match %r(attachments/[a-f\d]{32}/original/dog.pdf) expect(@product_file.name_displayable).to eq("dog") expect(@product_file.s3_object.content_type).to eq("application/pdf") # Assert content type of the old S3 object Rails.cache.delete("s3_key_ProductFile_#{@product_file.id}") # Clear the old cached s3_key expect(@product_file.s3_object.content_type).to eq("application/pdf") # Assert content type of the new S3 object end it "renames a file to a long name", :sidekiq_inline do new_name = "A" * 250 expect(MultipartTransfer).to receive(:transfer_to_s3).with(/billion-dollar-company-chapter-0.pd/, destination_filename: "#{new_name}.pdf", existing_s3_object: instance_of(@product_file.s3_object.class)).and_call_original @product_file.update!(display_name: new_name) @product_file.reload expect(@product_file.url).to match %r(attachments/[a-f\d]{32}/original/#{new_name}.pdf) expect(@product_file.name_displayable).to eq(new_name) end end it "creates the product file with filetype set to lowercase" do product_file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/fc34ee33bae54181badd048c71209d24/original/sample.PDF") expect(product_file.filetype).to eq("pdf") end end describe "product file for installments" do it "schedules analyze and not schedule PdfUnstampableNotifierJob if the file belongs to an installment" do product_file = create(:readable_document, link: nil, installment: create(:installment)) expect(AnalyzeFileWorker).to have_enqueued_sidekiq_job(product_file.id, ProductFile.name) expect(PdfUnstampableNotifierJob.jobs.size).to eq(0) end end describe "#transcodable?" do let(:product_file) do create(:streamable_video, width: 2550, height: 1750, bitrate: 869_480) end it "returns `false` if the width is not set" do product_file.update!(width: nil) expect(product_file.transcodable?).to be(false) end it "returns `false` if the height is not set" do product_file.update!(height: nil) expect(product_file.transcodable?).to be(false) end it "returns `false` if the file is not a video file" do expect(product_file).to receive(:streamable?).and_return(false) expect(product_file.transcodable?).to be(false) end it "returns `true` if the dimensions are set for a video file" do expect(product_file.transcodable?).to be(true) end end describe "#transcoding_in_progress?" do it "returns true if there's a transcoded video in progress" do product = create(:product_with_video_file) video_file = product.product_files.first expect(video_file.transcoding_in_progress?).to eq(false) create(:transcoded_video, streamable: video_file, original_video_key: video_file.s3_key, state: "processing") expect(video_file.reload.transcoding_in_progress?).to eq(true) end end describe "#transcoding_failed" do it "sends an email to the creator" do product_file = create(:product_file) expect { product_file.transcoding_failed } .to have_enqueued_mail(ContactingCreatorMailer, :video_transcode_failed).with(product_file.id) end end describe "#attempt_to_transcode?" do let(:product_file) do create(:streamable_video, width: 2550, height: 1750, bitrate: 869_480) end it "returns `false` if there are transcoding jobs in the 'processing' state" do create(:transcoded_video, streamable: product_file, original_video_key: product_file.s3_key, state: "processing") expect(product_file.attempt_to_transcode?).to be(false) end it "with allowed_when_processing=true returns `true` if there are transcoding jobs in the 'processing' state" do create(:transcoded_video, streamable: product_file, original_video_key: product_file.s3_key, state: "processing") expect(product_file.attempt_to_transcode?(allowed_when_processing: true)).to be(true) end it "returns `false` if there are transcoding jobs in the 'completed' state" do create(:transcoded_video, streamable: product_file, original_video_key: product_file.s3_key, state: "completed") expect(product_file.attempt_to_transcode?).to be(false) end it "returns `true` if the there are no 'processing' or 'completed' transcoding jobs" do expect(product_file.attempt_to_transcode?).to be(true) end end describe "s3 properties" do before do @product_file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/files/43a5363194e74e9ee75b6203eaea6705/original/black/white.mp4") end it "handles / in the filename properly" do expect(@product_file.s3_key).to eq("files/43a5363194e74e9ee75b6203eaea6705/original/black/white.mp4") expect(@product_file.s3_filename).to eq("black/white.mp4") expect(@product_file.s3_display_name).to eq("black/white") expect(@product_file.s3_extension).to eq(".mp4") expect(@product_file.s3_display_extension).to eq("MP4") end it "works as expected for files without an extension" do @product_file.update!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/files/43a5363194e74e9ee75b6203eaea6705/original/black/white") expect(@product_file.s3_key).to eq("files/43a5363194e74e9ee75b6203eaea6705/original/black/white") expect(@product_file.s3_filename).to eq("black/white") expect(@product_file.s3_display_name).to eq("black/white") expect(@product_file.s3_extension).to eq("") expect(@product_file.s3_display_extension).to eq("") end end describe "#delete!" do it "deletes all associated subtitle files for an mp4 file" do mp4_file = create(:product_file) subtitle_file = create(:subtitle_file, product_file: mp4_file) mp4_file.subtitle_files.append(subtitle_file) subtitle_file = create(:subtitle_file, url: "french.vtt", product_file: mp4_file) mp4_file.subtitle_files.append(subtitle_file) expect(mp4_file.subtitle_files.alive.size).to eq(2) mp4_file.delete! expect(mp4_file.reload.deleted_at).not_to be(nil) expect(mp4_file.subtitle_files.alive.size).to eq(0) mp4_file.subtitle_files.each do |file| expect(file.deleted_at).not_to be(nil) end end end describe "#hls_playlist" do before do @multifile_product = create(:product) @file_1 = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter 2.mp4", is_transcoded_for_hls: true) @multifile_product.product_files << @file_1 @transcoded_video = create(:transcoded_video, link: @multifile_product, streamable: @file_1, original_video_key: @file_1.s3_key, transcoded_video_key: "attachments/2_1/original/chapter 2/hls/index.m3u8", is_hls: true, state: "completed") s3_new = double("s3_new") s3_bucket = double("s3_bucket") s3_object = double("s3_object") hls = "#EXTM3U\n#EXT-X-STREAM-INF:PROGRAM-ID=1,RESOLUTION=854x480,CODECS=\"avc1.4d001f,mp4a.40.2\",BANDWIDTH=1191000\nhls_480p_.m3u8\n" hls += "#EXT-X-STREAM-INF:PROGRAM-ID=1,RESOLUTION=1280x720,CODECS=\"avc1.4d001f,mp4a.40.2\",BANDWIDTH=2805000\nhls_720p_.m3u8\n" allow(Aws::S3::Resource).to receive(:new).and_return(s3_new) allow(s3_new).to receive(:bucket).and_return(s3_bucket) allow(s3_bucket).to receive(:object).and_return(s3_object) allow(s3_object).to receive(:get).and_return(double(body: double(read: hls))) end it "replaces the links to the playlists with signed urls" do travel_to(Date.parse("2015-03-13")) do hls_playlist = @file_1.hls_playlist url = "#EXTM3U\n#EXT-X-STREAM-INF:PROGRAM-ID=1,RESOLUTION=854x480,CODECS=\"avc1.4d001f,mp4a.40.2\",BANDWIDTH=1191000\n" url += "https://d1jmbc8d0c0hid.cloudfront.net/attachments/2_1/original/chapter+2/hls/hls_480p_.m3u8?Expires=1426248000&" url += "Signature=lqqrPpAOP6KeFxLiOt/ynEpMvkAgIzwuQM9LZSA6cB143fSP0WVkGuq10VJzsICzQ/3wdSWhRYTgJsNQMATDtg==&" url += "Key-Pair-Id=APKAISH5PKOS7WQUJ6SA\n" url += "#EXT-X-STREAM-INF:PROGRAM-ID=1,RESOLUTION=1280x720,CODECS=\"avc1.4d001f,mp4a.40.2\",BANDWIDTH=2805000\n" url += "https://d1jmbc8d0c0hid.cloudfront.net/attachments/2_1/original/chapter+2/hls/hls_720p_.m3u8?Expires=1426248000&" url += "Signature=P3ocRbRxhWiP1pSWehzxz7PMx+GUlhoZGL5u+KMIj4+hrbcoT3Gm9rNiZL1PDUzBHP6DJ8Cgw3TNPYb2xcoNsQ==&" url += "Key-Pair-Id=APKAISH5PKOS7WQUJ6SA\n" expect(hls_playlist).to eq url end end it "escapes the user-provided filename even if the user has changed the filename since the video was transcoded" do @file_1.update!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter_2_no_spaces.mp4") travel_to(Date.parse("2015-03-13")) do hls_playlist = @file_1.hls_playlist url = "#EXTM3U\n#EXT-X-STREAM-INF:PROGRAM-ID=1,RESOLUTION=854x480,CODECS=\"avc1.4d001f,mp4a.40.2\",BANDWIDTH=1191000\n" url += "https://d1jmbc8d0c0hid.cloudfront.net/attachments/2_1/original/chapter+2/hls/hls_480p_.m3u8?Expires=1426248000&" # Notice the + in chapter+2 url += "Signature=lqqrPpAOP6KeFxLiOt/ynEpMvkAgIzwuQM9LZSA6cB143fSP0WVkGuq10VJzsICzQ/3wdSWhRYTgJsNQMATDtg==&" url += "Key-Pair-Id=APKAISH5PKOS7WQUJ6SA\n" url += "#EXT-X-STREAM-INF:PROGRAM-ID=1,RESOLUTION=1280x720,CODECS=\"avc1.4d001f,mp4a.40.2\",BANDWIDTH=2805000\n" url += "https://d1jmbc8d0c0hid.cloudfront.net/attachments/2_1/original/chapter+2/hls/hls_720p_.m3u8?Expires=1426248000&" # Notice the + in chapter+2 url += "Signature=P3ocRbRxhWiP1pSWehzxz7PMx+GUlhoZGL5u+KMIj4+hrbcoT3Gm9rNiZL1PDUzBHP6DJ8Cgw3TNPYb2xcoNsQ==&" url += "Key-Pair-Id=APKAISH5PKOS7WQUJ6SA\n" expect(hls_playlist).to eq url end end it "escapes the filename in legacy S3 attachments" do file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/0000134abcdefghhijkl354sfdg/chapter 2.mp4", is_transcoded_for_hls: true) @multifile_product.product_files << file @transcoded_video = create(:transcoded_video, link: @multifile_product, streamable: file, original_video_key: file.s3_key, transcoded_video_key: "attachments/0000134abcdefghhijkl354sfdg/chapter 2/hls/index.m3u8", is_hls: true, state: "completed") expect(file.hls_playlist).to include("attachments/0000134abcdefghhijkl354sfdg/chapter+2/hls/hls_480p_.m3u8") end it "escapes the newlines in the filename" do file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/12345/abcd12345/original/YouTube + Marketing Is Powerful\n.mp4", is_transcoded_for_hls: true) @multifile_product.product_files << file @transcoded_video = create(:transcoded_video, link: @multifile_product, streamable: file, original_video_key: file.s3_key, transcoded_video_key: "attachments/12345/abcd12345/original/YouTube + Marketing Is Powerful\n/hls/index.m3u8", is_hls: true, state: "completed") expect(file.hls_playlist).to include("attachments/12345/abcd12345/original/YouTube+%2B+Marketing+Is+Powerful%0A/hls/hls_720p_.m3u8") end end describe "#subtitle_files_for_mobile" do let(:product_file) { create(:product_file) } context "when there are no alive subtitle files associated" do it "returns an empty array" do expect(product_file.subtitle_files_for_mobile).to eq([]) end end context "when associated alive subtitle files exist" do let(:english_srt_url) { "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/english.srt" } let(:french_srt_url) { "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/french.srt" } let(:subtitle_file_en) do create(:subtitle_file, language: "English", url: english_srt_url, product_file:) end let(:subtitle_file_fr) do create(:subtitle_file, language: "Français", url: french_srt_url, product_file:) end let(:subtitle_file_de) do create(:subtitle_file, language: "Deutsch", product_file:, deleted_at: Time.current) end before do # Stub URLs to be returned as the process to do the actual computation makes S3 calls and such allow_any_instance_of(SignedUrlHelper).to( receive(:signed_download_url_for_s3_key_and_filename) .with(subtitle_file_en.s3_key, subtitle_file_en.s3_filename, is_video: true).and_return(english_srt_url)) allow_any_instance_of(SignedUrlHelper).to( receive(:signed_download_url_for_s3_key_and_filename) .with(subtitle_file_fr.s3_key, subtitle_file_fr.s3_filename, is_video: true).and_return(french_srt_url)) end it "returns url and language for all the files" do expected_result = [ { url: english_srt_url, language: "English" }, { url: french_srt_url, language: "Français" } ] expect(product_file.subtitle_files_for_mobile).to match_array(expected_result) end end end describe "mobile" do before do @file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter 2.mp4", is_transcoded_for_hls: true) end it "returns name values that contain extensions" do expect(@file.mobile_json_data[:name]).to eq "chapter 2.mp4" end it "returns name_displayable" do display_name = @file.mobile_json_data[:name_displayable] expect(display_name).to eq @file.name_displayable end end describe "#external_folder_id" do before do @folder = create(:product_folder) @file = create(:product_file, link: @folder.link, folder: @folder) end it "returns external id if folder exists" do expect(@file.external_folder_id).to eq(@folder.external_id) end it "returns nil if folder does not exist" do file = create(:product_file) expect(file.external_folder_id).to eq(nil) end it "returns nil if folder is hard deleted" do expect do @folder.delete end.to change { @file.reload.external_folder_id }.from(@folder.external_id).to(nil) end it "returns nil if folder is soft deleted" do expect do @folder.mark_deleted! end.to change { @file.reload.external_folder_id }.from(@folder.external_id).to(nil) end end describe "#has_cdn_url?" do it "returns a truthy value when the CDN URL is in a specific format" do product_file = create(:product_file) expect(product_file.has_cdn_url?).to be_truthy end it "returns a falsey value when the CDN URL is not in the regular Gumroad format" do product_file = build(:product_file, url: "https:/unknown.com/manual.pdf") expect(product_file.has_cdn_url?).to be_falsey end end describe "#has_valid_external_link?" do it "returns truthy value when url is valid" do test_urls = ["http://www.example.abc/test", "https://www.gumroad.com/product", "http://www.google.io/product"] test_urls.each do |test_url| product_file = build(:product_file, url: test_url) expect(product_file.has_valid_external_link?).to be_truthy end end it "returns falsey value when url is invalid" do test_urls = ["www.example.abc/test", "invalid_url", "ogle.io/product", "http:invalid", "http:/invalid"] test_urls.each do |test_url| product_file = build(:product_file, url: test_url) expect(product_file.has_valid_external_link?).to be_falsey end end end describe "#external_link?" do it "returns true for files which are external links" do product_file = create(:product_file, filetype: "link", url: "http://gumroad.com") expect(product_file.external_link?).to eq(true) end it "returns false for non-external link files" do product_file = create(:readable_document) expect(product_file.external_link?).to eq(false) end end describe "#display_extension" do it "returns URL for files which are external links" do product_file = create(:product_file, filetype: "link", url: "http://gumroad.com") expect(product_file.display_extension).to eq("URL") end it "returns extension for s3 files with an extension" do product_file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/files/43a5363194e74e9ee75b6203eaea6705/original/black/white.mp4") expect(product_file.display_extension).to eq("MP4") end it "returns empty string for s3 files without an extension" do product_file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/files/43a5363194e74e9ee75b6203eaea6705/original/black/white") expect(product_file.display_extension).to eq("") end end describe "#queue_for_transcoding" do it "returns `false` when both `streamable?` and `analyze_completed?` are `false`" do product_file = create(:product_file) product_file.update_columns(filegroup: "audio") # Need to bypass callbacks otherwise the value is overwritten expect(product_file.queue_for_transcoding?).to eq(false) end it "returns `false` when `streamable?` is `false` and `analyze_completed?` is `true`" do product_file = create(:product_file, analyze_completed: true) product_file.update_columns(filegroup: "audio") # Need to bypass callbacks otherwise the value is overwritten expect(product_file.queue_for_transcoding?).to eq(false) end it "returns `true` when both `streamable?` and `analyze_completed?` are `true`" do product_file = create(:product_file, analyze_completed: true) product_file.update_columns(filegroup: "video") # Need to bypass callbacks otherwise the value is overwritten expect(product_file.queue_for_transcoding?).to eq(true) end it "returns `false` when `streamable?` is `true` and `analyze_completed?` is `false`" do product_file = create(:product_file) product_file.update_columns(filegroup: "video") # Need to bypass callbacks otherwise the value is overwritten expect(product_file.queue_for_transcoding?).to eq(false) end end describe "#download_original" do it "returns original file as tempfile" do product_file = create(:readable_document) yielded = false product_file.download_original do |original_file| yielded = true expect(original_file.path).to include(".pdf") expect(original_file.size).to eq(111237) end expect(yielded).to eq(true) end end describe "#latest_media_location_for" do before do @url_redirect = create(:readable_url_redirect) @product_file = @url_redirect.referenced_link.product_files.first end it "returns nil if no media locations exist" do expect(@product_file.latest_media_location_for(@url_redirect.purchase)).to eq(nil) end it "returns nil if purchase does not exist" do expect(@product_file.latest_media_location_for(nil)).to eq(nil) end it "returns nil if product file belongs to an installment" do installment = create(:installment, call_to_action_text: "CTA", call_to_action_url: "https://www.gum.co", seller: create(:user)) installment_product_file = create(:product_file, installment:, link: installment.link) installment_purchase = create(:purchase, link: installment.link) installment_url_redirect = installment.generate_url_redirect_for_purchase(installment_purchase) create(:media_location, url_redirect_id: installment_url_redirect.id, purchase_id: installment_purchase.id, platform: Platform::WEB, product_file_id: installment_product_file.id, product_id: installment.link.id, location: 1, consumed_at: Time.current) expect(installment_product_file.latest_media_location_for(installment_purchase)).to eq(nil) end context "latest_media_location for different file types" do it "returns latest media location for readable" do consumption_timestamp = Time.current.change(usec: 0) create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, platform: Platform::WEB, product_file_id: @product_file.id, product_id: @url_redirect.referenced_link.id, location: 1, consumed_at: consumption_timestamp) expect(@product_file.latest_media_location_for(@url_redirect.purchase)).to eq({ location: 1, unit: MediaLocation::Unit::PAGE_NUMBER, timestamp: consumption_timestamp }) end it "returns latest media location for streamable" do streamable_file = create(:streamable_video, link: @url_redirect.referenced_link) consumption_timestamp = Time.current.change(usec: 0) create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, platform: Platform::WEB, product_file_id: streamable_file.id, product_id: @url_redirect.referenced_link.id, location: 2, consumed_at: consumption_timestamp) expect(streamable_file.latest_media_location_for(@url_redirect.purchase)).to eq({ location: 2, unit: MediaLocation::Unit::SECONDS, timestamp: consumption_timestamp }) end it "returns latest media location for listenable" do listenable_file = create(:listenable_audio, link: @url_redirect.referenced_link) consumption_timestamp = Time.current.change(usec: 0) create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, platform: Platform::WEB, product_file_id: listenable_file.id, product_id: @url_redirect.referenced_link.id, location: 10, consumed_at: consumption_timestamp) expect(listenable_file.latest_media_location_for(@url_redirect.purchase)).to eq({ location: 10, unit: MediaLocation::Unit::SECONDS, timestamp: consumption_timestamp }) end end it "returns the location with latest timestamp if multiple media_locations exist" do consumption_timestamp = Time.current.change(usec: 0) create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id,
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/card_bank_account_spec.rb
spec/models/card_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe CardBankAccount, :vcr do it "only allows debit cards" do card_bank_account = create(:card_bank_account) expect(card_bank_account.credit_card.funding_type).to eq(ChargeableFundingType::DEBIT) expect(card_bank_account.valid?).to be(true) card = card_bank_account.credit_card card.funding_type = ChargeableFundingType::CREDIT card.save! expect(card_bank_account.valid?).to be(false) expect(card_bank_account.errors[:base].first).to eq("Your payout card must be a US debit card.") end it "only allows cards from the US" do card_bank_account = create(:card_bank_account) expect(card_bank_account.credit_card.card_country).to eq(Compliance::Countries::USA.alpha2) expect(card_bank_account.valid?).to be(true) card = card_bank_account.credit_card card.card_country = Compliance::Countries::BRA.alpha2 card.save! expect(card_bank_account.valid?).to be(false) expect(card_bank_account.errors[:base].first).to eq("Your payout card must be a US debit card.") end it "disallows creating records with banned cards" do %w[5860 0559].each do |card_last_4| card_bank_account = build(:card_bank_account) card = card_bank_account.credit_card card.visual = "**** **** **** #{card_last_4}" expect(card_bank_account.valid?).to be(false) expect(card_bank_account.errors[:base].first).to eq("Your payout card must be a US debit card.") end end it "allows marking the records with banned cards as deleted" do %w[5860 0559].each do |card_last_4| card_bank_account = create(:card_bank_account) card = card_bank_account.credit_card card.visual = "**** **** **** #{card_last_4}" card.save! card_bank_account.mark_deleted! expect(card_bank_account.reload.deleted_at).to_not be_nil end end describe "#bank_account_type" do it "returns 'CARD'" do expect(create(:card_bank_account).bank_account_type).to eq("CARD") end end describe "#routing_number" do it "returns the capitalized card type" do expect(create(:card_bank_account).routing_number).to eq("Visa") end end describe "#account_number_visual" do it "returns the card's visual value" do expect(create(:card_bank_account).account_number_visual).to eq("**** **** **** 5556") end end describe "#account_number" do it "returns the card's visual value" do expect(create(:card_bank_account).account_number).to eq("**** **** **** 5556") end end describe "#account_number_last_four" do it "returns the last 4 digits of the card" do expect(create(:card_bank_account).account_number_last_four).to eq("5556") end end describe "#account_holder_full_name" do it "returns the card's visual value" do expect(create(:card_bank_account).account_holder_full_name).to eq("**** **** **** 5556") end end describe "#country" do it "returns the country code for the US" do expect(create(:card_bank_account).country).to eq(Compliance::Countries::USA.alpha2) end end describe "#currency" do it "returns the currency for the US" do expect(create(:card_bank_account).currency).to eq(Currency::USD) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/last_read_community_chat_message_spec.rb
spec/models/last_read_community_chat_message_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe LastReadCommunityChatMessage do subject(:last_read_message) { build(:last_read_community_chat_message) } describe "associations" do it { is_expected.to belong_to(:user) } it { is_expected.to belong_to(:community) } it { is_expected.to belong_to(:community_chat_message) } end describe "validations" do it { is_expected.to validate_uniqueness_of(:user_id).scoped_to(:community_id) } end describe ".set!" do let(:user) { create(:user) } let(:community) { create(:community) } let(:message1) { create(:community_chat_message, community: community, created_at: 1.hour.ago) } let(:message2) { create(:community_chat_message, community: community, created_at: Time.current) } context "when no record exists" do it "creates a new record" do expect do described_class.set!( user_id: user.id, community_id: community.id, community_chat_message_id: message1.id ) end.to change(described_class, :count).by(1) end end context "when record already exists" do before do create( :last_read_community_chat_message, user:, community:, community_chat_message: message1 ) end context "when given message is newer than existing message" do it "updates the record" do expect do described_class.set!( user_id: user.id, community_id: community.id, community_chat_message_id: message2.id ) end.not_to change(described_class, :count) last_read = described_class.find_by!(user:, community:) expect(last_read.community_chat_message_id).to eq(message2.id) end end context "when given message is older than existing message" do let(:message2) { create(:community_chat_message, community: community, created_at: 2.hours.ago) } it "does not update the record" do expect do described_class.set!( user_id: user.id, community_id: community.id, community_chat_message_id: message2.id ) end.not_to change(described_class, :count) last_read = described_class.find_by!(user:, community:) expect(last_read.community_chat_message_id).to eq(message1.id) end end end end describe ".unread_count_for" do let(:user) { create(:user) } let(:community) { create(:community) } let!(:message1) { create(:community_chat_message, community: community, created_at: 3.hours.ago) } let!(:message2) { create(:community_chat_message, community: community, created_at: 2.hours.ago) } let!(:message3) { create(:community_chat_message, community: community, created_at: 1.hour.ago) } context "when last read record exists" do before do create( :last_read_community_chat_message, user:, community:, community_chat_message: message1 ) end it "returns count of messages newer than the last read message" do count = described_class.unread_count_for( user_id: user.id, community_id: community.id ) expect(count).to eq(2) end it "returns count using provided message if specified" do count = described_class.unread_count_for( user_id: user.id, community_id: community.id, community_chat_message_id: message2.id ) expect(count).to eq(1) end end context "when no last read record exists" do it "returns count of all messages in the community" do count = described_class.unread_count_for( user_id: user.id, community_id: community.id ) expect(count).to eq(3) end end context "when messages are deleted" do before do create( :last_read_community_chat_message, user:, community:, community_chat_message: message1 ) message2.mark_deleted! end it "only counts alive messages" do count = described_class.unread_count_for( user_id: user.id, community_id: community.id ) expect(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/moldova_bank_account_spec.rb
spec/models/moldova_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe MoldovaBankAccount do describe "#bank_account_type" do it "returns MD" do expect(create(:moldova_bank_account).bank_account_type).to eq("MD") end end describe "#country" do it "returns MD" do expect(create(:moldova_bank_account).country).to eq("MD") end end describe "#currency" do it "returns mdl" do expect(create(:moldova_bank_account).currency).to eq("mdl") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:moldova_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAAMDMDXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:moldova_bank_account, account_number_last_four: "5678").account_number_visual).to eq("******5678") end end describe "#validate_bank_code" do it "allows only 8-11 characters in the correct format" do expect(build(:moldova_bank_account, bank_code: "AAAAMDMDXXX")).to be_valid expect(build(:moldova_bank_account, bank_code: "BBBBMDMDYYY")).to be_valid expect(build(:moldova_bank_account, bank_code: "AGRNMD2XZZZ")).to be_valid expect(build(:moldova_bank_account, bank_code: "AGRNMD2ZZ")).not_to be_valid expect(build(:moldova_bank_account, bank_code: "AGRNMM2XZZZ")).not_to be_valid expect(build(:moldova_bank_account, bank_code: "AGRNMD2XZZZZ")).not_to be_valid expect(build(:moldova_bank_account, bank_code: "AAAMDMDXXX")).not_to be_valid expect(build(:moldova_bank_account, bank_code: "AAAAMDMDXXXX")).not_to be_valid end end describe "#validate_account_number" do it "allows only 24 characters in the correct format" do expect(build(:moldova_bank_account, account_number: "MD07AG123456789012345678")).to be_valid expect(build(:moldova_bank_account, account_number: "MD11BC987654321098765432")).to be_valid expect(build(:moldova_bank_account, account_number: "MD07AG12345678901234567")).not_to be_valid expect(build(:moldova_bank_account, account_number: "MD07AG1234567890123456789")).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/chile_bank_account_spec.rb
spec/models/chile_bank_account_spec.rb
# frozen_string_literal: true describe ChileBankAccount do describe "#bank_account_type" do it "returns Chile" do expect(create(:chile_bank_account).bank_account_type).to eq("CL") end end describe "#country" do it "returns CL" do expect(create(:chile_bank_account).country).to eq("CL") end end describe "#currency" do it "returns clp" do expect(create(:chile_bank_account).currency).to eq("clp") end end describe "#routing_number" do it "returns valid for 3 characters" do ba = create(:chile_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("999") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:chile_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789") end end describe "#validate_bank_code" do it "allows 3 numeric characters only" do expect(build(:chile_bank_account, bank_code: "123")).to be_valid expect(build(:chile_bank_account, bank_code: "12")).not_to be_valid expect(build(:chile_bank_account, bank_code: "1234")).not_to be_valid expect(build(:chile_bank_account, bank_code: "12A")).not_to be_valid expect(build(:chile_bank_account, bank_code: "12@")).not_to be_valid end end describe "account types" do it "allows checking account types" do chile_bank_account = build(:chile_bank_account, account_type: ChileBankAccount::AccountType::CHECKING) expect(chile_bank_account).to be_valid expect(chile_bank_account.account_type).to eq(ChileBankAccount::AccountType::CHECKING) end it "allows savings account types" do chile_bank_account = build(:chile_bank_account, account_type: ChileBankAccount::AccountType::SAVINGS) expect(chile_bank_account).to be_valid expect(chile_bank_account.account_type).to eq(ChileBankAccount::AccountType::SAVINGS) end it "invalidates other account types" do chile_bank_account = build(:chile_bank_account, account_type: "evil_account_type") expect(chile_bank_account).to_not be_valid end it "translates a nil account type to the default (checking)" do chile_bank_account = build(:chile_bank_account, account_type: nil) expect(chile_bank_account).to be_valid expect(chile_bank_account.account_type).to eq(ChileBankAccount::AccountType::CHECKING) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/circle_integration_spec.rb
spec/models/circle_integration_spec.rb
# frozen_string_literal: true require "spec_helper" describe CircleIntegration do it "creates the correct json details" do integration = create(:circle_integration) CircleIntegration::INTEGRATION_DETAILS.each do |detail| expect(integration.respond_to?(detail)).to eq true end end it "saves details correctly" do integration = create(:circle_integration, community_id: "0", space_group_id: "0", keep_inactive_members: true) expect(integration.type).to eq(Integration.type_for(Integration::CIRCLE)) expect(integration.community_id).to eq("0") expect(integration.space_group_id).to eq("0") expect(integration.keep_inactive_members).to eq(true) end describe "#as_json" do it "returns the correct json object" do integration = create(:circle_integration) expect(integration.as_json).to eq({ api_key: GlobalConfig.get("CIRCLE_API_KEY"), keep_inactive_members: false, name: "circle", integration_details: { "community_id" => "3512", "space_group_id" => "43576", } }) end end describe ".is_enabled_for" do it "returns true if a circle integration is enabled on the product" do product = create(:product, active_integrations: [create(:circle_integration)]) purchase = create(:purchase, link: product) expect(CircleIntegration.is_enabled_for(purchase)).to eq(true) end it "returns false if a circle integration is not enabled on the product" do product = create(:product, active_integrations: [create(:discord_integration)]) purchase = create(:purchase, link: product) expect(CircleIntegration.is_enabled_for(purchase)).to eq(false) end it "returns false if a deleted circle integration exists on the product" do product = create(:product, active_integrations: [create(:circle_integration)]) purchase = create(:purchase, link: product) product.product_integrations.first.mark_deleted! expect(CircleIntegration.is_enabled_for(purchase)).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/trinidad_and_tobago_bank_account_spec.rb
spec/models/trinidad_and_tobago_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe TrinidadAndTobagoBankAccount do describe "#bank_account_type" do it "returns TT" do expect(create(:trinidad_and_tobago_bank_account).bank_account_type).to eq("TT") end end describe "#country" do it "returns TT" do expect(create(:trinidad_and_tobago_bank_account).country).to eq("TT") end end describe "#currency" do it "returns ttd" do expect(create(:trinidad_and_tobago_bank_account).currency).to eq("ttd") end end describe "#routing_number" do it "returns valid for 8 digits" do ba = create(:trinidad_and_tobago_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("99900001") end end describe "#account_number_visual" do it "returns the visual account number with country code prefixed" do expect(create(:trinidad_and_tobago_bank_account, account_number_last_four: "9999").account_number_visual).to eq("******9999") end end describe "#validate_bank_code" do it "allows 3 digits only" do expect(build(:trinidad_and_tobago_bank_account, bank_code: "110")).to be_valid expect(build(:trinidad_and_tobago_bank_account, bank_code: "123")).to be_valid expect(build(:trinidad_and_tobago_bank_account, bank_code: "11")).not_to be_valid expect(build(:trinidad_and_tobago_bank_account, bank_code: "ABC")).not_to be_valid end end describe "#validate_branch_code" do it "allows 5 digits only" do expect(build(:trinidad_and_tobago_bank_account, branch_code: "11001")).to be_valid expect(build(:trinidad_and_tobago_bank_account, branch_code: "12345")).to be_valid expect(build(:trinidad_and_tobago_bank_account, branch_code: "110011")).not_to be_valid expect(build(:trinidad_and_tobago_bank_account, branch_code: "ABCDE")).not_to be_valid end end describe "#validate_account_number" do it "allows records that match the required account number regex" do expect(build(:trinidad_and_tobago_bank_account, account_number: "000123456789")).to be_valid expect(build(:trinidad_and_tobago_bank_account, account_number: "123456789")).to be_valid expect(build(:trinidad_and_tobago_bank_account, account_number: "123456789012345")).to be_valid tt_bank_account = build(:trinidad_and_tobago_bank_account, account_number: "ABCDEFGHIJKL") expect(tt_bank_account).to_not be_valid expect(tt_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") tt_bank_account = build(:trinidad_and_tobago_bank_account, account_number: "8937040044053201300000") expect(tt_bank_account).to_not be_valid expect(tt_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/team_invitation_spec.rb
spec/models/team_invitation_spec.rb
# frozen_string_literal: true require "spec_helper" describe TeamInvitation do let(:seller) { create(:named_seller) } describe "validations" do it "requires seller, email, role to be present" do team_invitation = TeamInvitation.new expect(team_invitation.valid?).to eq(false) expect(team_invitation.errors.full_messages).to include("Seller must exist") expect(team_invitation.errors.full_messages).to include("Email is invalid") expect(team_invitation.errors.full_messages).to include("Role is not included in the list") end it "validates uniqueness for seller and email when the record is alive" do team_invitation = create(:team_invitation, seller:) team_invitation_dupe = team_invitation.dup expect(team_invitation_dupe.valid?).to eq(false) expect(team_invitation_dupe.errors.full_messages).to include("Email has already been invited") end it "validates email against active team membership" do team_membership = create(:team_membership, seller:) team_invitation = TeamInvitation.new(seller:, role: TeamMembership::ROLE_ADMIN, email: team_membership.user.email) expect(team_invitation.valid?).to eq(false) expect(team_invitation.errors.full_messages).to include("Email is associated with an existing team member") end it "validates email against owner's email" do team_invitation = TeamInvitation.new(seller:, role: TeamMembership::ROLE_ADMIN, email: seller.email) expect(team_invitation.valid?).to eq(false) expect(team_invitation.errors.full_messages).to include("Email is associated with an existing team member") end it "sanitizes email" do team_invitation = TeamInvitation.new(email: " Member@Example.com ") team_invitation.validate expect(team_invitation.email).to eq("member@example.com") end context "with deleted record" do let(:team_invitation) { create(:team_invitation, seller:) } before do team_invitation.update_as_deleted! end it "allows creating a new record with same email" do expect do create(:team_invitation, seller:, role: TeamMembership::ROLE_ADMIN, email: team_invitation.email) end.to change { TeamInvitation.count }.by(1) end end end describe "#expired?" do let(:team_invitation) { create(:team_invitation, seller:) } it "returns apropriate boolean value" do expect(team_invitation.expired?).to be(false) team_invitation.expires_at = Time.current expect(team_invitation.expired?).to be(true) end end describe "#from_gumroad_account?" do context "when seller.gumroad_account? is false" do let(:team_invitation) { create(:team_invitation, seller:) } it "returns false" do expect(team_invitation.from_gumroad_account?).to be(false) end end context "when seller.gumroad_account? is true" do let(:seller) { create(:named_seller, email: ApplicationMailer::ADMIN_EMAIL) } let(:team_invitation) { create(:team_invitation, seller:) } it "returns true" do expect(team_invitation.from_gumroad_account?).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/purchase_refund_policy_spec.rb
spec/models/purchase_refund_policy_spec.rb
# frozen_string_literal: true require "spec_helper" describe PurchaseRefundPolicy do it { is_expected.to have_one(:link).through(:purchase) } it { is_expected.to have_one(:product_refund_policy).through(:link) } describe "validations" do it "validates presence" do refund_policy = PurchaseRefundPolicy.new expect(refund_policy.valid?).to be false expect(refund_policy.errors.details[:purchase].first[:error]).to eq :blank expect(refund_policy.errors.details[:title].first[:error]).to eq :blank end describe "max_refund_period_in_days validation" do let(:purchase) { create(:purchase) } context "when created after MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON" do before do travel_to PurchaseRefundPolicy::MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON + 1.day end after do travel_back end it "requires max_refund_period_in_days to be present" do refund_policy = build(:purchase_refund_policy, purchase:, title: "30-day money back guarantee", max_refund_period_in_days: nil) expect(refund_policy.valid?).to be false expect(refund_policy.errors.details[:max_refund_period_in_days].first[:error]).to eq :blank end it "allows valid max_refund_period_in_days values" do refund_policy = build(:purchase_refund_policy, purchase:, title: "30-day money back guarantee", max_refund_period_in_days: 30) expect(refund_policy.valid?).to be true end end context "when created before MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON" do before do travel_to PurchaseRefundPolicy::MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON - 1.day end after do travel_back end it "does not require max_refund_period_in_days to be present" do refund_policy = build(:purchase_refund_policy, purchase:, title: "30-day money back guarantee", max_refund_period_in_days: nil) expect(refund_policy.valid?).to be true end it "allows max_refund_period_in_days to be nil" do refund_policy = build(:purchase_refund_policy, purchase:, title: "30-day money back guarantee", max_refund_period_in_days: nil) expect(refund_policy.valid?).to be true end end context "when created_at is nil (new record)" do it "requires max_refund_period_in_days to be present" do refund_policy = build(:purchase_refund_policy, purchase:, title: "30-day money back guarantee", max_refund_period_in_days: nil) expect(refund_policy.valid?).to be false expect(refund_policy.errors.details[:max_refund_period_in_days].first[:error]).to eq :blank end end end end describe "stripped_fields" do let(:purchase) { create(:purchase) } it "strips leading and trailing spaces for title and fine_print" do refund_policy = PurchaseRefundPolicy.new(purchase:, title: " Refund policy ", fine_print: " This is a product-level refund policy ") refund_policy.validate expect(refund_policy.title).to eq "Refund policy" expect(refund_policy.fine_print).to eq "This is a product-level refund policy" end it "nullifies fine_print" do refund_policy = create(:product_refund_policy, fine_print: "") expect(refund_policy.fine_print).to be_nil end end describe "product_refund_policy helper methods" do let(:product) { create(:product) } let(:product_refund_policy) { create(:product_refund_policy, product:) } let(:purchase) { create(:purchase, link: product) } describe "#different_than_product_refund_policy?" do context "when no product refund policy exists" do let(:refund_policy) do purchase.create_purchase_refund_policy!( title: "30-day money back guarantee", fine_print: "This is a purchase-level refund policy", max_refund_period_in_days: 30 ) end it "returns true" do expect(refund_policy.different_than_product_refund_policy?).to be true end end context "when max_refund_period_in_days is present" do let(:product_refund_policy) { create(:product_refund_policy, product:, max_refund_period_in_days: 30) } before do product.update!(product_refund_policy:) end context "when max_refund_period_in_days matches product refund policy" do let(:refund_policy) do purchase.create_purchase_refund_policy!( title: "Different title", fine_print: "Different fine print", max_refund_period_in_days: 30 ) end it "returns false" do expect(refund_policy.different_than_product_refund_policy?).to be false end end context "when max_refund_period_in_days differs from product refund policy" do let(:refund_policy) do purchase.create_purchase_refund_policy!( title: "Same title", fine_print: "Same fine print", max_refund_period_in_days: 14 ) end it "returns true" do expect(refund_policy.different_than_product_refund_policy?).to be true end end end context "when max_refund_period_in_days is not present" do let(:product_refund_policy) { create(:product_refund_policy, product:, title: "30-day money back guarantee") } before do product.update!(product_refund_policy:) end context "when title matches product refund policy title" do let(:refund_policy) do build( :purchase_refund_policy, purchase:, title: "30-day money back guarantee", fine_print: "Different fine print", max_refund_period_in_days: nil ) end it "returns false" do expect(refund_policy.different_than_product_refund_policy?).to be false end end context "when title differs from product refund policy title" do let(:refund_policy) do build( :purchase_refund_policy, purchase:, title: "Custom Refund Policy", fine_print: "Same fine print", max_refund_period_in_days: nil ) end it "returns true" do expect(refund_policy.different_than_product_refund_policy?).to be true 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_run_spec.rb
spec/models/community_chat_recap_run_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe CommunityChatRecapRun do subject(:recap_run) { build(:community_chat_recap_run) } describe "associations" do it { is_expected.to have_many(:community_chat_recaps).dependent(:destroy) } end describe "validations" do it { is_expected.to validate_presence_of(:from_date) } it { is_expected.to validate_presence_of(:to_date) } it { is_expected.to validate_uniqueness_of(:recap_frequency).scoped_to([:from_date, :to_date]) } it { is_expected.to validate_presence_of(:recap_frequency) } it { is_expected.to define_enum_for(:recap_frequency) .with_values(daily: "daily", weekly: "weekly") .backed_by_column_of_type(:string) .with_prefix(:recap_frequency) } end describe "scopes" do describe ".running" do it "returns only runs without finished_at timestamp" do running_run = create(:community_chat_recap_run, from_date: 1.day.ago.beginning_of_day, to_date: 1.day.ago.end_of_day) finished_run = create(:community_chat_recap_run, :finished, from_date: 2.day.ago.beginning_of_day, to_date: 2.day.ago.end_of_day) expect(described_class.running).to include(running_run) expect(described_class.running).not_to include(finished_run) end end describe ".finished" do it "returns only runs with finished_at timestamp" do running_run = create(:community_chat_recap_run, from_date: 1.day.ago.beginning_of_day, to_date: 1.day.ago.end_of_day) finished_run = create(:community_chat_recap_run, :finished, from_date: 2.day.ago.beginning_of_day, to_date: 2.day.ago.end_of_day) expect(described_class.finished).to include(finished_run) expect(described_class.finished).not_to include(running_run) end end describe ".between" do it "returns runs within the specified date range" do from_date = 3.days.ago.beginning_of_day to_date = 1.day.ago.end_of_day in_range_run = create(:community_chat_recap_run, from_date:, to_date:) before_range_run = create(:community_chat_recap_run, from_date: 5.days.ago.beginning_of_day, to_date: 4.days.ago.end_of_day) after_range_run = create(:community_chat_recap_run, from_date: Date.today.beginning_of_day, to_date: Date.tomorrow.end_of_day) result = described_class.between(from_date, to_date) expect(result).to include(in_range_run) expect(result).not_to include(before_range_run) expect(result).not_to include(after_range_run) end end end describe "#finished?" do it "returns true when finished_at is present" do recap_run = build(:community_chat_recap_run, finished_at: Time.current) expect(recap_run.finished?).to be true end it "returns false when finished_at is nil" do recap_run = build(:community_chat_recap_run, finished_at: nil) expect(recap_run.finished?).to be false end end describe "#check_if_finished!" do let(:recap_run) { create(:community_chat_recap_run, recaps_count: 3) } context "when already finished" do before { recap_run.update!(finished_at: 1.hour.ago) } it "does not update finished_at" do original_finished_at = recap_run.finished_at recap_run.check_if_finished! expect(recap_run.reload.finished_at).to eq(original_finished_at) end end context "when there are pending recaps" do before do create(:community_chat_recap, community_chat_recap_run: recap_run) create(:community_chat_recap, :finished, community_chat_recap_run: recap_run) end it "does not mark as finished" do recap_run.check_if_finished! expect(recap_run.reload.finished_at).to be_nil end end context "when all recaps are finished or failed" do before do create(:community_chat_recap, :finished, community_chat_recap_run: recap_run) create(:community_chat_recap, :finished, community_chat_recap_run: recap_run) create(:community_chat_recap, :failed, community_chat_recap_run: recap_run) end it "marks as finished" do expect do recap_run.check_if_finished! end.to change { recap_run.reload.finished_at }.from(nil) expect(recap_run.finished_at).to be_within(2.second).of(Time.current) end end context "when the recaps_count doesn't match processed recaps" do before do recap_run.update!(recaps_count: 4) create(:community_chat_recap, :finished, community_chat_recap_run: recap_run) create(:community_chat_recap, :finished, community_chat_recap_run: recap_run) create(:community_chat_recap, :failed, community_chat_recap_run: recap_run) end it "does not mark as finished" do recap_run.check_if_finished! expect(recap_run.reload.finished_at).to be_nil end end end describe "callbacks" do describe "after_save_commit" do describe "#trigger_weekly_recap_run" do let(:saturday) { Date.new(2025, 3, 22) } # A Saturday let(:sunday) { Date.new(2025, 3, 23) } # A Sunday context "when a daily recap run finishes for a Saturday" do let(:recap_run) { create(:community_chat_recap_run, from_date: saturday) } it "enqueues a weekly recap run job with the correct date" do expected_date = (saturday - 6.days).to_date.to_s expect do recap_run.update!(finished_at: Time.current) end.to change { TriggerCommunityChatRecapRunJob.jobs.size }.by(1) expect(TriggerCommunityChatRecapRunJob).to have_enqueued_sidekiq_job("weekly", expected_date) end end context "when daily recap finishes on a non-Saturday" do let(:recap_run) { build(:community_chat_recap_run, recap_frequency: "daily", from_date: sunday) } it "does not enqueue a weekly recap run job" do expect do recap_run.update!(finished_at: Time.current) end.not_to change { TriggerCommunityChatRecapRunJob.jobs.size } end end context "when a weekly recap run finishes" do let(:recap_run) { create(:community_chat_recap_run, :weekly, from_date: saturday - 6.days) } it "does not enqueue any other recap run job" do expect do recap_run.update!(finished_at: Time.current) end.not_to change { TriggerCommunityChatRecapRunJob.jobs.size } end end context "when run is not finished" do let(:recap_run) { build(:community_chat_recap_run, from_date: saturday) } it "does not enqueue a weekly recap run job" do expect do recap_run.save! end.not_to change { TriggerCommunityChatRecapRunJob.jobs.size } end end end describe "#send_recap_notifications" do let(:recap_run) { create(:community_chat_recap_run) } context "when run is marked as finished" do it "enqueues a notification job" do expect do recap_run.update!(finished_at: Time.current) end.to change { SendCommunityChatRecapNotificationsJob.jobs.size }.by(1) expect(SendCommunityChatRecapNotificationsJob).to have_enqueued_sidekiq_job(recap_run.id) expect(recap_run.reload.notified_at).to be_within(2.second).of(Time.current) end end context "when run is already notified" do before { recap_run.update!(notified_at: 1.hour.ago) } it "does not enqueue a notification job" do expect do recap_run.update!(finished_at: Time.current) end.not_to change { SendCommunityChatRecapNotificationsJob.jobs.size } end end context "when run is not finished" do it "does not enqueue a notification job" do expect do recap_run.save! end.not_to change { SendCommunityChatRecapNotificationsJob.jobs.size } 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/offer_code_spec.rb
spec/models/offer_code_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/max_purchase_count_concern" describe OfferCode do before do @product = create(:product, user: create(:user), price_cents: 2000, price_currency_type: "usd") end it_behaves_like "MaxPurchaseCount concern", :offer_code describe "code validation" do describe "uniqueness" do describe "universal offer codes" do it "does not allow 2 live universal offer codes with same code" do create(:universal_offer_code, code: "off", user: @product.user) duplicate_offer_code = OfferCode.new(code: "off", universal: true, user: @product.user, amount_cents: 100, currency_type: "usd") expect(duplicate_offer_code).to_not be_valid expect(duplicate_offer_code.errors.full_messages).to eq(["Discount code must be unique."]) end it "does not allow a universal offer code to have the same name as any product's offer code" do create(:offer_code, code: "off", user: @product.user, products: [@product]) duplicate_offer_code = OfferCode.new(code: "off", universal: true, user: @product.user, amount_cents: 100, currency_type: "usd") expect(duplicate_offer_code).to_not be_valid expect(duplicate_offer_code.errors.full_messages).to eq(["Discount code must be unique."]) end it "allows offer codes with same code if one of them is deleted" do old_code = create(:universal_offer_code, code: "off", user: @product.user) old_code.mark_deleted! live_offer_code = OfferCode.new(code: "off", universal: true, user: old_code.user, amount_cents: 100, currency_type: "usd") expect(live_offer_code).to be_valid expect { live_offer_code.save! }.to change { OfferCode.count }.by(1) # Make sure the validation does not prevent offer codes from being marked as deleted (deleted offer codes may have duplicate codes) live_offer_code.mark_deleted! expect(live_offer_code).to be_deleted end end describe "product-specific offer codes" do it "does not allow 2 live offer codes with same code" do create(:offer_code, code: "off", user: @product.user, products: [@product]) duplicate_offer_code = OfferCode.new(code: "off", user: @product.user, products: [@product], amount_cents: 100, currency_type: "usd") expect(duplicate_offer_code).to_not be_valid expect(duplicate_offer_code.errors.full_messages).to eq(["Discount code must be unique."]) end it "does not allow a product-specific offer code with the same code as the universal offer code" do create(:universal_offer_code, code: "off", user: @product.user) duplicate_offer_code = OfferCode.new(code: "off", user: @product.user, products: [@product], amount_cents: 100, currency_type: "usd") expect(duplicate_offer_code).to_not be_valid expect(duplicate_offer_code.errors.full_messages).to eq(["Discount code must be unique."]) end it "allows offer codes with same code if one of them is deleted" do old_code = create(:offer_code, code: "off", products: [@product]) old_code.mark_deleted! offer_code = OfferCode.new(code: "off", user: old_code.user, products: [@product], amount_cents: 100, currency_type: "usd") expect(offer_code).to be_valid expect { offer_code.save! }.to change { OfferCode.count }.by(1) offer_code.mark_deleted! expect(offer_code).to be_deleted end end end it "allows offer codes with alphanumeric characters, dashes, and underscores" do %w[100OFF 25discount sale50 ÕËëæç disc-50_100].each do |code| expect { create(:offer_code, products: [@product], code:) }.to change { OfferCode.count }.by(1) end end it "rejects offer codes with forbidden characters" do %w[100% #100OFF 100.OFF OFF@100].each do |code| offer_code = OfferCode.new(code:, products: [@product], amount_cents: 100, currency_type: "usd") expect(offer_code).to be_invalid expect(offer_code.errors.full_messages).to include("Discount code can only contain numbers, letters, dashes, and underscores.") end end it "strips lagging and leading whitespace from code" do [" foo", "bar ", " baz "].each do |code| offer_code = build(:offer_code, code:, products: [@product], amount_cents: 100, currency_type: "usd") expect(offer_code).to be_valid expect(offer_code.code).to eq code.strip end end end describe "#price_validation" do describe "percentage offer codes" do it "is valid if the price after discount is above the minimum purchase price" do expect { create(:percentage_offer_code, code: "oc1", products: [@product], amount_percentage: 50) }.to change { OfferCode.count }.by(1) expect { create(:percentage_offer_code, code: "oc2", products: [@product], amount_percentage: 100) }.to change { OfferCode.count }.by(1) expect { create(:percentage_offer_code, code: "oc3", products: [@product], amount_percentage: 5) }.to change { OfferCode.count }.by(1) expect { create(:percentage_offer_code, code: "oc4", products: [@product], amount_percentage: 0) }.to change { OfferCode.count }.by(1) end it "is not valid if the price after discount is below the minimum purchase price" do expect { create(:percentage_offer_code, products: [@product], amount_percentage: 99) } .to raise_error(ActiveRecord::RecordInvalid, "Validation failed: The price after discount for all of your products must be either $0 or at least $0.99.") expect { create(:percentage_offer_code, products: [@product], amount_percentage: 99) rescue nil }.to_not change { OfferCode.count } end it "is not valid if the percentage amount is outside 0-100 range" do expect { create(:percentage_offer_code, products: [@product], amount_percentage: 123) } .to raise_error(ActiveRecord::RecordInvalid, "Validation failed: Please enter a discount amount that is 100% or less.") expect { create(:percentage_offer_code, products: [@product], amount_percentage: 123) rescue nil }.to_not change { OfferCode.count } expect { create(:percentage_offer_code, products: [@product], amount_percentage: -100) rescue nil }.to_not change { OfferCode.count } end end describe "cents offer codes" do it "is valid if the amount off is >= 0" do expect { create(:offer_code, code: "oc1", products: [@product], amount_cents: 1000) }.to change { OfferCode.count }.by(1) expect { create(:offer_code, code: "oc2", products: [@product], amount_cents: 2000) }.to change { OfferCode.count }.by(1) expect { create(:offer_code, code: "oc3", products: [@product], amount_cents: 50) }.to change { OfferCode.count }.by(1) expect { create(:offer_code, code: "oc4", products: [@product], amount_cents: 10_000) }.to change { OfferCode.count }.by(1) expect { create(:offer_code, code: "oc5", products: [@product], amount_cents: 0) }.to change { OfferCode.count }.by(1) end it "is not valid if the amount off is negative" do expect { create(:offer_code, products: [@product], amount_cents: -2000) rescue nil }.to_not change { OfferCode.count } end it "is not valid if the price after discount is less than the minimum purchase price" do expect { create(:offer_code, products: [@product], amount_cents: 1999.5) } .to raise_error(ActiveRecord::RecordInvalid, "Validation failed: The price after discount for all of your products must be either $0 or at least $0.99.") expect { create(:offer_code, products: [@product], amount_cents: 1999.5) rescue nil }.to_not change { OfferCode.count } expect { create(:offer_code, products: [@product], amount_cents: -2000) rescue nil }.to_not change { OfferCode.count } end end describe "universal offer codes" do before do create(:product, user: @product.user, price_cents: 1000, price_currency_type: "usd") end it "persists valid offer codes" do expect { create(:universal_offer_code, code: "oc1", user: @product.user, amount_cents: 1000) }.to change { OfferCode.count }.by(1) expect { create(:universal_offer_code, code: "oc2", user: @product.user, amount_cents: 500) }.to change { OfferCode.count }.by(1) expect { create(:universal_offer_code, code: "oc3", user: @product.user, amount_cents: 2000) }.to change { OfferCode.count }.by(1) expect { create(:universal_offer_code, code: "oc4", user: @product.user, amount_cents: 10_000) }.to change { OfferCode.count }.by(1) expect { create(:universal_offer_code, code: "oc5", user: @product.user, amount_percentage: 50, amount_cents: nil) }.to change { OfferCode.count }.by(1) end it "does not persist invalid offer codes" do expect { create(:universal_offer_code, user: @product.user, amount_cents: -2000) rescue nil }.to_not change { OfferCode.count } expect { create(:universal_offer_code, user: @product.user, amount_percentage: 99, amount_cents: nil) rescue nil }.to_not change { OfferCode.count } end context "different currencies for products" do before do @euro_product = create(:product, user: @product.user, price_cents: 500, price_currency_type: "eur") end it "persists valid offer codes" do expect { create(:universal_offer_code, code: "uoc1", user: @product.user, amount_cents: 1000, currency_type: "usd") }.to change { OfferCode.count }.by(1) expect { create(:universal_offer_code, code: "uoc2", user: @product.user, amount_cents: 5000, currency_type: "usd") }.to change { OfferCode.count }.by(1) expect { create(:universal_offer_code, code: "uoc3", user: @product.user, amount_cents: 500, currency_type: "eur") }.to change { OfferCode.count }.by(1) expect { create(:universal_offer_code, code: "uoc4", user: @product.user, amount_cents: 1000, currency_type: "eur") }.to change { OfferCode.count }.by(1) expect { create(:universal_offer_code, code: "uoc5", user: @product.user, amount_percentage: 50, amount_cents: nil) }.to change { OfferCode.count }.by(1) end it "does not persist invalid offer codes" do expect { create(:universal_offer_code, code: "uoc", user: @product.user, amount_percentage: 99, amount_cents: nil) rescue nil }.to_not change { OfferCode.count } end end end context "the offer code applies to a membership product" do let(:offer_code) { create(:offer_code, products: [create(:membership_product_with_preset_tiered_pricing)], amount_cents: 300) } context "the offer code is fixed-duration" do before do offer_code.duration_in_billing_cycles = 1 end context "the offer code discounts the membership to free" do it "adds an error" do expect(offer_code).to_not be_valid expect(offer_code.errors.full_messages.first).to eq("A fixed-duration discount code cannot be used to make a membership product temporarily free. Please add a free trial to your membership instead.") end end context "the offer code doesn't discount the membership to free" do before do offer_code.update!(amount_cents: 100) end it "doesn't add an error" do expect(offer_code).to be_valid end end end context "the offer code is not fixed duration" do context "the offer code discounts the membership to free" do it "doesn't add an error" do expect(offer_code).to be_valid end end context "the offer code doesn't discount the membership to free" do before do offer_code.update!(amount_cents: 100) end it "doesn't add an error" do expect(offer_code).to be_valid end end end end end describe "validity dates validation" do context "when the start date is before the expiration date" do let(:offer_code) { build(:offer_code, valid_at: 2.days.ago, expires_at: 1.day.ago) } it "doesn't add an error" do expect(offer_code.valid?).to eq(true) end end context "when the expiration date is before the start date" do let(:offer_code) { build(:offer_code, valid_at: 1.day.ago, expires_at: 2.days.ago) } it "adds an error" do expect(offer_code.valid?).to eq(false) expect(offer_code.errors.full_messages.first).to eq("The discount code's start date must be earlier than its end date.") end end context "when the start date is unset and the expiration date is set" do let(:offer_code) { build(:offer_code, expires_at: 1.day.ago) } it "adds an error" do expect(offer_code.valid?).to eq(false) expect(offer_code.errors.full_messages.first).to eq("The discount code's start date must be earlier than its end date.") end end end describe "currency type validation" do context "percentage offer codes" do let(:usd_product) { create(:product, user: @product.user, price_cents: 1000, price_currency_type: "usd") } let(:eur_product) { create(:product, user: @product.user, price_cents: 800, price_currency_type: "eur") } context "when the offer code is a percentage discount" do it "doesn't validate currency type for percentage discounts" do offer_code = build(:percentage_offer_code, products: [usd_product], amount_percentage: 50) expect(offer_code).to be_valid end it "allows percentage discounts on products with different currencies" do offer_code = build(:percentage_offer_code, products: [usd_product, eur_product], amount_percentage: 25) expect(offer_code).to be_valid end end end context "cents offer codes" do let(:usd_product) { create(:product, user: @product.user, price_cents: 1000, price_currency_type: "usd") } let(:eur_product) { create(:product, user: @product.user, price_cents: 800, price_currency_type: "eur") } let(:gbp_product) { create(:product, user: @product.user, price_cents: 900, price_currency_type: "gbp") } context "when the currency types match" do it "is valid for USD products with USD offer code" do offer_code = build(:offer_code, products: [usd_product], amount_cents: 200, currency_type: "usd") expect(offer_code).to be_valid end it "is valid for EUR products with EUR offer code" do offer_code = build(:offer_code, products: [eur_product], amount_cents: 150, currency_type: "eur") expect(offer_code).to be_valid end it "is valid for multiple products with same currency type" do usd_product2 = create(:product, user: @product.user, price_cents: 1500, price_currency_type: "usd") offer_code = build(:offer_code, products: [usd_product, usd_product2], amount_cents: 300, currency_type: "usd") expect(offer_code).to be_valid end end context "when the currency types don't match" do it "adds an error for USD product with EUR offer code" do offer_code = build(:offer_code, products: [usd_product], amount_cents: 200, currency_type: "eur") expect(offer_code).to_not be_valid expect(offer_code.errors.full_messages).to include("This discount code uses EUR but the product uses USD. Please change the discount code to use the same currency as the product.") end it "adds an error for EUR product with GBP offer code" do offer_code = build(:offer_code, products: [eur_product], amount_cents: 150, currency_type: "gbp") expect(offer_code).to_not be_valid expect(offer_code.errors.full_messages).to include("This discount code uses GBP but the product uses EUR. Please change the discount code to use the same currency as the product.") end it "adds an error when products have mixed currencies" do offer_code = build(:offer_code, products: [usd_product, eur_product], amount_cents: 200, currency_type: "usd") expect(offer_code).to_not be_valid expect(offer_code.errors.full_messages).to include("This discount code uses USD but the product uses EUR. Please change the discount code to use the same currency as the product.") end end context "universal offer codes" do it "is valid for universal offer codes with currency type specified" do offer_code = build(:universal_offer_code, user: @product.user, amount_cents: 500, currency_type: "usd", universal: true) expect(offer_code).to be_valid end it "is valid for universal percentage offer codes without currency type" do offer_code = build(:universal_offer_code, user: @product.user, amount_percentage: 25, universal: true) expect(offer_code).to be_valid end end end end describe "#amount_off" do describe "percentage offer codes" do it "correctly calculates the amount off" do zero_off = create(:percentage_offer_code, code: "ZERO_OFF", products: [@product], amount_percentage: 0) expect(zero_off.amount_off(@product.price_cents)).to eq 0 ten_off = create(:percentage_offer_code, code: "TEN_OFF", products: [@product], amount_percentage: 10) expect(ten_off.amount_off(@product.price_cents)).to eq 200 fifty_off = create(:percentage_offer_code, code: "FIFTY_OFF", products: [@product], amount_percentage: 50) expect(fifty_off.amount_off(@product.price_cents)).to eq 1000 hundred_off = create(:percentage_offer_code, code: "FREE", products: [@product], amount_percentage: 100) expect(hundred_off.amount_off(@product.price_cents)).to eq 2000 end it "rounds the amount off" do product = create(:product, price_cents: 599, price_currency_type: "usd") offer_code = create(:percentage_offer_code, products: [product], amount_percentage: 50) expect(offer_code.amount_off(product.price_cents)).to eq 300 offer_code.update!(amount_percentage: 70) expect(offer_code.amount_off(1395)).to eq 976 end end describe "cents offer codes" do it "correctly calculates the amount off" do offer_code_1 = create(:offer_code, code: "1000_OFF", products: [@product], amount_cents: 1000) expect(offer_code_1.amount_off(@product.price_cents)).to eq 1000 offer_code_2 = create(:offer_code, code: "500_OFF", products: [@product], amount_cents: 500) expect(offer_code_2.amount_off(@product.price_cents)).to eq 500 offer_code_3 = create(:offer_code, code: "2000_OFF", products: [@product], amount_cents: 2000) expect(offer_code_3.amount_off(@product.price_cents)).to eq 2000 end end end describe "#original_price" do it "returns the original price for a percentage offer code" do offer_code = create(:percentage_offer_code, products: [@product], amount_percentage: 20) expect(offer_code.original_price(800)).to eq 1000 expect(offer_code.original_price(199)).to eq 249 end it "returns the original price for a cents offer code" do offer_code = create(:offer_code, products: [@product], amount_cents: 300) expect(offer_code.original_price(1000)).to eq 1300 end it "returns nil for a 100% off offer code" do offer_code = create(:percentage_offer_code, products: [@product], amount_percentage: 100) expect(offer_code.original_price(0)).to eq nil expect(offer_code.original_price(100)).to eq nil end end describe "#as_json" do describe "percentage offer codes" do before do @offer_code = create(:percentage_offer_code, products: [@product], amount_percentage: 50) end it "returns percent_off and not amount_cents" do params = @offer_code.as_json expect(params[:percent_off]).to eq 50 expect(params[:amount_cents]).to eq nil end end describe "cents offer codes" do before do @offer_code = create(:offer_code, products: [@product], amount_cents: 1000) end it "returns amount_cents and not percent_off" do params = @offer_code.as_json expect(params[:amount_cents]).to eq 1000 expect(params[:percent_off]).to eq nil end end end describe "#quantity_left" do let(:offer_code) { create(:universal_offer_code, user: @product.user, max_purchase_count: 10) } let(:membership) { create(:membership_product, user: offer_code.user) } it "counts free trial purchases" do product = create(:membership_product, :with_free_trial_enabled, user: offer_code.user) create(:free_trial_membership_purchase, link: product, offer_code:, seller: offer_code.user) expect(offer_code.quantity_left).to eq offer_code.max_purchase_count - 1 end it "counts preorder purchases" do create(:preorder_authorization_purchase, link: @product, offer_code:, seller: offer_code.user) expect(offer_code.quantity_left).to eq offer_code.max_purchase_count - 1 end it "counts original subscription purchases" do create(:membership_purchase, link: membership, offer_code:, seller: offer_code.user) expect(offer_code.quantity_left).to eq offer_code.max_purchase_count - 1 end it "excludes other purchases" do create(:recurring_membership_purchase, link: membership, offer_code:, is_original_subscription_purchase: false) create(:membership_purchase, link: membership, offer_code:, is_archived_original_subscription_purchase: true) create(:failed_purchase, link: @product, offer_code:, seller: @product.user) create(:test_purchase, link: @product, offer_code:, seller: @product.user) expect(offer_code.quantity_left).to eq offer_code.max_purchase_count end describe "universal offer codes" do let(:offer_code) { create(:universal_offer_code, user: @product.user, amount_percentage: 100, amount_cents: nil, currency_type: @product.price_currency_type, max_purchase_count: 10) } it "counts successful purchases" do create(:purchase, link: @product, offer_code:, seller: @product.user, price_cents: @product.price_cents) expect(offer_code.quantity_left).to eq offer_code.max_purchase_count - 1 end it "sums the quantities of applicable purchases" do create(:purchase, link: @product, offer_code:, seller: @product.user, price_cents: @product.price_cents * 10, quantity: 10) expect(offer_code.quantity_left).to eq 0 end end describe "product offer codes" do let(:offer_code) { create(:percentage_offer_code, products: [@product], amount_percentage: 50, max_purchase_count: 20) } it "counts successful purchases" do create(:purchase, link: @product, offer_code:, seller: @product.user, price_cents: @product.price_cents) expect(offer_code.quantity_left).to eq offer_code.max_purchase_count - 1 end it "sums the quantities of applicable purchases" do create(:purchase, link: @product, offer_code:, seller: @product.user, price_cents: @product.price_cents * 20, quantity: 20) expect(offer_code.quantity_left).to eq 0 end end end describe "#inactive?" do context "when the offer code has no valid or expiriration date" do let(:offer_code) { create(:offer_code) } it "returns false" do expect(offer_code.inactive?).to eq(false) end end context "when the offer code is valid and has no expiration" do let(:offer_code) { create(:offer_code, valid_at: 1.year.ago) } it "returns false" do expect(offer_code.inactive?).to eq(false) end end context "when the offer code is not yet valid" do let(:offer_code) { create(:offer_code, valid_at: 1.year.from_now) } it "returns true" do expect(offer_code.inactive?).to eq(true) end end context "when the offer code is expired" do let(:offer_code) { create(:offer_code, valid_at: 2.years.ago, expires_at: 1.year.ago) } it "returns true" do expect(offer_code.inactive?).to eq(true) end end end describe "#discount" do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } context "when the discount is fixed" do let(:offer_code) { create(:offer_code, products: [product], amount_cents: 100, minimum_quantity: 2, duration_in_billing_cycles: 1, minimum_amount_cents: 100) } it "returns the discount" do expect(offer_code.discount).to eq( { type: "fixed", cents: 100, product_ids: [product.external_id], expires_at: nil, minimum_quantity: 2, duration_in_billing_cycles: 1, minimum_amount_cents: 100, } ) end end context "when the discount is percentage" do let(:offer_code) { create(:percentage_offer_code, amount_percentage: 10, universal: true, valid_at: 1.day.ago, expires_at: 1.day.from_now) } it "returns the discount" do expect(offer_code.discount).to eq( { type: "percent", percents: 10, product_ids: nil, expires_at: offer_code.expires_at, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, } ) end end end describe "#is_amount_valid?" do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller, price_cents: 200) } context "when the offer code is absolute" do context "when the discounted price is 0" do let(:offer_code) { create(:offer_code, user: seller, products: [product], amount_cents: 200) } it "returns true" do expect(offer_code.is_amount_valid?(product)).to eq(true) end end context "when the discounted price is greater than or equal to the minimum" do let(:offer_code) { create(:offer_code, user: seller, products: [product], amount_cents: 100) } it "returns true" do expect(offer_code.is_amount_valid?(product)).to eq(true) end end context "when the discounted price is less than the minimum and not 0" do let!(:offer_code) { create(:offer_code, user: seller, products: [product], amount_cents: 100) } before do product.update!(price_cents: 150) end it "returns false" do expect(offer_code.is_amount_valid?(product)).to eq(false) end end context "when the product is a tiered membership" do let(:membership) { create(:membership_product_with_preset_tiered_pricing, user: seller) } let!(:offer_code) { create(:offer_code, user: seller, products: [membership], amount_cents: 300) } context "when at least one tier has an invalid discounted price" do before do membership.alive_variants.first.prices.first.update!(price_cents: 350) end it "returns false" do expect(offer_code.is_amount_valid?(membership)).to eq(false) end end context "when all tiers have valid discounted prices" do it "returns true" do expect(offer_code.is_amount_valid?(membership)).to eq(true) end end end context "when the product is a versioned product" do let(:versioned_product) { create(:product_with_digital_versions, user: seller) } let!(:offer_code) { create(:offer_code, user: seller, products: [versioned_product], amount_cents: 100) } context "when at least one version has an invalid discounted price" do before do versioned_product.alive_variants.first.update!(price_difference_cents: 50) end it "returns false" do expect(offer_code.is_amount_valid?(versioned_product)).to eq(false) end end context "when all versions have valid discounted prices" do it "returns true" do expect(offer_code.is_amount_valid?(versioned_product)).to eq(true) end end end end context "when the offer code is percentage" do context "when the discounted price is 0" do let(:offer_code) { create(:offer_code, user: seller, products: [product], amount_percentage: 100) } it "returns true" do expect(offer_code.is_amount_valid?(product)).to eq(true) end end context "when the discounted price is greater than or equal to the minimum" do let(:offer_code) { create(:offer_code, user: seller, products: [product], amount_percentage: 50) } it "returns true" do expect(offer_code.is_amount_valid?(product)).to eq(true) end end context "when the discounted price is less than the minimum and not 0" do let!(:offer_code) { create(:offer_code, user: seller, products: [product], amount_percentage: 50) } before do product.update!(price_cents: 150) end it "returns false" do expect(offer_code.is_amount_valid?(product)).to eq(false) end end end end describe "#applicable?" do context "when the offer code is universal and has no currency type" do let(:offer_code) { create(:universal_offer_code, user: @product.user, amount_percentage: 10, currency_type: nil) } let(:usd_product) { @product } let(:eur_product) { create(:product, user: @product.user, price_cents: 1000, price_currency_type: "eur") } it "returns true for products regardless of currency" do expect(offer_code.applicable?(usd_product)).to eq(true) expect(offer_code.applicable?(eur_product)).to eq(true) end end context "when the offer code is universal with a currency type" do let(:offer_code) { create(:universal_offer_code, user: @product.user, amount_cents: 100, currency_type: "usd") } let(:usd_product) { @product } let(:eur_product) { create(:product, user: @product.user, price_cents: 1000, price_currency_type: "eur") } it "returns true only for products with matching currency" do expect(offer_code.applicable?(usd_product)).to eq(true) expect(offer_code.applicable?(eur_product)).to eq(false) end end context "when the offer code applies to specific products" do let(:other_product) { create(:product, user: @product.user, price_cents: 1000, price_currency_type: "usd") } let(:offer_code) { create(:offer_code, products: [@product], amount_cents: 100, currency_type: "usd") } it "returns true for the associated product and false otherwise" do expect(offer_code.applicable?(@product)).to eq(true) expect(offer_code.applicable?(other_product)).to eq(false) end end end describe "reindexing products" do let(:creator) { create(:user) } let(:product1) { create(:product, user: creator) } let(:product2) { create(:product, user: creator) } let!(:offer_code) { create(:offer_code, user: creator, code: "BLACKFRIDAY2025", products: [product1, product2]) } describe "after_save callback" do it "reindexes associated products when offer code is updated" do expect(product1).to receive(:enqueue_index_update_for).with(["offer_codes"]) expect(product2).to receive(:enqueue_index_update_for).with(["offer_codes"]) offer_code.update(amount_cents: 500) end it "reindexes associated products when offer code code is changed" do expect(product1).to receive(:enqueue_index_update_for).with(["offer_codes"]) expect(product2).to receive(:enqueue_index_update_for).with(["offer_codes"]) offer_code.update(code: "NEWYEAR2025") end end describe "after_destroy callback" do let(:products_to_reindex) { [product1, product2] } before do allow(Link).to receive(:where).with(id: products_to_reindex.map(&:id)).and_return(products_to_reindex) end it "reindexes associated products when offer code is destroyed" do expect(product1).to receive(:enqueue_index_update_for).with(["offer_codes"])
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/user_spec.rb
spec/models/user_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/versionable_concern" describe User, :vcr do it_behaves_like "Versionable concern", :user, { email: %w(old@example.com), payment_address: %w(old-paypal@example.com paypal@example.com) } describe "associations" do before :each do @user = create(:user) end it "has many links" do product = create(:product, user: @user) expect(@user.reload.links).to match_array [product] end it "has many purchases as a purchaser" do purchase = create(:purchase, purchaser: @user) expect(@user.reload.purchases).to match_array [purchase] end describe "affiliate associations" do let!(:global_affiliate) { @user.global_affiliate } let!(:direct_affiliate) { create(:direct_affiliate, affiliate_user: @user) } let(:affiliated_products) { create_list(:product, 2) } it "has many affiliates as a seller" do direct_affiliate = create(:direct_affiliate, seller: @user) expect(@user.reload.direct_affiliates).to match_array [direct_affiliate] end it "has one (live) global affiliate" do global_affiliate.mark_deleted! live_global_affiliate = GlobalAffiliate.new(affiliate_user: @user, affiliate_basis_points: GlobalAffiliate::AFFILIATE_BASIS_POINTS) live_global_affiliate.save(validate: false) # bypass uniqueness validation expect(@user.reload.global_affiliate).to eq live_global_affiliate end it "has many direct affiliate accounts" do expect(@user.reload.direct_affiliate_accounts).to match_array [direct_affiliate] end it "has many affiliate accounts" do expect(@user.reload.affiliate_accounts).to match_array [direct_affiliate, global_affiliate] end it "has many affiliate sales" do direct_purchase = create(:purchase, affiliate: direct_affiliate) global_purchase = create(:purchase, affiliate: global_affiliate) create(:purchase, affiliate: create(:direct_affiliate)) expect(@user.affiliate_sales).to match_array [direct_purchase, global_purchase] end it "has many affiliated products" do direct_affiliate.products = affiliated_products global_affiliate.products << affiliated_products.second expect(@user.affiliated_products).to match_array affiliated_products end it "has many affiliated creators" do direct_affiliate.products = affiliated_products global_affiliate.products << affiliated_products.second expect(@user.affiliated_creators).to match_array affiliated_products.map(&:user) end end describe "collaborator associations" do it { is_expected.to have_many(:collaborators).with_foreign_key(:seller_id) } describe "#collaborating_products" do it "only contains those from collaborations the user have accepted" do user = create(:user) product1 = create(:product) product2 = create(:product) product3 = create(:product) accepted_collaboration = create( :collaborator, affiliate_user: user, seller: product1.user, products: [product1] ) # This is a pending collaboration. create( :collaborator, :with_pending_invitation, affiliate_user: user, seller: product2.user, products: [product2] ) # This is a deleted collaboration. create( :collaborator, affiliate_user: user, seller: product3.user, products: [product3], deleted_at: 1.day.ago ) expect(user.accepted_alive_collaborations).to contain_exactly(accepted_collaboration) expect(user.collaborating_products).to contain_exactly(product1) end end end it "has_many StripeApplePayDomains" do record = StripeApplePayDomain.create(user: @user, domain: "sample.gumroad.com", stripe_id: "sample_stripe_id") expect(@user.stripe_apple_pay_domains).to match_array [record] end it "has many blocked customer objects" do blocked_customer_object1 = create(:blocked_customer_object, seller: @user) blocked_customer_object2 = create(:blocked_customer_object, object_type: "charge_processor_fingerprint", object_value: "test1234", buyer_email: "john@example.com", seller: @user, blocked_at: DateTime.current) expect(@user.blocked_customer_objects).to match_array([blocked_customer_object1, blocked_customer_object2]) end it "has_one yearly stat" do yearly_stat = create(:yearly_stat, user: @user) expect(@user.yearly_stat).to eq yearly_stat end it "has_many utm_links" do utm_link = create(:utm_link, seller: @user) expect(@user.utm_links).to eq [utm_link] end it { is_expected.to have_many(:seller_communities).class_name("Community").with_foreign_key(:seller_id).dependent(:destroy) } it { is_expected.to have_many(:community_chat_messages).dependent(:destroy) } it { is_expected.to have_many(:last_read_community_chat_messages).dependent(:destroy) } it { is_expected.to have_many(:community_notification_settings).dependent(:destroy) } it { is_expected.to have_many(:seller_community_chat_recaps).class_name("CommunityChatRecap").with_foreign_key(:seller_id).dependent(:destroy) } end describe "scopes" do describe ".payment_reminder_risk_state" do it "selects creators that are not reviewed, flagged for TOS, or compliant" do not_reviewed = create(:user, user_risk_state: "not_reviewed") create(:user, user_risk_state: "on_probation") create(:user, user_risk_state: "flagged_for_fraud") create(:user, user_risk_state: "suspended_for_fraud") flagged_for_tos_violation = create(:user, user_risk_state: "flagged_for_tos_violation") create(:user, user_risk_state: "suspended_for_tos_violation") compliant = create(:user, user_risk_state: "compliant") expect(User.payment_reminder_risk_state).to match_array([not_reviewed, flagged_for_tos_violation, compliant]) end end describe ".not_suspended" do it "selects creators that are not suspended" do not_reviewed = create(:user, user_risk_state: "not_reviewed") on_probation = create(:user, user_risk_state: "on_probation") flagged_for_fraud = create(:user, user_risk_state: "flagged_for_fraud") create(:user, user_risk_state: "suspended_for_fraud") flagged_for_tos_violation = create(:user, user_risk_state: "flagged_for_tos_violation") create(:user, user_risk_state: "suspended_for_tos_violation") compliant = create(:user, user_risk_state: "compliant") expect(User.not_suspended).to match_array([not_reviewed, on_probation, flagged_for_fraud, flagged_for_tos_violation, compliant]) end end describe ".holding_balance_more_than" do before do @sam = create(:user) create(:balance, user: @sam, amount_cents: 10) create(:balance, user: @sam, amount_cents: 11, date: 1.day.ago) create(:balance, user: @sam, amount_cents: 100, date: 2.days.ago) create(:balance, user: @sam, amount_cents: -79, date: 3.days.ago, state: "paid") jill = create(:user) create(:balance, user: jill, amount_cents: 7) create(:balance, user: jill, amount_cents: 10, date: 1.day.ago) create(:balance, user: jill, amount_cents: 103, date: 2.days.ago) create(:balance, user: jill, amount_cents: 1, date: 3.days.ago, state: "paid") @jake = create(:user) create(:balance, user: @jake, amount_cents: 8) create(:balance, user: @jake, amount_cents: 9, date: 1.day.ago) create(:balance, user: @jake, amount_cents: 105, date: 2.days.ago) create(:balance, user: @jake, amount_cents: -53, date: 3.days.ago, state: "paid") end it "returns users who have unpaid balances more than the specified amount" do expect(described_class.holding_balance_more_than(120)).to match_array([@sam, @jake]) end end describe ".holding_balance" do before do @sam = create(:user) create(:balance, user: @sam, amount_cents: 1) create(:balance, user: @sam, amount_cents: -79, date: 3.days.ago, state: "paid") jill = create(:user) create(:balance, user: jill, amount_cents: -1, date: 2.days.ago) create(:balance, user: jill, amount_cents: 142, date: 3.days.ago, state: "paid") @jake = create(:user) create(:balance, user: @jake, amount_cents: 12, date: 1.day.ago) create(:balance, user: @jake, amount_cents: -53, date: 3.days.ago, state: "paid") end it "returns users who have unpaid balances more than 0" do expect(described_class.holding_balance).to match_array([@sam, @jake]) end end describe ".holding_non_zero_balance" do before do @sam = create(:user) create(:balance, user: @sam, amount_cents: 10) create(:balance, user: @sam, amount_cents: 11, date: 1.day.ago) create(:balance, user: @sam, amount_cents: -100, date: 2.days.ago) create(:balance, user: @sam, amount_cents: 79, date: 3.days.ago, state: "paid") jill = create(:user) create(:balance, user: jill, amount_cents: 20) create(:balance, user: jill, amount_cents: 121, date: 1.day.ago) create(:balance, user: jill, amount_cents: -141, date: 2.days.ago) create(:balance, user: jill, amount_cents: 1, date: 3.days.ago, state: "paid") @jake = create(:user) create(:balance, user: @jake, amount_cents: 20) create(:balance, user: @jake, amount_cents: 12, date: 1.day.ago) create(:balance, user: @jake, amount_cents: 21, date: 2.days.ago) create(:balance, user: @jake, amount_cents: -53, date: 3.days.ago, state: "paid") end it "returns users who have non-zero unpaid balances" do expect(described_class.holding_non_zero_balance).to match_array([@sam, @jake]) end end end describe "has_cdn_url" do before do stub_const("CDN_URL_MAP", { "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}" => "https://public-files.gumroad.com", "#{AWS_S3_ENDPOINT}/gumroad/" => "https://public-files.gumroad.com/res/gumroad/" }) puts "CDN_URL_MAP: #{CDN_URL_MAP}" puts "AWS_S3_ENDPOINT: #{AWS_S3_ENDPOINT}" end describe "#subscribe_preview_url" do before do @user_with_preview = create(:user, :with_subscribe_preview) end it "returns CDN URL" do key = @user_with_preview.subscribe_preview.key expect(@user_with_preview.subscribe_preview_url).to eq("https://public-files.gumroad.com/#{key}") end end describe "#resized_avatar_url" do before do @user = create(:user, :with_avatar) end it "returns CDN URL" do variant = @user.avatar.variant(resize_to_limit: [256, 256]).processed.key expect(@user.resized_avatar_url(size: 256)).to match("https://public-files.gumroad.com/#{variant}") end end describe "#avatar_url" do before do @user = create(:user, :with_avatar) end it "returns CDN URL" do expect(@user.avatar_url).to match("https://public-files.gumroad.com/#{@user.avatar_variant.key}") end end describe "#financial_annual_report_url_for" do context "when no annual reports attached" do let(:user) { create(:user) } it "returns nil" do expect(user.financial_annual_report_url_for(year: 2022)).to eq(nil) end end context "when annual report does not exist for year param" do let(:user) { create(:user, :with_annual_report) } it "returns nil" do expect(user.financial_annual_report_url_for(year: 2011)).to eq(nil) end end context "when annual report exists" do let(:user) { create(:user, :with_annual_report) } it "returns report URL for the current year by default" do expect(user.financial_annual_report_url_for).to match("https://public-files.gumroad.com/") end context "for a previous year" do let(:year) { 2019 } it "returns report URL for the selected year" do blob = ActiveStorage::Blob.create_and_upload!( io: Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "followers_import.csv"), "text/csv"), filename: "Financial Annual Report #{year}.csv", metadata: { year: } ) blob.analyze user.annual_reports.attach(blob) expect(user.financial_annual_report_url_for(year:)).to eq("https://public-files.gumroad.com/#{blob.key}") end end end end end describe "#display_name" do context "when name is present" do before do @user = create(:user, name: "Test name") end it "returns name" do expect(@user.display_name).to eq "Test name" end end context "when name is blank" do before do @user = create(:user, name: "", username: nil) end context "when 'prefer_email_over_default_username' is set to true" do subject(:display_name) { @user.display_name(prefer_email_over_default_username: true) } context "when a custom username is not set" do it "returns email" do expect(@user.username).to eq(@user.external_id) expect(display_name).to eq(@user.email) end end context "when a custom username is set" do before do @user.update!(username: "johndoe") end it "returns custom username" do expect(display_name).to eq("johndoe") end end end context "when 'prefer_email_over_default_username' is set to false" do subject(:display_name) { @user.display_name } context "when a custom username is not set" do it "returns username" do expect(display_name).to eq(@user.username) end end context "when a custom username is set" do before do @user.update!(username: "johndoe") end it "returns username" do expect(display_name).to eq("johndoe") end end end end end describe "#support_or_form_email" do let(:support_email) { "support-email@example.com" } let(:email) { "seller-email@example.com" } context "when support_email is set" do it "returns the support_email value" do user = create(:user, email:, support_email:) expect(user.support_or_form_email).to eq(support_email) end end context "when support_email is absent" do it "returns the email value" do user = create(:user, email:) expect(user.support_or_form_email).to eq(email) end end end describe "#product_level_support_emails" do let(:user) { create(:user) } let!(:product1) { create(:product, user:, support_email: "1+2@example.com") } let!(:product2) { create(:product, user:, support_email: "1+2@example.com") } let!(:product3) { create(:product, user:, support_email: "3@example.com") } let!(:product4) { create(:product, user:, support_email: nil) } before { Feature.activate(:product_level_support_emails) } it "returns the user's product support emails" do result = user.product_level_support_emails expect(result).to contain_exactly( { email: "1+2@example.com", product_ids: [product1.external_id, product2.external_id], }, { email: "3@example.com", product_ids: [product3.external_id], } ) end context "when product_level_support_emails feature is disabled" do before { Feature.deactivate(:product_level_support_emails) } it "returns nil" do expect(user.product_level_support_emails).to be_nil end end end describe "#update_product_level_support_emails!" do let(:user) { create(:user) } let!(:product1) { create(:product, user:, support_email: "old1@example.com") } let!(:product2) { create(:product, user:, support_email: "old2@example.com") } let!(:product3) { create(:product, user:, support_email: "old3@example.com") } before do Feature.activate(:product_level_support_emails) end it "updates products support emails" do user.update_product_level_support_emails!( [ { email: "new1+2@example.com", product_ids: [product1.external_id, product2.external_id] } ] ) expect(product1.reload.support_email).to eq("new1+2@example.com") expect(product2.reload.support_email).to eq("new1+2@example.com") expect(product3.reload.support_email).to eq(nil) end end describe "#has_valid_payout_info?" do let(:user) { create(:user) } it "returns true if the user has valid PayPal account info" do allow(PaypalPayoutProcessor).to receive(:has_valid_payout_info?).and_return(true) expect(user.has_valid_payout_info?).to eq true end it "returns true if the user has valid Stripe account info" do allow(StripePayoutProcessor).to receive(:has_valid_payout_info?).and_return(true) expect(user.has_valid_payout_info?).to eq true end it "returns false if the user has neither PayPal nor Stripe account info" do expect(user.has_valid_payout_info?).to eq false end end describe "merchant_account" do let(:user) { create(:user) } describe "user has no merchant accounts" do it "returns nil" do expect(user.merchant_account("charge-processor-id")).to eq(nil) end end describe "user has one merchant account" do let(:merchant_account_1) { create(:merchant_account, user:, charge_processor_id: "charge-processor-id-1") } before do merchant_account_1 end it "returns the merchant account if matching charge processor id" do expect(user.merchant_account("charge-processor-id-1")).to eq(merchant_account_1) end it "returns nil if stripe merchant account is for cross-border payouts only and can not accept charges" do create(:merchant_account, user:, country: "TH") expect(user.merchant_account("stripe")).to be nil end it "returns the merchant account if it can accept charges" do merchant_account = create(:merchant_account, user:, country: "HK") expect(user.merchant_account("stripe")).to eq(merchant_account) end it "returns nil if not matching charge processor id" do expect(user.merchant_account("charge-processor-id-2")).to eq(nil) end end describe "user has multiple merchant accounts" do let(:merchant_account_1) { create(:merchant_account, user:, charge_processor_id: "charge-processor-id-1") } let(:merchant_account_2) { create(:merchant_account, user:, charge_processor_id: "charge-processor-id-2") } before do merchant_account_1 merchant_account_2 end it "returns the merchant account if matching charge processor id" do expect(user.merchant_account("charge-processor-id-1")).to eq(merchant_account_1) expect(user.merchant_account("charge-processor-id-2")).to eq(merchant_account_2) end it "returns nil if not matching charge processor id" do expect(user.merchant_account("charge-processor-id-3")).to eq(nil) end end describe "merchant migration enabled" do before do @creator = create(:user) create(:user_compliance_info, user: @creator) Feature.activate_user(:merchant_migration, @creator) @stripe_account = create(:merchant_account_stripe, user: @creator) @stripe_connect_account = create(:merchant_account_stripe_connect, user: @creator) end it "returns the Stripe Connect account if present and merchant migration is enabled" do expect(@creator.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq(@stripe_connect_account) Feature.deactivate_user(:merchant_migration, @creator) @creator.check_merchant_account_is_linked = true @creator.save! expect(@creator.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq(@stripe_connect_account) end it "returns the custom stripe merchant account if no Stripe Connect account present" do @stripe_connect_account.mark_deleted! expect(@creator.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq(@stripe_account) end it "returns the custom stripe merchant account if merchant migration is not enabled" do Feature.deactivate_user(:merchant_migration, @creator) expect(@creator.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq(@stripe_account) end it "returns nil if neither Stripe Connect nor custom stripe merchant account present" do @stripe_connect_account.mark_deleted! @stripe_account.mark_deleted! expect(@creator.merchant_account(StripeChargeProcessor.charge_processor_id)).to be nil end end end describe "#profile_url" do let(:seller) { create(:named_seller) } it "returns the subdomain of the user by default" do expect(seller.profile_url).to eq("http://seller.test.gumroad.com:31337") end context "when given a custom domain" do it "returns the custom domain" do expect(seller.profile_url(custom_domain_url: "https://example.com")).to eq("https://example.com") end end context "when recommended_by is specified" do it "adds a query parameter" do expect(seller.profile_url(recommended_by: "discover")).to eq("http://seller.test.gumroad.com:31337?recommended_by=discover") expect(seller.profile_url(custom_domain_url: "https://example.com", recommended_by: "discover")).to eq("https://example.com?recommended_by=discover") end end end describe "#subdomain_with_protocol" do it "returns subdomain_with_protocol of the user after converting underscores to hyphens" do @creator = create(:user) # We don't support underscores in username now, but we need to generate subdomain_with_protocol for # old creators who have underscores in their username. @creator.update_column(:username, "test_user_1") stub_const("ROOT_DOMAIN", "test-root.gumroad.com") expect(@creator.subdomain_with_protocol).to eq "http://test-user-1.test-root.gumroad.com" end end describe "#subdomain" do it "returns subdomain of the user after converting underscores to hyphens" do @creator = create(:user) # We don't support underscores in username now, but we need to generate subdomain_with_protocol for # old creators who have underscores in their username. @creator.update_column(:username, "test_user_1") stub_const("ROOT_DOMAIN", "test-root.gumroad.com") expect(@creator.subdomain).to eq "test-user-1.test-root.gumroad.com" end end describe ".find_by_hostname" do before do @creator_without_username = create(:user, username: nil) @creator_with_subdomain = create(:user, username: "john") @creator_with_custom_domain = create(:user, username: "jane") create(:custom_domain, domain: "example.com", user: @creator_with_custom_domain) @root_hostname = URI("#{PROTOCOL}://#{ROOT_DOMAIN}").host end it "returns nil if blank hostname provided" do expect(User.find_by_hostname("")).to eq(nil) expect(User.find_by_hostname(nil)).to eq(nil) end it "finds user by subdomain" do expect(User.find_by_hostname("john.#{@root_hostname}")).to eq(@creator_with_subdomain) end it "finds user by custom domain" do expect(User.find_by_hostname("example.com")).to eq(@creator_with_custom_domain) end end describe "#two_factor_authentication_enabled" do before do @user = create(:user, skip_enabling_two_factor_authentication: false) end it "sets two_factor_authentication_enabled to true by default" do expect(@user.two_factor_authentication_enabled).to eq true end end describe "#set_refund_fee_notice_shown" do it "sets refund_fee_notice_shown to true by default" do expect(create(:user).refund_fee_notice_shown?).to eq true end end describe "#set_refund_policy_enabled" do it "sets refund_policy_enabled to true by default" do expect(create(:user).refund_policy_enabled?).to eq true end context "when seller_refund_policy_disabled_for_all feature flag is set to true" do before do Feature.activate(:seller_refund_policy_disabled_for_all) end it "sets refund_policy_enabled to false" do user = create(:user) expect(user.refund_policy_enabled?).to eq true expect(user.account_level_refund_policy_enabled?).to eq false Feature.deactivate(:seller_refund_policy_disabled_for_all) expect(user.refund_policy_enabled?).to eq true expect(user.account_level_refund_policy_enabled?).to eq true end end context "when seller_refund_policy_new_users_enabled feature flag is set to true" do before do Feature.deactivate(:seller_refund_policy_new_users_enabled) end it "sets refund_policy_enabled to false" do expect(create(:user).refund_policy_enabled?).to eq false end end end describe "#account_level_refund_policy_enabled?" do let(:user) { create(:user) } it { expect(user.account_level_refund_policy_enabled?).to be true } context "with account_level_refund_policy_delayed_for_sellers feature flag" do before { Feature.activate_user(:account_level_refund_policy_delayed_for_sellers, user) } context "with time" do it "returns false before LAST_ALLOWED_TIME_FOR_PRODUCT_LEVEL_REFUND_POLICY" do travel_to(User::LAST_ALLOWED_TIME_FOR_PRODUCT_LEVEL_REFUND_POLICY) do expect(user.account_level_refund_policy_enabled?).to be false end end it "returns true after LAST_ALLOWED_TIME_FOR_PRODUCT_LEVEL_REFUND_POLICY" do travel_to(User::LAST_ALLOWED_TIME_FOR_PRODUCT_LEVEL_REFUND_POLICY + 1.second) do expect(user.account_level_refund_policy_enabled?).to be true end end end end context "with seller_refund_policy_disabled_for_all" do before { Feature.activate(:seller_refund_policy_disabled_for_all) } it { expect(user.account_level_refund_policy_enabled?).to be false } end end describe "#paypal_payout_email" do let(:user) { create(:user, payment_address: "payme@example.com") } it "returns the payment_address if it is present" do expect(user.paypal_payout_email).to eq "payme@example.com" create(:merchant_account_paypal, user:, charge_processor_merchant_id: "B66YJBBNCRW6L") expect(user.paypal_payout_email).to eq "payme@example.com" end it "returns the email associated with connected PayPal account if payment_address is not present" do expect(user.paypal_payout_email).to eq "payme@example.com" create(:merchant_account_paypal, user:, charge_processor_merchant_id: "B66YJBBNCRW6L") user.update!(payment_address: "") expect(user.paypal_payout_email).to eq "sb-byx2u2205460@business.example.com" end it "returns nil if neither the payment_address nor connected PayPal account are present" do user.update!(payment_address: "") expect(user.paypal_payout_email).to eq nil end it "returns nil if payment_address is blank and connected PayPal account details are not available" do user.update!(payment_address: "") create(:merchant_account_paypal, user:, charge_processor_merchant_id: "B66YJBBNCRW6L") allow_any_instance_of(MerchantAccount).to receive(:paypal_account_details).and_return(nil) expect(user.paypal_payout_email).to eq nil end end describe "#build_user_compliance_info" do before do @user = build(:user) end it "sets json_data of user_compliance_info to an empty json" do expect(@user.build_user_compliance_info.attributes["json_data"]).to eq({}) end end describe "#deactivate!" do before do @user = create(:user) @user.fetch_or_build_user_compliance_info.dup_and_save! do |new_compliance_info| new_compliance_info.country = "United States" end @product = create(:product, user: @user) @installment = create(:installment, seller: @user) @bank_account = create(:ach_account_stripe_succeed, user: @user) end context "when user can be deactivated" do it "deactivates the user" do delete_at = Time.current travel_to(delete_at) do return_value = @user.reload.deactivate! expect(return_value).to be_truthy end expect(@user.reload.read_attribute(:username)).to be_nil expect(@user.deleted_at.to_i).to eq(delete_at.to_i) expect(@product.reload.deleted_at.to_i).to eq(delete_at.to_i) expect(@installment.reload.deleted_at.to_i).to eq(delete_at.to_i) expect(@user.user_compliance_infos.pluck(:deleted_at).map(&:to_i)).to eq([delete_at.to_i, delete_at.to_i]) expect(@bank_account.reload.deleted_at.to_i).to eq(delete_at.to_i) end it "invalidates all the active sessions" do travel_to(DateTime.current) do expect do @user.deactivate! end.to change { @user.reload.last_active_sessions_invalidated_at }.from(nil).to(DateTime.current) end end context "when user has a saved credit card" do before do @credit_card = create(:credit_card, users: [@user]) end it "clears the saved credit card information" do expect do @user.deactivate! end.to change { @user.reload.credit_card }.from(@credit_card).to(nil) end end context "when user has a custom domain" do before do @custom_domain = create(:custom_domain, user: @user) end it "marks the custom domain as deleted" do expect do @user.deactivate! end.to change { @custom_domain.reload.deleted_at }.from(nil).to(be_present) end it "handles deactivation when custom domain is already deleted" do @custom_domain.mark_deleted! expect { @user.deactivate! }.not_to raise_error end end context "when the user has active subscriptions" do let!(:subscription1) { create(:subscription, link: create(:membership_product), user: @user, free_trial_ends_at: 30.days.from_now) } let!(:subscription2) { create(:subscription, link: create(:membership_product), user: @user, free_trial_ends_at: 30.days.from_now) } it "cancels the active subscriptions" do expect do @user.deactivate! end.to change { @user.subscriptions.active_without_pending_cancel.count }.from(2).to(0) [subscription1, subscription2].each do |subscription| subscription.reload expect(subscription.cancelled_at).to be_present expect(subscription.cancelled_by_buyer).to be_truthy end end end end context "when user cannot be deactivated" do shared_examples "user is not deactivated" do before do allow(@user).to receive(:deactivate!).and_raise(User::UnpaidBalanceError).and_return(false) create(:subscription, link: create(:membership_product), user: @user, free_trial_ends_at: 30.days.from_now) end it "does not deactivate the user" do return_value = nil expect do return_value = @user.deactivate! end.to not_change { @user.reload.last_active_sessions_invalidated_at } .and not_change { @user.subscriptions.active_without_pending_cancel.count } @user.reload expect(return_value).to be_falsey expect(@user.read_attribute(:username)).to_not be_nil expect(@user.deleted_at).to be_nil expect(@product.reload.deleted_at).to be_nil expect(@installment.reload.deleted_at).to be_nil expect(@user.user_compliance_infos.reload.last.deleted_at).to be_nil
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/brunei_bank_account_spec.rb
spec/models/brunei_bank_account_spec.rb
# frozen_string_literal: true describe BruneiBankAccount do describe "#bank_account_type" do it "returns BN" do expect(create(:brunei_bank_account).bank_account_type).to eq("BN") end end describe "#country" do it "returns BN" do expect(create(:brunei_bank_account).country).to eq("BN") end end describe "#currency" do it "returns bnd" do expect(create(:brunei_bank_account).currency).to eq("bnd") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:brunei_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAABNBBXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:brunei_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(:brunei_bank_account)).to be_valid expect(build(:brunei_bank_account, account_number: "000012345")).to be_valid expect(build(:brunei_bank_account, account_number: "1")).to be_valid expect(build(:brunei_bank_account, account_number: "000012345678")).to be_valid bn_bank_account = build(:brunei_bank_account, account_number: "000012345678910") expect(bn_bank_account).to_not be_valid expect(bn_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") bn_bank_account = build(:brunei_bank_account, account_number: "BN0012345678910") expect(bn_bank_account).to_not be_valid expect(bn_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/community_spec.rb
spec/models/community_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Community do subject(:community) { build(:community) } describe "associations" do it { is_expected.to belong_to(:seller).class_name("User") } it { is_expected.to belong_to(:resource) } it { is_expected.to have_many(:community_chat_messages).dependent(:destroy) } it { is_expected.to have_many(:last_read_community_chat_messages).dependent(:destroy) } it { is_expected.to have_many(:community_chat_recaps).dependent(:destroy) } end describe "validations" do it { is_expected.to validate_uniqueness_of(:seller_id).scoped_to([:resource_id, :resource_type, :deleted_at]) } end describe "#name" do it "returns the resource name" do community = build(:community, resource: create(:product, name: "Test product")) expect(community.name).to eq("Test product") end end describe "#thumbnail_url" do it "returns the resource thumbnail url for email" do community = build(:community, resource: create(:product)) expect(community.thumbnail_url).to eq(ActionController::Base.helpers.asset_url("native_types/thumbnails/digital.png")) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/custom_field_spec.rb
spec/models/custom_field_spec.rb
# frozen_string_literal: true require "spec_helper" describe CustomField do describe "#as_json" do it "returns the correct data" do product = create(:product) field = create(:custom_field, products: [product]) expect(field.as_json).to eq({ id: field.external_id, type: field.type, name: field.name, required: field.required, global: field.global, collect_per_product: field.collect_per_product, products: [product.external_id], }) end end describe "validations" do it "validates that the field name is a valid URI for terms fields" do field = create(:custom_field, global: true) field.update(field_type: "terms") expect(field.errors.full_messages).to include("Please provide a valid URL for custom field of Terms type.") end it "disallows boolean fields for post-purchase custom fields" do field = build(:custom_field, is_post_purchase: true, field_type: CustomField::TYPE_CHECKBOX) expect(field).not_to be_valid expect(field.errors.full_messages).to include("Boolean post-purchase fields are not allowed") field.field_type = CustomField::TYPE_TERMS expect(field).not_to be_valid expect(field.errors.full_messages).to include("Boolean post-purchase fields are not allowed") field.field_type = CustomField::TYPE_TEXT expect(field).to be_valid end end describe "defaults" do it "sets the default name for file fields" do file_field = create(:custom_field, field_type: CustomField::TYPE_FILE, name: nil) expect(file_field.name).to eq(CustomField::FILE_FIELD_NAME) end it "raises an error when name is nil for non-file fields" do expect do create(:custom_field, field_type: CustomField::TYPE_TEXT, name: nil) end.to raise_error(ActiveRecord::RecordInvalid) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/preorder_link_spec.rb
spec/models/preorder_link_spec.rb
# frozen_string_literal: true require "spec_helper" describe PreorderLink do describe "#release!" do before do @product = create(:product_with_pdf_file, price_cents: 600, is_in_preorder_state: true) create(:rich_content, entity: @product, description: [{ "type" => "fileEmbed", "attrs" => { "id" => @product.product_files.first.external_id, "uid" => SecureRandom.uuid } }]) @preorder_link = create(:preorder_link, link: @product, release_at: 2.days.from_now) end it "does not allow the product to be released if the release date hasn't arrived yet" do expect(@preorder_link.release!).to be(false) expect(@preorder_link.reload.state).to eq "unreleased" end it "allows the product to be released if the release date is within a minute" do @preorder_link.update_attribute(:release_at, 30.seconds.from_now) expect(@preorder_link.release!).to be(true) expect(@preorder_link.reload.state).to eq "released" end it "does not allow the product to be released if the release date is not within a minute" do @preorder_link.update_attribute(:release_at, 70.seconds.from_now) expect(@preorder_link.release!).to be(false) expect(@preorder_link.reload.state).to eq "unreleased" end it "does not allow the product to be released if the product is banned" do @preorder_link.update_attribute(:release_at, Time.current) @preorder_link.link.update(banned_at: Time.current) expect(@preorder_link.release!).to be(false) expect(@preorder_link.reload.state).to eq "unreleased" end it "doesn't allow the product to be released if the product is unpublished" do @preorder_link.update_attribute(:release_at, Time.current) @preorder_link.link.update_column(:purchase_disabled_at, Time.current) expect(@preorder_link.release!).to be(false) expect(@preorder_link.reload.state).to eq "unreleased" end it "allows the unpublished product to be released if it's being released manually" do @preorder_link.update_attribute(:release_at, Time.current) @preorder_link.link.update_column(:purchase_disabled_at, Time.current) @preorder_link.is_being_manually_released_by_the_seller = true expect(@preorder_link.release!).to be(true) expect(@preorder_link.reload.state).to eq "released" end it "doesn't allow the product to be released if the product is deleted" do @preorder_link.update_attribute(:release_at, Time.current) @preorder_link.link.update_column(:deleted_at, Time.current) expect(@preorder_link.release!).to be(false) expect(@preorder_link.reload.state).to eq "unreleased" end it "allows the product to be released if the release date is in the future but it's being released by the seller" do @preorder_link.is_being_manually_released_by_the_seller = true expect(@preorder_link.release!).to be(true) expect(@preorder_link.reload.state).to eq "released" end describe "regular preorder" do it "does not allow the product to be released if the product does not have rich content" do @preorder_link.update_attribute(:release_at, Time.current) @product.alive_rich_contents.find_each(&:mark_deleted!) expect(@preorder_link.release!).to be(false) expect(@preorder_link.reload.state).to eq "unreleased" end end describe "physical preorder" do before do @product.update!(is_physical: true, require_shipping: true) @product.save_files!([]) end it "allows releasing the product even if it does not have any delivery content" do @preorder_link.update_attribute(:release_at, Time.current) expect(@preorder_link.release!).to be(true) expect(@preorder_link.reload.state).to eq "released" end end context "when purchasing a preorder twice with different version selections", :vcr do before do variant_category = create(:variant_category, link: @product) large_variant = create(:variant, variant_category:) create(:rich_content, entity: large_variant, description: [{ "type" => "fileEmbed", "attrs" => { "id" => @product.product_files.first.external_id, "uid" => SecureRandom.uuid } }]) small_variant = create(:variant, name: "Small", variant_category:) create(:rich_content, entity: small_variant, description: [{ "type" => "paragraph" }]) # Purchase the large variant auth_large_variant = build(:purchase, link: @product, chargeable: build(:chargeable), purchase_state: "in_progress", is_preorder_authorization: true, variant_attributes: [large_variant]) preorder = @preorder_link.build_preorder(auth_large_variant) preorder.authorize! expect(preorder.errors.full_messages).to be_empty preorder.mark_authorization_successful @email = auth_large_variant.email # Purchase the small variant auth_small_variant = build(:purchase, link: @product, chargeable: build(:chargeable), purchase_state: "in_progress", email: @email, is_preorder_authorization: true, variant_attributes: [small_variant]) preorder = @preorder_link.build_preorder(auth_small_variant) preorder.authorize! expect(preorder.errors.full_messages).to be_empty preorder.mark_authorization_successful end it "releases the preorder and charges both purchases", :sidekiq_inline do @preorder_link.is_being_manually_released_by_the_seller = true expect do expect(@preorder_link.release!).to be(true) end.to change { Purchase.successful.by_email(@email).count }.by(2) expect(@preorder_link.reload.state).to eq "released" end end it "marks the link as released" do @preorder_link.update_attribute(:release_at, Time.current) # bypass validation @preorder_link.release! expect(@preorder_link.reload.state).to eq "released" expect(@preorder_link.link.is_in_preorder_state?).to be(false) end it "adds the proper job to the queue when it comes time to charge the preorders" do @preorder_link.update_attribute(:release_at, Time.current) @preorder_link.release! expect(ChargeSuccessfulPreordersWorker).to have_enqueued_sidekiq_job(@preorder_link.id) end end describe "#revenue_cents" do before do @product = create(:product, price_cents: 600, is_in_preorder_state: false) @preorder_product = create(:preorder_product_with_content, link: @product) @preorder_product.update(release_at: Time.current) # bypassed the creation validation @good_card = build(:chargeable) @incorrect_cvc_card = build(:chargeable_decline) @good_card_but_cant_charge = build(:chargeable_success_charge_decline) end it "returns the correct revenue", :vcr do # first preorder fails to authorize authorization_purchase = build(:purchase, link: @product, chargeable: @incorrect_cvc_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_failed # second preorder authorizes and charges successfully authorization_purchase = build(:purchase, link: @product, chargeable: @good_card, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful preorder.charge! preorder.mark_charge_successful # third preorder authorizes successfully but the charge fails authorization_purchase = build(:purchase, link: @product, chargeable: @good_card_but_cant_charge, purchase_state: "in_progress", is_preorder_authorization: true) preorder = @preorder_product.build_preorder(authorization_purchase) preorder.authorize! preorder.mark_authorization_successful preorder.charge! expect(@preorder_product.revenue_cents).to eq 600 end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/imported_customer_spec.rb
spec/models/imported_customer_spec.rb
# frozen_string_literal: true require "spec_helper" describe ImportedCustomer do describe "validations" do it "requires an email to create an ImportedCustomer" do imported_customer_invalid = ImportedCustomer.new(email: nil) expect(imported_customer_invalid).to_not be_valid valid_customer = ImportedCustomer.new(email: "me@maxwell.com") expect(valid_customer).to be_valid end end describe "as_json" do it "includes imported customer details" do imported_customer = create(:imported_customer, link: create(:product)) result = imported_customer.as_json expect(result["email"]).to be_present expect(result["created_at"]).to be_present expect(result[:link_name]).to be_present expect(result[:product_name]).to be_present expect(result[:price]).to be_nil expect(result[:is_imported_customer]).to be true expect(result[:purchase_email]).to be_present expect(result[:id]).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/thailand_bank_account_spec.rb
spec/models/thailand_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe ThailandBankAccount do describe "#bank_account_type" do it "returns thailand" do expect(create(:thailand_bank_account).bank_account_type).to eq("TH") end end describe "#country" do it "returns TH" do expect(create(:thailand_bank_account).country).to eq("TH") end end describe "#currency" do it "returns thb" do expect(create(:thailand_bank_account).currency).to eq("thb") end end describe "#routing_number" do it "returns valid for 3 digits" do ba = create(:thailand_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("999") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:thailand_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(:thailand_bank_account, bank_code: "111")).to be_valid expect(build(:thailand_bank_account, bank_code: "999")).to be_valid expect(build(:thailand_bank_account, bank_code: "ABCD")).not_to be_valid expect(build(:thailand_bank_account, bank_code: "1234")).not_to be_valid end end describe "#validate_account_number" do it "allows records that match the required account number regex" do expect(build(:thailand_bank_account, account_number: "000123456789")).to be_valid expect(build(:thailand_bank_account, account_number: "123456789")).to be_valid expect(build(:thailand_bank_account, account_number: "123456789012345")).to be_valid th_bank_account = build(:thailand_bank_account, account_number: "ABCDEFGHIJKL") expect(th_bank_account).to_not be_valid expect(th_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") th_bank_account = build(:thailand_bank_account, account_number: "8937040044053201300000") expect(th_bank_account).to_not be_valid expect(th_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") th_bank_account = build(:thailand_bank_account, account_number: "12345") expect(th_bank_account).to_not be_valid expect(th_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/algeria_bank_account_spec.rb
spec/models/algeria_bank_account_spec.rb
# frozen_string_literal: true describe AlgeriaBankAccount do describe "#bank_account_type" do it "returns DZ" do expect(create(:algeria_bank_account).bank_account_type).to eq("DZ") end end describe "#country" do it "returns DZ" do expect(create(:algeria_bank_account).country).to eq("DZ") end end describe "#currency" do it "returns dzd" do expect(create(:algeria_bank_account).currency).to eq("dzd") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:algeria_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAADZDZXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:algeria_bank_account, account_number_last_four: "1234").account_number_visual).to eq("******1234") 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) # Valid account number (success case) expect(build(:algeria_bank_account)).to be_valid expect(build(:algeria_bank_account, account_number: "00001234567890123456")).to be_valid # Test error cases from Stripe docs expect(build(:algeria_bank_account, account_number: "00001001001111111116")).to be_valid # no_account expect(build(:algeria_bank_account, account_number: "00001001001111111113")).to be_valid # account_closed expect(build(:algeria_bank_account, account_number: "00001001002222222227")).to be_valid # insufficient_funds expect(build(:algeria_bank_account, account_number: "00001001003333333335")).to be_valid # debit_not_authorized expect(build(:algeria_bank_account, account_number: "00001001004444444440")).to be_valid # invalid_currency # Invalid format tests dz_bank_account = build(:algeria_bank_account, account_number: "12345") # too short expect(dz_bank_account).not_to be_valid expect(dz_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") dz_bank_account = build(:algeria_bank_account, account_number: "123456789012345678901") # too long expect(dz_bank_account).not_to be_valid expect(dz_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") dz_bank_account = build(:algeria_bank_account, account_number: "ABCD12345678901234XX") # contains letters expect(dz_bank_account).not_to be_valid expect(dz_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/turkey_bank_account_spec.rb
spec/models/turkey_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe TurkeyBankAccount do describe "#bank_account_type" do it "returns Turkey" do expect(create(:turkey_bank_account).bank_account_type).to eq("TR") end end describe "#country" do it "returns TR" do expect(create(:turkey_bank_account).country).to eq("TR") end end describe "#currency" do it "returns try" do expect(create(:turkey_bank_account).currency).to eq("try") end end describe "#routing_number" do it "returns valid for 8 characters" do ba = create(:turkey_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("ADABTRIS") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:turkey_bank_account, account_number_last_four: "1326").account_number_visual).to eq("******1326") end end describe "#validate_bank_code" do it "allows 8 to 11 characters only" do expect(build(:turkey_bank_account, bank_code: "ADABTRISXXX")).to be_valid expect(build(:turkey_bank_account, bank_code: "ADABTRIS")).to be_valid expect(build(:turkey_bank_account, bank_code: "ADABTRI")).not_to be_valid expect(build(:turkey_bank_account, bank_code: "ADABTRISXXXX")).not_to be_valid end end describe "#validate_account_number" do it "allows records that match the required account number regex" do allow(Rails.env).to receive(:production?).and_return(true) expect(build(:turkey_bank_account)).to be_valid expect(build(:turkey_bank_account, account_number: "TR320010009999901234567890")).to be_valid tr_bank_account = build(:turkey_bank_account, account_number: "TR12345") expect(tr_bank_account).to_not be_valid expect(tr_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") tr_bank_account = build(:turkey_bank_account, account_number: "TR3200100099999012345678901") expect(tr_bank_account).to_not be_valid expect(tr_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") tr_bank_account = build(:turkey_bank_account, account_number: "TR32001000999990123456789") expect(tr_bank_account).to_not be_valid expect(tr_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") tr_bank_account = build(:turkey_bank_account, account_number: "TRABCDE") expect(tr_bank_account).to_not be_valid expect(tr_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/bangladesh_bank_account_spec.rb
spec/models/bangladesh_bank_account_spec.rb
# frozen_string_literal: true describe BangladeshBankAccount do describe "#bank_account_type" do it "returns BD" do expect(create(:bangladesh_bank_account).bank_account_type).to eq("BD") end end describe "#country" do it "returns BD" do expect(create(:bangladesh_bank_account).country).to eq("BD") end end describe "#currency" do it "returns bdt" do expect(create(:bangladesh_bank_account).currency).to eq("bdt") end end describe "#routing_number" do it "returns valid for 9 characters" do ba = create(:bangladesh_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("110000000") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:bangladesh_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(:bangladesh_bank_account)).to be_valid expect(build(:bangladesh_bank_account, account_number: "0000123456789")).to be_valid expect(build(:bangladesh_bank_account, account_number: "00001234567891011")).to be_valid bd_bank_account = build(:bangladesh_bank_account, account_number: "000012345678") expect(bd_bank_account).to_not be_valid expect(bd_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") bd_bank_account = build(:bangladesh_bank_account, account_number: "0000123456789101112") expect(bd_bank_account).to_not be_valid expect(bd_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") bd_bank_account = build(:bangladesh_bank_account, account_number: "BD00123456789101112") expect(bd_bank_account).to_not be_valid expect(bd_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") bd_bank_account = build(:bangladesh_bank_account, account_number: "BDABC") expect(bd_bank_account).to_not be_valid expect(bd_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/macao_bank_account_spec.rb
spec/models/macao_bank_account_spec.rb
# frozen_string_literal: true describe MacaoBankAccount do describe "#bank_account_type" do it "returns MO" do expect(create(:macao_bank_account).bank_account_type).to eq("MO") end end describe "#country" do it "returns MO" do expect(create(:macao_bank_account).country).to eq("MO") end end describe "#currency" do it "returns MOP" do expect(create(:macao_bank_account).currency).to eq("mop") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:macao_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAAMOMXXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:macao_bank_account, account_number_last_four: "7897").account_number_visual).to eq("******7897") end end describe "#validate_account_number" do it "allows records that match the required account number regex" do expect(build(:macao_bank_account)).to be_valid expect(build(:macao_bank_account, account_number: "0000000001234567897")).to be_valid expect(build(:macao_bank_account, account_number: "0")).to be_valid expect(build(:macao_bank_account, account_number: "0000123456789101")).to be_valid mo_bank_account = build(:macao_bank_account, account_number: "00001234567891234567890") expect(mo_bank_account).not_to be_valid expect(mo_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") end end describe "#validate_bank_code" do it "validates bank code format" do expect(build(:macao_bank_account, bank_code: "AAAAMOMXXXX")).to be_valid expect(build(:macao_bank_account, bank_code: "BBBBMOMBXXX")).to be_valid mo_bank_account = build(:macao_bank_account, bank_code: "INVALIDCODEE") expect(mo_bank_account).not_to be_valid expect(mo_bank_account.errors.full_messages.to_sentence).to eq("The bank code 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/ghana_bank_account_spec.rb
spec/models/ghana_bank_account_spec.rb
# frozen_string_literal: true describe GhanaBankAccount do describe "#bank_account_type" do it "returns GH" do expect(create(:ghana_bank_account).bank_account_type).to eq("GH") end end describe "#country" do it "returns GH" do expect(create(:ghana_bank_account).country).to eq("GH") end end describe "#currency" do it "returns ghs" do expect(create(:ghana_bank_account).currency).to eq("ghs") end end describe "#routing_number" do it "returns valid for 6 digits" do expect(create(:ghana_bank_account, bank_code: "022112")).to be_valid end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:ghana_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(:ghana_bank_account)).to be_valid expect(build(:ghana_bank_account, account_number: "00012345678")).to be_valid expect(build(:ghana_bank_account, account_number: "000123456789")).to be_valid expect(build(:ghana_bank_account, account_number: "00012345678912345678")).to be_valid gh_bank_account = build(:ghana_bank_account, account_number: "1234567") expect(gh_bank_account).not_to be_valid expect(gh_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") gh_bank_account = build(:ghana_bank_account, account_number: "000123456789123456789") expect(gh_bank_account).not_to be_valid expect(gh_bank_account.errors.full_messages.to_sentence).to eq("The account number is invalid.") gh_bank_account = build(:ghana_bank_account, account_number: "ABCD12345678") expect(gh_bank_account).not_to be_valid expect(gh_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/panama_bank_account_spec.rb
spec/models/panama_bank_account_spec.rb
# frozen_string_literal: true require "spec_helper" describe PanamaBankAccount do describe "#bank_account_type" do it "returns PA" do expect(create(:panama_bank_account).bank_account_type).to eq("PA") end end describe "#country" do it "returns PA" do expect(create(:panama_bank_account).country).to eq("PA") end end describe "#currency" do it "returns usd" do expect(create(:panama_bank_account).currency).to eq("usd") end end describe "#routing_number" do it "returns valid for 11 characters" do ba = create(:panama_bank_account) expect(ba).to be_valid expect(ba.routing_number).to eq("AAAAPAPAXXX") end end describe "#account_number_visual" do it "returns the visual account number" do expect(create(:panama_bank_account, account_number_last_four: "6789").account_number_visual).to eq("******6789") end end describe "#validate_bank_code" do it "allows 11 characters only" do expect(build(:panama_bank_account, bank_number: "AAAAPAPAXXX")).to be_valid expect(build(:panama_bank_account, bank_number: "AAAAPAPAXX")).not_to be_valid expect(build(:panama_bank_account, bank_number: "AAAAPAPAXXXX")).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/concerns/attribute_blockable_spec.rb
spec/models/concerns/attribute_blockable_spec.rb
# frozen_string_literal: true require "spec_helper" describe AttributeBlockable do let(:blocked_email) { "blocked@example.com" } let(:unblocked_email) { "unblocked@example.com" } let(:user_with_blocked_email) { create(:user, email: blocked_email) } let(:user_with_unblocked_email) { create(:user, email: unblocked_email) } before do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], blocked_email, 1) end after do BlockedObject.delete_all end describe ".attr_blockable" do it "defines blocked? methods for the specified attribute" do expect(user_with_blocked_email).to respond_to(:blocked_by_email?) expect(user_with_blocked_email).to respond_to(:blocked_by_email_object) end it "defines blocked? methods for custom method names" do expect(user_with_blocked_email).to respond_to(:blocked_by_form_email?) expect(user_with_blocked_email).to respond_to(:blocked_by_form_email_object) end it "defines block and unblock methods" do expect(user_with_blocked_email).to respond_to(:block_by_email!) expect(user_with_blocked_email).to respond_to(:unblock_by_email!) end describe "generated instance methods" do describe "#blocked_by_email?" do it "returns true for blocked emails" do expect(user_with_blocked_email.blocked_by_email?).to be true end it "returns false for unblocked emails" do expect(user_with_unblocked_email.blocked_by_email?).to be false end it "returns false for blank email" do user = create(:user) user.update_column(:email, "") expect(user.blocked_by_email?).to be false end end describe "#blocked_by_email_object" do it "returns blocked object with blocked_at timestamp for blocked emails" do blocked_object = user_with_blocked_email.blocked_by_email_object expect(blocked_object).to be_a(BlockedObject) expect(blocked_object.blocked_at).to be_a(DateTime) expect(blocked_object.blocked_at.to_time).to be_within(1.minute).of(Time.current) end it "returns nil for unblocked emails" do expect(user_with_unblocked_email.blocked_by_email_object).to be_nil end it "caches the result in blocked_by_attributes" do user_with_blocked_email.blocked_by_email_object expect(user_with_blocked_email.blocked_by_attributes["email"]).not_to be_nil end it "uses cached value on subsequent calls" do first_result = user_with_blocked_email.blocked_by_email_object blocked_object = BlockedObject.find_by(object_value: blocked_email) blocked_object.update!(blocked_at: 1.year.ago) second_result = user_with_blocked_email.blocked_by_email_object expect(second_result.blocked_at).to eq(first_result.blocked_at) end end describe "#blocked_by_form_email?" do it "uses the email attribute for blocking checks" do expect(user_with_blocked_email.blocked_by_form_email?).to be true expect(user_with_unblocked_email.blocked_by_form_email?).to be false end it "does not consider unblocked records" do user = create(:user, email: "test_unblocked_#{SecureRandom.hex(4)}@example.com") blocked_object = BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], user.email, 1) expect(user.reload.blocked_by_form_email?).to be true expect(user.blocked_by_form_email_object).not_to be_nil blocked_object.unblock! expect(user.reload.blocked_by_form_email?).to be false expect(user.blocked_by_form_email_object).to be_nil end it "finds active block after unblocking and reblocking" do user = create(:user, email: "test_reblock_#{SecureRandom.hex(4)}@example.com") first_block = BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], user.email, 1) expect(user.reload.blocked_by_form_email?).to be true first_block.unblock! expect(user.reload.blocked_by_form_email?).to be false expect(user.blocked_by_form_email_object).to be_nil second_block = BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], user.email, 1) expect(first_block.id).to eq(second_block.id) expect(user.reload.blocked_by_form_email?).to be true expect(user.blocked_by_form_email_object.id).to eq(first_block.id) expect(user.blocked_by_form_email_object.blocked_at).not_to be_nil end end describe "#block_by_email!" do it "blocks the user by their email" do user = create(:user, email: "test@example.com") expect(user.blocked_by_email?).to be false user.block_by_email! expect(user.blocked_by_email?).to be true end it "accepts expires_in parameter" do user = create(:user, email: "test@example.com") user.block_by_email!(expires_in: 1.hour) expect(user.blocked_by_email?).to be true expect(BlockedObject.last.expires_at.to_time).to be_within(1.minute).of(1.hour.from_now) end it "accepts by_user_id parameter" do user = create(:user, email: "userid@example.com") user.block_by_email!(by_user_id: 123) expect(user.blocked_by_email?).to be true expect(BlockedObject.last.blocked_by).to eq(123) end it "accepts both by_user_id and expires_in parameters" do user = create(:user, email: "both@example.com") user.block_by_email!(by_user_id: 456, expires_in: 2.hours) expect(user.blocked_by_email?).to be true blocked_object = BlockedObject.last expect(blocked_object.blocked_by).to eq(456) expect(blocked_object.expires_at.to_time).to be_within(1.minute).of(2.hours.from_now) end it "does nothing when email is blank" do user = create(:user) user.update_column(:email, "") expect { user.block_by_email! }.not_to change { BlockedObject.count } end it "does nothing when email is nil" do user = create(:user) user.update_column(:email, nil) expect { user.block_by_email! }.not_to change { BlockedObject.count } end it "updates cache with correct blockable_method key" do user = create(:user, email: "cache_key_test@example.com") user.block_by_email! # Cache should be keyed by "email" (the blockable_method) expect(user.blocked_by_attributes["email"]).to be_a(BlockedObject) expect(user.blocked_by_attributes["email"].object_value).to eq("cache_key_test@example.com") end it "immediately reflects blocked status via cache" do user = create(:user, email: "immediate_cache@example.com") user.block_by_email! # Should not need to query database again expect(user.blocked_by_email?).to be true expect(user.blocked_by_attributes["email"]).to be_a(BlockedObject) end end describe "#unblock_by_email!" do it "unblocks the user by their email" do user = create(:user, email: "blocked_test@example.com") user.block_by_email! expect(user.blocked_by_email?).to be true user.unblock_by_email! user.reload expect(user.blocked_by_email?).to be false end it "does nothing when email is blank" do user = create(:user) user.update_column(:email, "") expect { user.unblock_by_email! }.not_to raise_error end it "does nothing when email is nil" do user = create(:user) user.update_column(:email, nil) expect { user.unblock_by_email! }.not_to raise_error end it "clears cached blocked_by_attributes when unblocking" do user = create(:user, email: "cached_test@example.com") user.block_by_email! user.blocked_by_email? # Populate cache expect(user.blocked_by_attributes["email"]).to be_a(BlockedObject) user.unblock_by_email! expect(user.blocked_by_attributes["email"]).to be_nil end end describe "cache management with custom method names" do describe "#block_by_form_email!" do it "updates cache with blockable_method key, not object_type key" do user = create(:user, email: "cache_test@example.com") user.block_by_form_email! expect(user.blocked_by_attributes["form_email"]).to be_a(BlockedObject) expect(user.blocked_by_attributes["email"]).to be_nil end it "correctly identifies blocked status after blocking" do user = create(:user, email: "form_block_test@example.com") user.block_by_form_email! expect(user.blocked_by_form_email?).to be true expect(user.blocked_by_email?).to be true end it "maintains separate cache entries for email and form_email" do user = create(:user, email: "separate_cache@example.com") user.block_by_form_email! user.blocked_by_email? # Populate the "email" cache key expect(user.blocked_by_attributes["form_email"]).to be_a(BlockedObject) expect(user.blocked_by_attributes["email"]).to be_a(BlockedObject) expect(user.blocked_by_attributes.keys).to include("form_email", "email") end end describe "#unblock_by_form_email!" do it "clears cache using blockable_method key, not object_type key" do user = create(:user, email: "cache_unblock_test@example.com") user.block_by_form_email! expect(user.blocked_by_attributes["form_email"]).to be_a(BlockedObject) user.unblock_by_form_email! expect(user.blocked_by_attributes["form_email"]).to be_nil end it "correctly updates blocked status after unblocking" do user = create(:user, email: "form_unblock_test@example.com") user.block_by_form_email! expect(user.blocked_by_form_email?).to be true user.unblock_by_form_email! user.reload expect(user.blocked_by_form_email?).to be false expect(user.blocked_by_email?).to be false end it "handles mixed cache state correctly" do user = create(:user, email: "mixed_cache@example.com") user.block_by_form_email! user.blocked_by_email? # Populate cache entry expect(user.blocked_by_attributes["form_email"]).to be_a(BlockedObject) expect(user.blocked_by_attributes["email"]).to be_a(BlockedObject) user.unblock_by_form_email! expect(user.blocked_by_attributes["form_email"]).to be_nil # The "email" cache still has a stale reference - reload is needed to get fresh data user.reload expect(user.blocked_by_email?).to be false end end describe "cache key consistency" do it "uses consistent cache keys across all operations" do user = create(:user, email: "consistency_test@example.com") user.block_by_form_email! expect(user.blocked_by_attributes.keys).to include("form_email") user.blocked_by_form_email? expect(user.blocked_by_attributes.keys).to include("form_email") user.unblock_by_form_email! expect(user.blocked_by_attributes["form_email"]).to be_nil end it "does not pollute cache with object_type keys" do user = create(:user, email: "no_pollution@example.com") user.block_by_form_email! expect(user.blocked_by_attributes.keys).not_to include("email") expect(user.blocked_by_attributes.keys).to include("form_email") end end end describe "cache management with email_domain methods" do describe "#block_by_form_email_domain!" do it "updates cache with blockable_method key" do user = create(:user, email: "test@domain.com") user.block_by_form_email_domain! # Cache should be keyed by "form_email_domain", not "email_domain" expect(user.blocked_by_attributes["form_email_domain"]).to be_a(BlockedObject) expect(user.blocked_by_attributes["email_domain"]).to be_nil end it "correctly identifies blocked status" do user = create(:user, email: "test@blocked-domain.com") user.block_by_form_email_domain! expect(user.blocked_by_form_email_domain?).to be true # form_email_domain blocks the actual domain value expect(BlockedObject.find_by(object_value: "blocked-domain.com")).to be_present end it "maintains independent cache from email methods" do user = create(:user, email: "test@multi-block.com") user.block_by_form_email_domain! expect(user.blocked_by_attributes["form_email_domain"]).to be_a(BlockedObject) expect(user.blocked_by_attributes["form_email"]).to be_nil end end describe "#unblock_by_form_email_domain!" do it "clears cache using correct blockable_method key" do user = create(:user, email: "test@unblock-domain.com") user.block_by_form_email_domain! expect(user.blocked_by_attributes["form_email_domain"]).to be_a(BlockedObject) user.unblock_by_form_email_domain! expect(user.blocked_by_attributes["form_email_domain"]).to be_nil end it "correctly updates blocked status" do user = create(:user, email: "test@unblock-test.com") user.block_by_form_email_domain! expect(user.blocked_by_form_email_domain?).to be true user.unblock_by_form_email_domain! user.reload expect(user.blocked_by_form_email_domain?).to be false end end end end end describe "blockable attribute introspection" do describe ".blockable_attributes" do it "returns an array of attribute configurations" do expect(User.blockable_attributes).to be_an(Array) expect(User.blockable_attributes).not_to be_empty end it "includes configuration for each attr_blockable declaration" do # User has: attr_blockable :email, :form_email (object_type: :email), # :email_domain, :form_email_domain (object_type: :email_domain), # :account_created_ip (object_type: :ip_address) expect(User.blockable_attributes).to include( { object_type: :email, blockable_method: :email } ) expect(User.blockable_attributes).to include( { object_type: :email, blockable_method: :form_email } ) expect(User.blockable_attributes).to include( { object_type: :email_domain, blockable_method: :email_domain } ) expect(User.blockable_attributes).to include( { object_type: :email_domain, blockable_method: :form_email_domain } ) expect(User.blockable_attributes).to include( { object_type: :ip_address, blockable_method: :account_created_ip } ) end it "tracks custom attribute mappings correctly" do # form_email uses :email as the object_type form_email_config = User.blockable_attributes.find do |attr| attr[:blockable_method] == :form_email end expect(form_email_config).to eq({ object_type: :email, blockable_method: :form_email }) end it "returns unique entries per model class" do # Create a custom test model with its own blockable attributes test_model_class = Class.new(ApplicationRecord) do self.table_name = "users" include AttributeBlockable attr_blockable :test_attribute def self.name "TestIntrospectionModel" end end expect(test_model_class.blockable_attributes).to include( { object_type: :test_attribute, blockable_method: :test_attribute } ) # User's attributes shouldn't include the test model's attributes expect(User.blockable_attributes).not_to include( { object_type: :test_attribute, blockable_method: :test_attribute } ) end end describe ".blockable_method_names" do it "returns an array of blockable method names" do expect(User.blockable_method_names).to be_an(Array) expect(User.blockable_method_names).to all(be_a(Symbol)) end it "includes all blockable method names defined on the model" do expect(User.blockable_method_names).to include(:email) expect(User.blockable_method_names).to include(:form_email) expect(User.blockable_method_names).to include(:email_domain) expect(User.blockable_method_names).to include(:form_email_domain) expect(User.blockable_method_names).to include(:account_created_ip) end it "returns only method names without object_type info" do expect(User.blockable_method_names).to eq([:email, :form_email, :email_domain, :form_email_domain, :account_created_ip]) end end describe ".with_all_blocked_attributes" do let!(:users) { 3.times.map { |i| create(:user, email: "unblocked#{i}@example.com") } } let!(:blocked_user) { create(:user, email: blocked_email) } it "returns an ActiveRecord::Relation" do result = User.with_all_blocked_attributes expect(result).to be_a(ActiveRecord::Relation) end it "preloads all blockable attributes" do users_with_preload = User.with_all_blocked_attributes.to_a users_with_preload.each do |user| # Check that the cache has been populated for all blockable methods if user.email == blocked_email expect(user.blocked_by_attributes["email"]).to be_a(BlockedObject) else expect(user.blocked_by_attributes["email"]).to be_nil end # The cache should have entries for all blockable methods expect(user.blocked_by_attributes).to have_key("form_email") expect(user.blocked_by_attributes).to have_key("email_domain") expect(user.blocked_by_attributes).to have_key("form_email_domain") expect(user.blocked_by_attributes).to have_key("account_created_ip") end end it "maintains chainability" do result = User.with_all_blocked_attributes.where(id: users.map(&:id)) expect(result).to be_a(ActiveRecord::Relation) expect(result.to_a.size).to eq(3) end it "correctly identifies blocked users" do all_users = User.with_all_blocked_attributes blocked_users = all_users.select(&:blocked_by_email?) unblocked_users = all_users.reject(&:blocked_by_email?) expect(blocked_users.map(&:email)).to include(blocked_email) expect(unblocked_users.map(&:email)).not_to include(blocked_email) end end end describe ".with_blocked_attributes_for" do let!(:users) { 3.times.map { |i| create(:user, email: "unblocked#{i}@example.com") } } let!(:blocked_user) { create(:user, email: blocked_email) } it "returns an ActiveRecord::Relation" do result = User.with_blocked_attributes_for(:email) expect(result).to be_a(ActiveRecord::Relation) end it "maintains chainability" do result = User.with_blocked_attributes_for(:email).where(id: users.map(&:id)) expect(result).to be_a(ActiveRecord::Relation) expect(result.to_a.size).to eq(3) end it "can chain additional scopes" do result = User.with_blocked_attributes_for(:email) .where(email: blocked_email) .limit(1) expect(result).to be_a(ActiveRecord::Relation) expect(result.first).to eq(blocked_user) end it "accepts multiple method names" do result = User.with_blocked_attributes_for(:email, :form_email) expect(result).to be_a(ActiveRecord::Relation) end describe "bulk loading blocked attributes" do it "correctly identifies blocked and unblocked records" do all_users = User.with_blocked_attributes_for(:email) blocked_users = all_users.select(&:blocked_by_email?) unblocked_users = all_users.reject(&:blocked_by_email?) expect(blocked_users.map(&:email)).to include(blocked_email) expect(unblocked_users.map(&:email)).not_to include(blocked_email) end it "populates blocked_by_attributes for all records" do users_with_preload = User.with_blocked_attributes_for(:email).to_a users_with_preload.each do |user| if user.email == blocked_email expect(user.blocked_by_attributes["email"]).to be_a(BlockedObject) else expect(user.blocked_by_attributes["email"]).to be_nil end end end it "handles mixed blocked and unblocked records" do mixed_blocked_email = "mixed_blocked@example.com" mixed_emails = [mixed_blocked_email, "unique_unblocked@example.com", "another@example.com"] BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], mixed_blocked_email, 1) BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], "another@example.com", 1) mixed_users = mixed_emails.map { |email| create(:user, email:) } result = User.where(id: mixed_users.map(&:id)).with_blocked_attributes_for(:email) blocked_users = result.select(&:blocked_by_email?) expect(blocked_users.map(&:email)).to eq([mixed_blocked_email, "another@example.com"]) end it "works with custom method names that map to different object types" do custom_blocked_email = "custom_blocked@example.com" custom_unblocked_email = "custom_unblocked@example.com" BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], custom_blocked_email, 1) test_users = [ create(:user, email: custom_blocked_email), create(:user, email: custom_unblocked_email) ] result_users = User.where(id: test_users.map(&:id)).with_blocked_attributes_for(:form_email) blocked_users = result_users.select(&:blocked_by_form_email?) unblocked_users = result_users.reject(&:blocked_by_form_email?) expect(blocked_users.map(&:email)).to eq([custom_blocked_email]) expect(unblocked_users.map(&:email)).to eq([custom_unblocked_email]) result_users.each do |user| if user.email == custom_blocked_email expect(user.blocked_by_attributes["form_email"]).to be_a(BlockedObject) else expect(user.blocked_by_attributes["form_email"]).to be_nil end end end it "uses the correct BlockedObject scope for custom method names" do custom_blocked_email_1 = "scope_test1@example.com" custom_blocked_email_2 = "scope_test2@example.com" custom_blocked_email_domain = "example.com" test_users = [ create(:user, email: custom_blocked_email_1), create(:user, email: custom_blocked_email_2) ] BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], custom_blocked_email_1, 1) BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], custom_blocked_email_2, 1) BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], custom_blocked_email_domain, 1) allow(BlockedObject).to receive(:find_active_objects).and_call_original User.where(id: test_users.map(&:id)).with_blocked_attributes_for(:form_email, :email_domain).to_a expect(BlockedObject).to have_received(:find_active_objects).with([custom_blocked_email_1, custom_blocked_email_2]).once expect(BlockedObject).to have_received(:find_active_objects).with([custom_blocked_email_domain]).once end end describe "performance" do it "makes only one MongoDB query when loading blocked attributes for multiple blocked users" do perf_users = [] 5.times do |i| email = "blocked_perfuser#{i}@example.com" perf_users << create(:user, email:) BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], email, 1) end allow(BlockedObject).to receive(:find_active_objects).and_call_original result = User.where(id: perf_users.map(&:id)).with_blocked_attributes_for(:email) expect(result.size).to eq(5) result.each do |user| expect(user.blocked_by_attributes["email"]).to be_a(BlockedObject) expect(user.blocked_by_email?).to be true end expect(BlockedObject).to have_received(:find_active_objects).once end it "handles empty result sets gracefully" do result = User.where(id: -1).with_blocked_attributes_for(:email) expect(result).to be_empty end it "handles records with nil values" do user_with_nil_email = create(:user) user_with_nil_email.update_column(:email, nil) result = User.with_blocked_attributes_for(:email).find_by(id: user_with_nil_email.id) expect(result.blocked_by_email?).to be false expect(result.blocked_by_email_object).to be_nil end it "only preloads active blocks, ignoring unblocked records" do # Create users with active and unblocked records active_email = "preload_active_#{SecureRandom.hex(4)}@example.com" unblocked_email = "preload_unblocked_#{SecureRandom.hex(4)}@example.com" reblocked_email = "preload_reblocked_#{SecureRandom.hex(4)}@example.com" user_active = create(:user, email: active_email) user_unblocked = create(:user, email: unblocked_email) user_reblocked = create(:user, email: reblocked_email) # Create active block active_record = BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], active_email, 1) # Create unblocked record (blocked_at is nil) unblocked_record = BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], unblocked_email, 1) unblocked_record.unblock! # Create unblocked record, then block the same email again # find_or_initialize_by ensures it's the same record, just re-blocked BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], reblocked_email, 1) BlockedObject.send(:email).find_by(object_value: reblocked_email).unblock! reblocked_record = BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], reblocked_email, 1) # Preload blocked attributes users = User.where(id: [user_active.id, user_unblocked.id, user_reblocked.id]) .with_blocked_attributes_for(:email) .to_a # Verify results active_user = users.find { |u| u.id == user_active.id } unblocked_user = users.find { |u| u.id == user_unblocked.id } reblocked_user = users.find { |u| u.id == user_reblocked.id } expect(active_user.blocked_by_email?).to be true expect(active_user.blocked_by_email_object.id).to eq(active_record.id) expect(unblocked_user.blocked_by_email?).to be false expect(unblocked_user.blocked_by_email_object).to be_nil expect(reblocked_user.blocked_by_email?).to be true expect(reblocked_user.blocked_by_email_object.id).to eq(reblocked_record.id) expect(reblocked_user.blocked_by_email_object.blocked_at).not_to be_nil end end end describe "different blocked object types" do let(:blocked_ip) { "192.168.1.100" } let(:unblocked_ip) { "192.168.1.200" } before do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], blocked_ip, 1, expires_in: 1.hour) end let(:test_model_class) do Class.new(ApplicationRecord) do self.table_name = "users" include AttributeBlockable attr_blockable :current_sign_in_ip, object_type: :ip_address def self.name "TestModel" end end end it "works with different BLOCKED_OBJECT_TYPES" do model = test_model_class.new(current_sign_in_ip: blocked_ip) expect(model.blocked_by_current_sign_in_ip?).to be true model2 = test_model_class.new(current_sign_in_ip: unblocked_ip) expect(model2.blocked_by_current_sign_in_ip?).to be false end end describe "edge cases and error handling" do it "raises an error for missing BLOCKED_OBJECT_TYPES" do user = create(:user, username: "testuser") expect do user.blocked_at_by_method(:username) end.to raise_error(NoMethodError) end it "handles expired blocked objects" do expired_email = "expired@example.com" BlockedObject.create!( object_type: BLOCKED_OBJECT_TYPES[:email], object_value: expired_email, blocked_at: 1.hour.ago, expires_at: 30.minutes.ago, blocked_by: 1 ) user = create(:user, email: expired_email) # Expired blocks are treated the same as unblocked - no object returned expect(user.blocked_by_email?).to be false expect(user.blocked_by_email_object).to be_nil end it "handles blocked objects without expires_at" do permanent_blocked_email = "permanent@example.com" BlockedObject.create!( object_type: BLOCKED_OBJECT_TYPES[:email], object_value: permanent_blocked_email, blocked_at: 1.hour.ago, expires_at: nil, blocked_by: 1 ) user = create(:user, email: permanent_blocked_email) expect(user.blocked_by_email?).to be true expect(user.blocked_by_email_object&.expires_at).to be_nil end end describe "integration with blocked_by_attributes" do it "initializes with empty hash" do user = User.new expect(user.blocked_by_attributes).to eq({}) end it "persists cached blocked attributes" do user = create(:user, email: blocked_email) expect(user.blocked_by_attributes["email"]).to be_nil user.blocked_by_email? # Populate cache expect(user.blocked_by_attributes["email"]).to be_a(BlockedObject) user.reload # Clear cache expect(user.blocked_by_attributes["email"]).to be_nil expect(user.blocked_by_email?).to be true end end describe "#blocked_objects_for_values" do let(:user) { create(:user, email: "test@example.com") } it "returns blocked objects for given values" do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], "blocked1@example.com", 1) BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], "blocked2@example.com", 1) values = ["blocked1@example.com", "blocked2@example.com", "unblocked@example.com"] blocked_objects = user.blocked_objects_for_values(:email, values) expect(blocked_objects.count).to eq(2) expect(blocked_objects.map(&:object_value)).to contain_exactly("blocked1@example.com", "blocked2@example.com") end it "returns empty collection when no values are blocked" do values = ["unblocked1@example.com", "unblocked2@example.com"] blocked_objects = user.blocked_objects_for_values(:email, values) expect(blocked_objects).to be_empty end it "works with different object types" do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], "192.168.1.1", 1, expires_in: 1.hour) values = ["192.168.1.1", "192.168.1.2"] blocked_objects = user.blocked_objects_for_values(:ip_address, values) expect(blocked_objects.count).to eq(1) expect(blocked_objects.first.object_value).to eq("192.168.1.1") expect(blocked_objects.first.ip_address?).to be true end it "handles empty values array" do blocked_objects = user.blocked_objects_for_values(:email, []) expect(blocked_objects).to be_empty end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/unused_columns_spec.rb
spec/models/concerns/unused_columns_spec.rb
# frozen_string_literal: true require "spec_helper" ActiveRecord::Schema.define do create_table :test_models, temporary: true, force: true do |t| t.string :name t.string :email t.string :description end end describe UnusedColumns do class TestModel < ActiveRecord::Base include UnusedColumns unused_columns :description end let(:record) do TestModel.new end it "raises NoMethodError when reading a value from an unused column" do expect { record.description }.to raise_error( NoMethodError ).with_message("Column description is deprecated and no longer used.") end it "raises NoMethodError when assigning a value to a unused column" do expect { record.description = "some value" }.to raise_error( NoMethodError ).with_message("Column description is deprecated and no longer used.") end it "returns unused attributes" do expect(TestModel.unused_attributes).to eq(["description"]) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/charge_processable_spec.rb
spec/models/concerns/charge_processable_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe ChargeProcessable do let(:test_class) do Class.new do include ChargeProcessable attr_accessor :charge_processor_id def initialize(charge_processor_id) @charge_processor_id = charge_processor_id end end end describe "#stripe_charge_processor?" do context "when charge_processor_id is stripe" do subject { test_class.new(StripeChargeProcessor.charge_processor_id) } it "returns true" do expect(subject.stripe_charge_processor?).to be true end end context "when charge_processor_id is not stripe" do subject { test_class.new(PaypalChargeProcessor.charge_processor_id) } it "returns false" do expect(subject.stripe_charge_processor?).to be false end end context "when charge_processor_id is nil" do subject { test_class.new(nil) } it "returns false" do expect(subject.stripe_charge_processor?).to be false end end end describe "#paypal_charge_processor?" do context "when charge_processor_id is paypal" do subject { test_class.new(PaypalChargeProcessor.charge_processor_id) } it "returns true" do expect(subject.paypal_charge_processor?).to be true end end context "when charge_processor_id is not paypal" do subject { test_class.new(StripeChargeProcessor.charge_processor_id) } it "returns false" do expect(subject.paypal_charge_processor?).to be false end end context "when charge_processor_id is nil" do subject { test_class.new(nil) } it "returns false" do expect(subject.paypal_charge_processor?).to be false end end end describe "#braintree_charge_processor?" do context "when charge_processor_id is braintree" do subject { test_class.new(BraintreeChargeProcessor.charge_processor_id) } it "returns true" do expect(subject.braintree_charge_processor?).to be true end end context "when charge_processor_id is not braintree" do subject { test_class.new(StripeChargeProcessor.charge_processor_id) } it "returns false" do expect(subject.braintree_charge_processor?).to be false end end context "when charge_processor_id is nil" do subject { test_class.new(nil) } it "returns false" do expect(subject.braintree_charge_processor?).to be false end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/rich_contents_spec.rb
spec/models/concerns/rich_contents_spec.rb
# frozen_string_literal: true require "spec_helper" describe RichContents do let(:description) { [{ "type" => "paragraph", "content" => [{ "text" => Faker::Lorem.unique.sentence, "type" => "text" }] }] } context "for a product" do let(:product) { create(:product) } describe "#rich_content_json" do context "when product has rich content" do let!(:rich_content1) { create(:rich_content, entity: product, description:, title: "Page 1", position: 3) } let!(:rich_content2) { create(:rich_content, entity: product, description:, title: "Deleted page 2", deleted_at: 1.day.ago, position: 0) } let!(:rich_content3) { create(:rich_content, entity: product, description:, title: "Page 3", position: 1) } let!(:another_product_rich_content) { create(:rich_content, description:, title: "Another product's page", position: 2) } it "returns the product-level alive rich contents in order" do expect(product.rich_content_json).to eq([ { id: rich_content3.external_id, page_id: rich_content3.external_id, variant_id: nil, title: "Page 3", description: { type: "doc", content: rich_content3.description }, updated_at: rich_content3.updated_at }, { id: rich_content1.external_id, page_id: rich_content1.external_id, variant_id: nil, title: "Page 1", description: { type: "doc", content: rich_content1.description }, updated_at: rich_content1.updated_at } ]) end context "when `has_same_rich_content_for_all_variants` is true" do before do product.update!(has_same_rich_content_for_all_variants: true) end it "returns the product-level alive rich contents" do expect(product.rich_content_json).to eq([ { id: rich_content3.external_id, page_id: rich_content3.external_id, variant_id: nil, title: "Page 3", description: { type: "doc", content: rich_content3.description }, updated_at: rich_content3.updated_at }, { id: rich_content1.external_id, page_id: rich_content1.external_id, variant_id: nil, title: "Page 1", description: { type: "doc", content: rich_content1.description }, updated_at: rich_content1.updated_at } ]) end end end context "when product does not have rich content" do it "returns empty array" do expect(product.rich_content_json).to eq([]) end end end describe "#rich_content_folder_name" do it "returns the folder name when the corresponding folder exists in the rich content" do file1 = create(:product_file, display_name: "File 1") file2 = create(:product_file, display_name: "File 2") file3 = create(:product_file, display_name: "File 3") file4 = create(:product_file, display_name: "File 4") file5 = create(:product_file, display_name: "File 5") product.product_files = [file1, file2, file3, file4, file5] folder1_id = SecureRandom.uuid folder2_id = SecureRandom.uuid create(:rich_content, entity: product, title: "Page 1", description: [], position: 0) expect(product.rich_content_folder_name(folder1_id)).to eq (nil) expect(product.rich_content_folder_name(folder2_id)).to eq (nil) page2_description = [ { "type" => "fileEmbedGroup", "attrs" => { "name" => "folder 1", "uid" => folder1_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid } }, ] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Ignore me" }] }] page3_description = [ { "type" => "fileEmbedGroup", # Ensure folders with numeric names are handled as strings "attrs" => { "name" => 100, "uid" => folder2_id }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file3.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file4.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => file5.external_id, "uid" => SecureRandom.uuid } }, ] } ] create(:rich_content, entity: product, title: "Page 2", description: page2_description, position: 1) create(:rich_content, entity: product, title: "Page 3", description: page3_description, position: 2) expect(product.reload.rich_content_folder_name(folder1_id)).to eq ("folder 1") expect(product.reload.rich_content_folder_name(folder2_id)).to eq ("100") end end end context "for a variant" do let(:variant_category) { create(:variant_category) } let(:variant) { create(:variant, variant_category:) } describe "#rich_content_json" do context "when variant has rich content" do let!(:rich_content1) { create(:rich_content, entity: variant, description:, title: "Page 1", position: 3) } let!(:rich_content2) { create(:rich_content, entity: variant, description:, title: "Deleted page 2", deleted_at: 1.day.ago, position: 0) } let!(:rich_content3) { create(:rich_content, entity: variant, description:, title: "Page 3", position: 1) } let!(:another_variant_rich_content) { create(:rich_content, entity: create(:variant, variant_category:), description:, title: "Another variant's page", position: 2) } it "returns the variant-level alive rich contents" do expect(variant.rich_content_json).to eq([ { id: rich_content3.external_id, page_id: rich_content3.external_id, variant_id: variant.external_id, title: "Page 3", description: { type: "doc", content: rich_content3.description }, updated_at: rich_content3.updated_at }, { id: rich_content1.external_id, page_id: rich_content1.external_id, variant_id: variant.external_id, title: "Page 1", description: { type: "doc", content: rich_content1.description }, updated_at: rich_content1.updated_at } ]) end context "when corresponding product's `has_same_rich_content_for_all_variants` is true" do before do variant_category.link.update!(has_same_rich_content_for_all_variants: true) end it "returns empty array" do expect(variant.rich_content_json).to eq([]) end end end context "when variant does not have rich content" do it "returns empty array" do expect(variant.rich_content_json).to eq([]) 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/concerns/json_data_spec.rb
spec/models/concerns/json_data_spec.rb
# frozen_string_literal: true require "spec_helper" describe JsonData do # This can be any model, but I'm using the Purchase model for the tests. I could not # find a way to create a mock model which included JsonData. let(:model) do create(:purchase) end describe "attr_json_data_accessor" do describe "attr_json_data_reader" do it "returns the value of the attribute" do model.json_data = { "locale" => :en } expect(model.locale.to_sym).to eq(:en) end it "returns the default value when attribute not set or blank" do model.json_data = { "locale" => nil } expect(model.locale.to_sym).to eq(:en) end end describe "attr_json_data_writer" do it "sets the attribute in json_data" do model.locale = :ja expect(model.json_data["locale"].to_sym).to eq(:ja) end end end describe "json_data" do before do model.json_data = nil end it "returns an empty hash if not initialized" do expect(model.json_data).to eq({}) end end describe "json_data_for_attr" do it "gets the attribute in json_data" do model.json_data = { "attribute" => "hi" } expect(model.json_data_for_attr("attribute", default: "default")).to eq("hi") end it "returns the default if json_data is nil" do model.json_data = nil expect(model.json_data_for_attr("attribute", default: "default")).to eq("default") end it "returns the default if the attribute does not exist in json_data" do model.json_data = {} expect(model.json_data_for_attr("attribute", default: "default")).to eq("default") end it "returns the default if the attribute does exist but is not present" do model.json_data = { "attribute" => "" } expect(model.json_data_for_attr("attribute", default: "default")).to eq("default") end it "returns the default if the attribute does exist but is nil" do model.json_data = { "attribute" => nil } expect(model.json_data_for_attr("attribute", default: "default")).to eq("default") end it "returns nil if the attribute does not exist in json_data and no default" do model.json_data = {} expect(model.json_data_for_attr("attribute")).to be_nil end end describe "set_json_data_for_attr" do it "sets the attribute in json_data" do model.set_json_data_for_attr("attribute", "hi") expect(model.json_data["attribute"]).to eq("hi") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/transactional_attribute_change_tracker_spec.rb
spec/models/concerns/transactional_attribute_change_tracker_spec.rb
# frozen_string_literal: true describe TransactionalAttributeChangeTracker do before do @model = create_mock_model @model.include(described_class) end after do destroy_mock_model(@model) end describe "#attributes_committed" do let!(:record) { @model.create! } let(:fresh_record) { @model.find(record.id) } it "returns nil if no attribute changes were committed" do expect(fresh_record.attributes_committed).to eq(nil) fresh_record.title = "foo" expect(fresh_record.attributes_committed).to eq(nil) end it "returns attributes changed in the transaction when record was created" do expect(record.attributes_committed).to match_array(%w[id created_at updated_at]) end it "returns attributes changed in the transaction when record was updated" do record.update!(title: "foo", subtitle: "bar") expect(record.attributes_committed).to match_array(%w[title subtitle updated_at]) end it "only returns attributes changed in the transaction when record was last updated" do record.update!(title: "foo") expect(record.attributes_committed).to match_array(%w[title updated_at]) record.update!(subtitle: "bar") expect(record.attributes_committed).to match_array(%w[subtitle updated_at]) end it "returns attributes changed in the transaction when record was updated several times" do expect(record.title).to eq(nil) ApplicationRecord.transaction do record.update!(title: "foo") record.update!(subtitle: "bar") record.update!(user_id: 1) # expected behavior: even if within a transaction an attribute is changed back to the # value it had before the commit, it will still be tracked in `attributes_committed` record.update!(title: nil) end expect(record.attributes_committed).to match_array(%w[title subtitle user_id updated_at]) end it "returns attributes changed in the transaction when record was updated and reloaded" do ApplicationRecord.transaction do record.update!(title: "foo") record.update!(subtitle: "bar") record.reload end expect(record.attributes_committed).to match_array(%w[title subtitle updated_at]) end it "does not return attributes changed in the transaction when transaction is rolled back" do ApplicationRecord.transaction do record.update!(title: "foo") raise ActiveRecord::Rollback end expect(record.attributes_committed).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/concerns/stripped_fields_spec.rb
spec/models/concerns/stripped_fields_spec.rb
# frozen_string_literal: true require "spec_helper" ActiveRecord::Schema.define do create_table :test_fields, temporary: true, force: true do |t| t.string :name t.string :email t.string :description t.string :sql t.string :code end end describe StrippedFields do class TestField < ApplicationRecord include StrippedFields stripped_fields :name, :email, transform: ->(v) { v.upcase } stripped_fields :description, nilify_blanks: false stripped_fields :sql, remove_duplicate_spaces: false stripped_fields :code, transform: ->(v) { v.gsub(/\s/, "") } end let(:record) do TestField.new( name: " my name ", email: " ", description: " ", sql: " keep extra spaces ", code: " 1234 56\n78 " ) end it "updates values" do record.validate expect(record.name).to eq("MY NAME") expect(record.email).to be_nil expect(record.description).to eq("") expect(record.sql).to eq("keep extra spaces") expect(record.code).to eq("12345678") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/with_filtering_spec.rb
spec/models/concerns/with_filtering_spec.rb
# frozen_string_literal: true require "spec_helper" describe WithFiltering do describe "scopes" do describe "abandoned_cart_type" do it "returns only installments with the 'abandoned_cart' type" do abandoned_cart_installment = create(:installment, installment_type: Installment::ABANDONED_CART_TYPE) create(:installment) expect(Installment.abandoned_cart_type).to eq([abandoned_cart_installment]) end it "returns only workflows with the 'abandoned_cart' type" do abandoned_cart_workflow = create(:abandoned_cart_workflow) create(:workflow) expect(Workflow.abandoned_cart_type).to eq([abandoned_cart_workflow]) end end end describe "#purchase_passes_filters" do context "for created filters" do before do @product = create(:product) @purchase = create(:purchase, link: @product) @old_purchase = create(:purchase, link: @product, created_at: 1.month.ago) end context "when created_before filter is set" do before do @post = create(:seller_installment, seller: @product.user, json_data: { created_before: 1.day.ago }) end it "returns true for purchase older than the created_before date" do expect(@post.purchase_passes_filters(@old_purchase)).to eq(true) end it "returns false for purchase newer than the created_before date" do expect(@post.purchase_passes_filters(@purchase)).to eq(false) end end context "when created_after filter is set" do before do @post = create(:seller_installment, seller: @product.user, json_data: { created_after: 1.day.ago }) end it "returns true for purchase newer than the created_after date" do expect(@post.purchase_passes_filters(@purchase)).to eq(true) end it "returns false for purchase older than the created_after date" do expect(@post.purchase_passes_filters(@old_purchase)).to eq(false) end end context "when created_before and created_after filters are set" do before do @purchase_2 = create(:purchase, link: @product, created_at: 1.week.ago) @post = create(:seller_installment, seller: @product.user, json_data: { created_after: 2.weeks.ago, created_before: 1.day.ago }) end it "returns true for purchase within the created dates" do expect(@post.purchase_passes_filters(@purchase_2)).to eq(true) end it "returns false for purchases outside the created dates" do expect(@post.purchase_passes_filters(@purchase)).to eq(false) expect(@post.purchase_passes_filters(@old_purchase)).to eq(false) end end end context "for price filters" do before do @product = create(:product) @small_purchase = create(:purchase, link: @product, price_cents: 50) @medium_purchase = create(:purchase, link: @product, price_cents: 500) @big_purchase = create(:purchase, link: @product, price_cents: 1000) end context "when paid_more_than_cents filter is set" do before do @post = create(:seller_installment, seller: @product.user, json_data: { paid_more_than_cents: 100 }) end it "returns true for purchases higher than the paid_more_than_cents filter" do expect(@post.purchase_passes_filters(@medium_purchase)).to eq(true) expect(@post.purchase_passes_filters(@big_purchase)).to eq(true) end it "returns false for purchases lower than the paid_more_than_cents filter" do expect(@post.purchase_passes_filters(@small_purchase)).to eq(false) end end context "when paid_less_than_cents filter is set" do before do @post = create(:seller_installment, seller: @product.user, json_data: { paid_less_than_cents: 100 }) end it "returns false for purchases higher than the paid_more_than_cents filter" do expect(@post.purchase_passes_filters(@medium_purchase)).to eq(false) expect(@post.purchase_passes_filters(@big_purchase)).to eq(false) end it "returns true for purchases lower than the paid_more_than_cents filter" do expect(@post.purchase_passes_filters(@small_purchase)).to eq(true) end end context "when paid_more_than_cents and paid_less_than_cents filters are set" do before do @post = create(:seller_installment, seller: @product.user, json_data: { paid_more_than_cents: 100, paid_less_than_cents: 500 }) end it "returns true for purchase within the price range" do expect(@post.purchase_passes_filters(@medium_purchase)).to eq(true) end it "returns false for purchases outside the price range" do expect(@post.purchase_passes_filters(@small_purchase)).to eq(false) expect(@post.purchase_passes_filters(@big_purchase)).to eq(false) end end end context "when bought from country filter is set" do before do @product = create(:product) @us_purchase_1 = create(:purchase, link: @product, country: "United States") @us_purchase_2 = create(:purchase, link: @product, ip_country: "United States") @non_us_purchase = create(:purchase, link: @product, price_cents: 1000, country: "Canada") @post = create(:seller_installment, seller: @product.user, json_data: { bought_from: "United States" }) end it "returns true for purchases from selected bought_from country filter" do expect(@post.purchase_passes_filters(@us_purchase_1)).to eq(true) expect(@post.purchase_passes_filters(@us_purchase_2)).to eq(true) end it "returns false for purchase not matching the bought_from country filter" do expect(@post.purchase_passes_filters(@non_us_purchase)).to eq(false) end end describe "bought products and variants filters" do before do @product = create(:product) @variant = create(:variant, variant_category: create(:variant_category, link: @product)) @purchase = create(:purchase, link: @product) end describe "bought products only" do it "returns true if the purchased product is included in the filter" do post = create(:seller_installment, seller: @product.user, json_data: { bought_products: [@product.unique_permalink] }) expect(post.purchase_passes_filters(@purchase)).to eq true end it "returns false if the purchased product is not included in the filter" do post = create(:seller_installment, seller: @product.user, json_data: { bought_products: [create(:product).unique_permalink] }) expect(post.purchase_passes_filters(@purchase)).to eq false end end describe "bought variants only" do before do @purchase.variant_attributes = [@variant] end it "returns true if the purchased variant is included in the filter" do post = create(:seller_installment, seller: @product.user, json_data: { bought_variants: [@variant.external_id] }) expect(post.purchase_passes_filters(@purchase)).to eq true end it "returns false if the purchased variant is not included in the filter" do post = create(:seller_installment, seller: @product.user, json_data: { bought_variants: [create(:variant).external_id] }) expect(post.purchase_passes_filters(@purchase)).to eq false end end describe "bought products and variants" do it "returns true if the purchased product is included in the filter" do post = create(:seller_installment, seller: @product.user, json_data: { bought_products: [@product.unique_permalink], bought_variants: [create(:variant).external_id] }) expect(post.purchase_passes_filters(@purchase)).to eq true end it "returns false if the purchased product is not included in the filter" do post = create(:seller_installment, seller: @product.user, json_data: { bought_products: [create(:product).unique_permalink], bought_variants: [create(:variant).external_id] }) expect(post.purchase_passes_filters(@purchase)).to eq false end it "returns true if the purchased variant is included in the filter" do @purchase.variant_attributes = [@variant] post = create(:seller_installment, seller: @product.user, json_data: { bought_products: [create(:product).unique_permalink], bought_variants: [@variant.external_id] }) expect(post.purchase_passes_filters(@purchase)).to eq true end it "returns false if the purchased variant is not included in the filter" do @purchase.variant_attributes = [@variant] post = create(:seller_installment, seller: @product.user, json_data: { bought_products: [create(:product).unique_permalink], bought_variants: [create(:variant).external_id] }) expect(post.purchase_passes_filters(@purchase)).to eq false end end end describe "not bought filters" do let(:post) { create(:seller_installment, seller: @product.user, json_data: { not_bought_products:, not_bought_variants: }) } before do @product = create(:product) @variant = create(:variant, variant_category: create(:variant_category, link: @product)) @purchase = create(:purchase, link: @product) end describe "not bought products only" do context "when the purchased product is not included in the filter" do let(:not_bought_products) { [create(:product).unique_permalink] } let(:not_bought_variants) { [] } it "returns true" do expect(post.purchase_passes_filters(@purchase)).to eq true end end context "when the purchased product is included in the filter" do let(:not_bought_products) { [@product.unique_permalink] } let(:not_bought_variants) { [] } it "returns false" do expect(post.purchase_passes_filters(@purchase)).to eq false end end end describe "not bought variants only" do before do @purchase.variant_attributes = [@variant] end context "when the purchased variant is not included in the filter" do let(:not_bought_products) { nil } let(:not_bought_variants) { [@variant.external_id] } it "returns false" do expect(post.purchase_passes_filters(@purchase)).to eq false end end context "when the purchased variant is not included in the filter" do let(:not_bought_products) { [] } let(:not_bought_variants) { [create(:variant).external_id] } it "returns true" do expect(post.purchase_passes_filters(@purchase)).to eq true end end end describe "not bought products and variants" do context "when the purchased product is included in the filter" do let(:not_bought_products) { [@product.unique_permalink] } let(:not_bought_variants) { [create(:variant).external_id] } it "returns false" do expect(post.purchase_passes_filters(@purchase)).to eq false end end context "when the purchased product is not included in the filter" do let(:not_bought_products) { [create(:product).unique_permalink] } let(:not_bought_variants) { [create(:variant).external_id] } it "returns true" do expect(post.purchase_passes_filters(@purchase)).to eq true end end context "when the purchased variant is included in the filter" do let(:not_bought_products) { [create(:product).unique_permalink] } let(:not_bought_variants) { [@variant.external_id] } it "returns false" do @purchase.variant_attributes = [@variant] expect(post.purchase_passes_filters(@purchase)).to eq false end end context "when the purchased variant is not included in the filter" do let(:not_bought_products) { [create(:product).unique_permalink] } let(:not_bought_variants) { [create(:variant).external_id] } it "returns true" do @purchase.variant_attributes = [@variant] expect(post.purchase_passes_filters(@purchase)).to eq true end end end end describe "bought and not bought filters" do context "memberships that have changed tier" do before do @membership_product = create(:membership_product_with_preset_tiered_pricing) @old_tier = @membership_product.default_tier @new_tier = @membership_product.tiers.find_by(name: "Second Tier") email = generate(:email) original_purchase = create(:membership_purchase, email:, link: @membership_product, variant_attributes: [@old_tier]) subscription = original_purchase.subscription create(:purchase, email:, link: @membership_product, subscription:, variant_attributes: [@old_tier]) @new_original_purchase = create(:purchase, email:, link: @membership_product, subscription:, variant_attributes: [@new_tier], is_original_subscription_purchase: true, purchase_state: "not_charged") original_purchase.update!(is_archived_original_subscription_purchase: true) end it "returns true if the membership used to have the 'not bought' variant and currently has the 'bought' variant" do post = create(:seller_installment, seller: @membership_product.user, bought_variants: [@new_tier.external_id], not_bought_variants: [@old_tier.external_id]) expect(post.purchase_passes_filters(@new_original_purchase)).to eq true end it "returns false if the membership used to have the 'bought' variant and currently has the 'not bought' variant" do post = create(:seller_installment, seller: @membership_product.user, bought_variants: [@old_tier.external_id], not_bought_variants: [@new_tier.external_id]) expect(post.purchase_passes_filters(@new_original_purchase)).to eq false end end end end describe "#seller_post_passes_filters" do before do @creator = create(:user) end context "for created filters" do context "when created_before filter is set" do before do @post = create(:seller_installment, seller: @creator, json_data: { created_before: 1.day.ago }) end it "returns true for max_created_at older than the created_before date" do expect(@post.seller_post_passes_filters(max_created_at: 1.week.ago)).to eq(true) end it "returns false for max_created_at newer than the created_before date" do expect(@post.seller_post_passes_filters(max_created_at: Time.current)).to eq(false) end it "returns false when passed filters are missing" do expect(@post.seller_post_passes_filters).to eq(false) end end context "when created_after filter is set" do before do @post = create(:seller_installment, seller: @creator, json_data: { created_after: 1.day.ago }) end it "returns true for min_created_at newer than the created_after date" do expect(@post.seller_post_passes_filters(min_created_at: Time.current)).to eq(true) end it "returns false for min_created_at older than the created_after date" do expect(@post.seller_post_passes_filters(min_created_at: 1.week.ago)).to eq(false) end it "returns false when passed filters are missing" do expect(@post.seller_post_passes_filters).to eq(false) end end context "when created_before and created_after filters are set" do before do @post = create(:seller_installment, seller: @creator, json_data: { created_after: 2.weeks.ago, created_before: 1.day.ago }) end it "returns true when created timestamp filters are within the created dates" do expect(@post.seller_post_passes_filters(min_created_at: 1.week.ago, max_created_at: 2.days.ago)).to eq(true) end it "returns false for created timestamp filters are outside the created dates" do expect(@post.seller_post_passes_filters(min_created_at: 3.weeks.ago, max_created_at: 2.days.ago)).to eq(false) expect(@post.seller_post_passes_filters(min_created_at: 1.week.ago, max_created_at: Time.current)).to eq(false) end it "returns false when passed filters are missing" do expect(@post.seller_post_passes_filters).to eq(false) end end end context "for price filters" do context "when paid_more_than_cents filter is set" do before do @post = create(:seller_installment, seller: @creator, json_data: { paid_more_than_cents: 100 }) end it "returns true for min_price_cents higher than the paid_more_than_cents" do expect(@post.seller_post_passes_filters(min_price_cents: 150)).to eq(true) end it "returns false for min_price_cents lower than the paid_more_than_cents" do expect(@post.seller_post_passes_filters(min_price_cents: 50)).to eq(false) end it "returns false when passed filters are missing" do expect(@post.seller_post_passes_filters).to eq(false) end end context "when paid_less_than_cents filter is set" do before do @post = create(:seller_installment, seller: @creator, json_data: { paid_less_than_cents: 100 }) end it "returns true for max_price_cents lower than the paid_less_than_cents" do expect(@post.seller_post_passes_filters(max_price_cents: 50)).to eq(true) end it "returns false for max_price_cents higher than the paid_less_than_cents" do expect(@post.seller_post_passes_filters(max_price_cents: 150)).to eq(false) end it "returns false when passed filters are missing" do expect(@post.seller_post_passes_filters).to eq(false) end end context "when paid_more_than_cents and paid_less_than_cents filters are set" do before do @post = create(:seller_installment, seller: @creator, json_data: { paid_more_than_cents: 100, paid_less_than_cents: 500 }) end it "returns true when price filters are within the post's price range" do expect(@post.seller_post_passes_filters(min_price_cents: 200, max_price_cents: 200)).to eq(true) end it "returns false when price filters are outside the post's price range" do expect(@post.seller_post_passes_filters(min_price_cents: 99, max_price_cents: 200)).to eq(false) expect(@post.seller_post_passes_filters(min_price_cents: 200, max_price_cents: 1000)).to eq(false) expect(@post.seller_post_passes_filters(min_price_cents: 50, max_price_cents: 1000)).to eq(false) end it "returns false when passed filters are missing" do expect(@post.seller_post_passes_filters).to eq(false) end end end context "when bought from country filter is set" do before do @post = create(:seller_installment, seller: @creator, json_data: { bought_from: "United States" }) end it "returns true for country matching the selected bought_from country filter" do expect(@post.seller_post_passes_filters(country: "United States")).to eq(true) end it "returns true for ip_country matching the selected bought_from country filter" do expect(@post.seller_post_passes_filters(ip_country: "United States")).to eq(true) end it "returns false for country different than the selected bought_from country filter" do expect(@post.seller_post_passes_filters(country: "Canada")).to eq(false) end it "returns false for ip_country different than the selected bought_from country filter" do expect(@post.seller_post_passes_filters(country: "Canada")).to eq(false) end it "returns false when passed filters are missing" do expect(@post.seller_post_passes_filters).to eq(false) end end describe "bought products and variants filters" do describe "bought products only" do it "returns false when passed filters are missing" do post = create(:seller_installment, seller: @creator, json_data: { bought_products: ["a"] }) expect(post.seller_post_passes_filters).to eq(false) end it "returns false when product permalinks don't match the bought_products filter" do post = create(:seller_installment, seller: @creator, json_data: { bought_products: %w[a b] }) expect(post.seller_post_passes_filters(product_permalinks: %w[c d e])).to eq(false) end it "returns true when one product permalink matches the bought_products filter" do post = create(:seller_installment, seller: @creator, json_data: { bought_products: %w[a b] }) expect(post.seller_post_passes_filters(product_permalinks: %w[b c d])).to eq(true) end end describe "bought variants only" do it "returns false when passed filters are missing" do post = create(:seller_installment, seller: @creator, json_data: { bought_variants: ["a"] }) expect(post.seller_post_passes_filters).to eq(false) end it "returns false when product permalinks don't match the bought_products filter" do post = create(:seller_installment, seller: @creator, json_data: { bought_variants: %w[a b] }) expect(post.seller_post_passes_filters(variant_external_ids: %w[c d e])).to eq(false) end it "returns true when one product permalink matches the bought_products filter" do post = create(:seller_installment, seller: @creator, json_data: { bought_variants: %w[a b] }) expect(post.seller_post_passes_filters(variant_external_ids: %w[b c d])).to eq(true) end end end end describe "#affiliate_passes_filters" do context "for created filters" do before do @product = create(:product) @direct_affiliate = create(:direct_affiliate, seller: @product.user) @old_direct_affiliate = create(:direct_affiliate, seller: @product.user, created_at: 1.month.ago) end context "when created_before filter is set" do before do @post = create(:affiliate_installment, seller: @product.user, json_data: { created_before: 1.day.ago }) end it "returns true for affiliates older than the created_before date" do expect(@post.affiliate_passes_filters(@old_direct_affiliate)).to eq(true) end it "returns false for affiliates newer than the created_before date" do expect(@post.affiliate_passes_filters(@direct_affiliate)).to eq(false) end end context "when created_after filter is set" do before do @post = create(:seller_installment, seller: @product.user, json_data: { created_after: 1.day.ago }) end it "returns true for affiliates newer than the created_after date" do expect(@post.affiliate_passes_filters(@direct_affiliate)).to eq(true) end it "returns false for affiliates older than the created_after date" do expect(@post.affiliate_passes_filters(@old_direct_affiliate)).to eq(false) end end context "when created_before and created_after filters are set" do before do @direct_affiliate_2 = create(:direct_affiliate, seller: @product.user, created_at: 1.week.ago) @post = create(:affiliate_installment, seller: @product.user, json_data: { created_after: 2.weeks.ago, created_before: 1.day.ago }) end it "returns true for affiliates within the created dates" do expect(@post.affiliate_passes_filters(@direct_affiliate_2)).to eq(true) end it "returns false for affiliates outside the created dates" do expect(@post.affiliate_passes_filters(@direct_affiliate)).to eq(false) expect(@post.affiliate_passes_filters(@old_direct_affiliate)).to eq(false) end end end end describe "#follower_passes_filters" do context "for created filters" do before do @product = create(:product) user = create(:user, email: "follower@gum.co") old_user = create(:user, email: "follower2@gum.co") @follower = create(:follower, user: @product.user, email: user.email) @old_follower = create(:follower, user: @product.user, email: old_user.email, created_at: 1.month.ago) end context "when created_before filter is set" do before do @post = create(:follower_installment, seller: @product.user, json_data: { created_before: 1.day.ago }) end it "returns true for followers older than the created_before date" do expect(@post.follower_passes_filters(@old_follower)).to eq(true) end it "returns false for followers newer than the created_before date" do expect(@post.follower_passes_filters(@follower)).to eq(false) end end context "when created_after filter is set" do before do @post = create(:follower_installment, seller: @product.user, json_data: { created_after: 1.day.ago }) end it "returns true for followers newer than the created_after date" do expect(@post.follower_passes_filters(@follower)).to eq(true) end it "returns false for followers older than the created_after date" do expect(@post.follower_passes_filters(@old_follower)).to eq(false) end end context "when created_before and created_after filters are set" do before do user = create(:user, email: "follower3@gum.co") @follower_2 = create(:follower, user: @product.user, email: user.email, created_at: 1.week.ago) @post = create(:follower_installment, seller: @product.user, json_data: { created_after: 2.weeks.ago, created_before: 1.day.ago }) end it "returns true for followers within the created dates" do expect(@post.affiliate_passes_filters(@follower_2)).to eq(true) end it "returns false for followers outside the created dates" do expect(@post.affiliate_passes_filters(@follower)).to eq(false) expect(@post.affiliate_passes_filters(@old_follower)).to eq(false) end end end end describe "#abandoned_cart_type?" do it "returns true if the installment type is abandoned_cart" do post = create(:installment, installment_type: Installment::ABANDONED_CART_TYPE) expect(post.abandoned_cart_type?).to be(true) end it "returns true if the workflow type is abandoned_cart" do workflow = create(:abandoned_cart_workflow) expect(workflow.abandoned_cart_type?).to be(true) end it "returns false if the installment type is not abandoned_cart" do post = create(:seller_installment) expect(post.abandoned_cart_type?).to be(false) end it "returns false if the workflow type is not abandoned_cart" do workflow = create(:workflow) expect(workflow.abandoned_cart_type?).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/concerns/search_index_model_common_spec.rb
spec/models/concerns/search_index_model_common_spec.rb
# frozen_string_literal: true describe SearchIndexModelCommon do before do @klass = Class.new(User) @klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1 include SearchIndexModelCommon include Elasticsearch::Model index_name "user-fake-index-for-test" mappings do indexes :first_name, type: :keyword indexes :last_name, type: :keyword indexes :email, type: :keyword indexes :is_active_with_name, type: :boolean indexes :active, type: :boolean indexes :has_amex, type: :boolean end ATTRIBUTE_TO_SEARCH_FIELDS = { "first_name" => ["first_name", "is_active_with_name"], "last_name" => ["last_name", "is_active_with_name"], "email" => "email", "active" => ["active", "is_active_with_name"], } def search_field_value(field_name) "\#{field_name} value" end RUBY end describe ".search_fields" do it "returns a list of search fields for the index" do expect(@klass.search_fields).to match_array([ "first_name", "is_active_with_name", "last_name", "email", "active", "has_amex" ]) end end describe "#as_indexed_json" do it "returns json versions" do instance = @klass.new expect(instance.as_indexed_json).to eq( "first_name" => "first_name value", "is_active_with_name" => "is_active_with_name value", "last_name" => "last_name value", "email" => "email value", "active" => "active value", "has_amex" => "has_amex 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/concerns/secure_external_id_spec.rb
spec/models/concerns/secure_external_id_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe SecureExternalId do let(:test_class) do Class.new do include SecureExternalId def self.name "TestClass" end def self.find_by(conditions) new if conditions[:id] == 123 end def id 123 end end end let(:test_instance) { test_class.new } before do allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return({ primary_key_version: "1", keys: { "1" => "a" * 32 } }) end describe "#secure_external_id" do it "generates an encrypted token" do token = test_instance.secure_external_id(scope: "test") expect(token).to be_a(String) expect(token.length).to be >= 50 end end describe ".find_by_secure_external_id" do it "finds record with valid token" do token = test_instance.secure_external_id(scope: "test") expect(test_class.find_by_secure_external_id(token, scope: "test")).to be_a(test_class) end it "returns nil for invalid token" do expect(test_class.find_by_secure_external_id("invalid", scope: "test")).to be_nil end it "returns nil for wrong scope" do token = test_instance.secure_external_id(scope: "test") expect(test_class.find_by_secure_external_id(token, scope: "wrong")).to be_nil end it "checks for expired token" do expires_at = 1.hour.from_now token = test_instance.secure_external_id(scope: "test", expires_at: expires_at) travel_to 45.minutes.from_now do expect(test_class.find_by_secure_external_id(token, scope: "test")).to be_a(test_class) end travel_to 2.hours.from_now do expect(test_class.find_by_secure_external_id(token, scope: "test")).to be_nil # expired end end it "returns nil for non-string input" do expect(test_class.find_by_secure_external_id(123, scope: "test")).to be_nil end it "returns nil for invalid base64" do expect(test_class.find_by_secure_external_id("invalid base64!", scope: "test")).to be_nil end it "returns nil for wrong model name" do other_class = Class.new do include SecureExternalId def self.name "OtherClass" end def id 123 end end token = test_instance.secure_external_id(scope: "test") expect(other_class.find_by_secure_external_id(token, scope: "test")).to be_nil end it "supports key rotation" do token_v1 = test_instance.secure_external_id(scope: "test") allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return({ primary_key_version: "2", keys: { "1" => "a" * 32, "2" => "b" * 32 } }) expect(test_class.find_by_secure_external_id(token_v1, scope: "test")).to be_a(test_class) token_v2 = test_instance.secure_external_id(scope: "test") expect(test_class.find_by_secure_external_id(token_v2, scope: "test")).to be_a(test_class) end end describe "configuration validation" do it "raises error when configuration is blank" do allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return({}) expect do test_instance.secure_external_id(scope: "test") end.to raise_error(SecureExternalId::Error, "SecureExternalId configuration is missing") end it "raises error when primary_key_version is missing" do allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return({ keys: { "1" => "a" * 32 } }) expect do test_instance.secure_external_id(scope: "test") end.to raise_error(SecureExternalId::Error, "primary_key_version is required in SecureExternalId config") end it "raises error when primary_key_version is blank" do allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return({ primary_key_version: "", keys: { "1" => "a" * 32 } }) expect do test_instance.secure_external_id(scope: "test") end.to raise_error(SecureExternalId::Error, "primary_key_version is required in SecureExternalId config") end it "raises error when keys are missing" do allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return({ primary_key_version: "1" }) expect do test_instance.secure_external_id(scope: "test") end.to raise_error(SecureExternalId::Error, "keys are required in SecureExternalId config") end it "raises error when keys are blank" do allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return({ primary_key_version: "1", keys: {} }) expect do test_instance.secure_external_id(scope: "test") end.to raise_error(SecureExternalId::Error, "keys are required in SecureExternalId config") end it "raises error when primary key version is not found in keys" do allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return({ primary_key_version: "2", keys: { "1" => "a" * 32 } }) expect do test_instance.secure_external_id(scope: "test") end.to raise_error(SecureExternalId::Error, "Primary key version '2' not found in keys") end it "raises error when key is not exactly 32 bytes" do allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return({ primary_key_version: "1", keys: { "1" => "short_key" } }) expect do test_instance.secure_external_id(scope: "test") end.to raise_error(SecureExternalId::Error, "Key for version '1' must be exactly 32 bytes for aes-256-gcm") end it "raises error when any key in rotation is not exactly 32 bytes" do allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return({ primary_key_version: "1", keys: { "1" => "a" * 32, "2" => "too_short" } }) expect do test_instance.secure_external_id(scope: "test") end.to raise_error(SecureExternalId::Error, "Key for version '2' must be exactly 32 bytes for aes-256-gcm") end it "passes validation with proper configuration" do allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return({ primary_key_version: "1", keys: { "1" => "a" * 32, "2" => "b" * 32 } }) expect do test_instance.secure_external_id(scope: "test") end.not_to raise_error end end describe "environment variable configuration" do let(:primary_key_version_value) { "1" } let(:key_versions) { { "1" => "a" * 32 } } def stub_env_config(primary_version: primary_key_version_value, keys: key_versions) allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, default: nil) .and_return(nil) allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, :primary_key_version, default: nil) .and_return(primary_version) (1..10).each do |version| key_value = keys[version.to_s] allow(GlobalConfig).to receive(:dig) .with(:secure_external_id, :keys, version.to_s, default: nil) .and_return(key_value) end end context "when credentials are not present" do before do stub_env_config end it "builds config from environment variables" do token = test_instance.secure_external_id(scope: "test") expect(token).to be_a(String) expect(test_class.find_by_secure_external_id(token, scope: "test")).to be_a(test_class) end it "builds config with multiple key versions" do stub_env_config(primary_version: "2", keys: { "1" => "a" * 32, "2" => "b" * 32 }) token = test_instance.secure_external_id(scope: "test") expect(token).to be_a(String) expect(test_class.find_by_secure_external_id(token, scope: "test")).to be_a(test_class) end it "supports key rotation with env vars" do token_v1 = test_instance.secure_external_id(scope: "test") test_class.instance_variable_set(:@config, nil) test_class.instance_variable_set(:@encryptors, nil) stub_env_config(primary_version: "2", keys: { "1" => "a" * 32, "2" => "b" * 32 }) expect(test_class.find_by_secure_external_id(token_v1, scope: "test")).to be_a(test_class) token_v2 = test_instance.secure_external_id(scope: "test") expect(test_class.find_by_secure_external_id(token_v2, scope: "test")).to be_a(test_class) end it "raises error when primary_key_version is missing" do stub_env_config(primary_version: nil, keys: {}) expect do test_instance.secure_external_id(scope: "test") end.to raise_error(SecureExternalId::Error, "SecureExternalId configuration is missing") end it "raises error when primary_key_version is blank" do stub_env_config(primary_version: "", keys: {}) expect do test_instance.secure_external_id(scope: "test") end.to raise_error(SecureExternalId::Error, "SecureExternalId configuration is missing") 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/concerns/timestamp_state_fields_spec.rb
spec/models/concerns/timestamp_state_fields_spec.rb
# frozen_string_literal: true require "spec_helper" describe TimestampStateFields do class TestUser < ApplicationRecord self.table_name = "users" include TimestampStateFields timestamp_state_fields \ :created, :confirmed, :banned, :deleted, default_state: :confirmed, states_excluded_from_default: %i[created] end let!(:user) do TestUser.create!( name: "Joe", email: "joe@example.com", recommendation_type: User::RecommendationType::OWN_PRODUCTS ) end describe "class methods" do before { user.update_as_banned! } it "it filter records" do expect(TestUser.banned).to eq [user] expect(TestUser.not_banned).to eq [] end end describe "instance methods" do it "returns boolean value when using predicate methods" do expect(user.created?).to be(true) expect(user.not_created?).to be(false) end it "updates record via update methods" do expect(user.banned?).to be(false) user.update_as_banned! expect(user.banned?).to be(true) user.update_as_not_banned! expect(user.banned?).to be(false) end it "reponds to state methods" do expect(user.created?).to be(true) expect(user.state_confirmed?).to be(true) expect(user.state).to eq(:confirmed) expect(user.banned?).to be(false) expect(user.deleted?).to be(false) user.update_as_banned! expect(user.state).to eq(:banned) expect(user.state_banned?).to be(true) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/two_factor_authentication_spec.rb
spec/models/concerns/two_factor_authentication_spec.rb
# frozen_string_literal: true require "spec_helper" describe TwoFactorAuthentication do before do @user = create(:user) end describe "#otp_secret_key" do it "sets otp_secret_key for a new user" do expect(@user.otp_secret_key.length).to eq 32 end end describe ".find_by_encrypted_external_id" do it "find the user" do expect(User.find_by_encrypted_external_id(@user.encrypted_external_id)).to eq @user end end describe "#encrypted_external_id" do it "returns the encrypted external id" do expect(@user.encrypted_external_id).to eq ObfuscateIds.encrypt(@user.external_id) end end describe "#two_factor_authentication_cookie_key" do it "returns two factor authentication cookie key" do encrypted_id_sha = Digest::SHA256.hexdigest(@user.encrypted_external_id)[0..12] expect(@user.two_factor_authentication_cookie_key).to eq "_gumroad_two_factor_#{encrypted_id_sha}" end end describe "#send_authentication_token!" do it "enqueues authentication token email" do expect do @user.send_authentication_token! end.to have_enqueued_mail(TwoFactorAuthenticationMailer, :authentication_token).with(@user.id) end end describe "#add_two_factor_authenticated_ip!" do it "adds the two factor authenticated IP to redis" do @user.add_two_factor_authenticated_ip!("127.0.0.1") expect(@user.two_factor_auth_redis_namespace.get("auth_ip_#{@user.id}_127.0.0.1")).to eq "true" end end describe "#token_authenticated?" do describe "token validity" do context "when token is more than 10 minutes old" do before do travel_to(11.minutes.ago) do @token = @user.otp_code end end it "returns false" do expect(@user.token_authenticated?(@token)).to eq false end end context "when token is less than 10 minutes old" do before do travel_to(9.minutes.ago) do @token = @user.otp_code end end it "returns true" do expect(@user.token_authenticated?(@token)).to eq true end end end describe "default authentication token" do before do allow(@user).to receive(:authenticate_otp).and_return(false) end context "when Rails environment is not production" do it "returns true" do expect(@user.token_authenticated?("000000")).to eq true end end context "when Rails environment is production" do before do allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("production")) end it "returns false" do expect(@user.token_authenticated?("000000")).to eq false end end end end describe "#has_logged_in_from_ip_before?" do before do @user.add_two_factor_authenticated_ip!("127.0.0.2") end context "when the user has logged in from the IP" do it "returns true" do expect(@user.has_logged_in_from_ip_before?("127.0.0.2")).to eq true end end context "when the user has not logged in from the IP" do it "returns false" do expect(@user.has_logged_in_from_ip_before?("127.0.0.3")).to eq false end end end describe "#two_factor_auth_redis_namespace" do it "returns the redis namespace for two factor authentication" do redis_namespace = @user.two_factor_auth_redis_namespace expect(redis_namespace).to be_a Redis::Namespace expect(redis_namespace.namespace).to eq :two_factor_auth_redis_namespace end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/installment/searchable_spec.rb
spec/models/concerns/installment/searchable_spec.rb
# frozen_string_literal: true require "spec_helper" describe Installment::Searchable do describe "#as_indexed_json" do let(:installment) { create(:published_installment, name: "First post", message: "<p>body</p>") } it "includes all fields" do expect(installment.as_indexed_json).to eq( "message" => "<p>body</p>", "created_at" => installment.created_at.utc.iso8601, "deleted_at" => nil, "published_at" => installment.published_at.utc.iso8601, "id" => installment.id, "seller_id" => installment.seller_id, "workflow_id" => installment.workflow_id, "name" => "First post", "selected_flags" => ["send_emails", "allow_comments"], ) end it "allows only a selection of fields to be used" do expect(installment.as_indexed_json(only: ["name"])).to eq( "name" => "First post" ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/product/structured_data_spec.rb
spec/models/concerns/product/structured_data_spec.rb
# frozen_string_literal: true require "spec_helper" describe Product::StructuredData do let(:user) { create(:user, name: "John Doe") } let(:product) { create(:product, user:, name: "My Great Book") } describe "#structured_data" do context "when product is not an ebook" do before do product.update!(native_type: "digital") end it "returns an empty hash" do expect(product.structured_data).to eq({}) end end context "when product is an ebook" do before do product.update!(native_type: Link::NATIVE_TYPE_EBOOK) end it "returns structured data with correct schema.org format" do data = product.structured_data expect(data["@context"]).to eq("https://schema.org") expect(data["@type"]).to eq("Book") end it "includes the product name" do data = product.structured_data expect(data["name"]).to eq("My Great Book") end it "includes the author information" do data = product.structured_data expect(data["author"]).to eq({ "@type" => "Person", "name" => "John Doe" }) end it "includes the product URL" do data = product.structured_data expect(data["url"]).to eq(product.long_url) end context "with description" do context "when custom_summary is present" do let(:custom_summary_text) { "This is a custom summary for the book" } before do product.save_custom_summary(custom_summary_text) product.update!(description: "This is the regular description") end it "uses custom_summary for description" do data = product.structured_data expect(data["description"]).to eq(custom_summary_text) end end context "when custom_summary is not present" do before do product.update!(description: "This is the regular description") end it "uses sanitized html_safe_description" do data = product.structured_data expect(data["description"]).to eq("This is the regular description") end end context "when description is blank" do before do product.update!(description: "") end it "returns nil for description" do data = product.structured_data expect(data["description"]).to be_nil end end context "when description exceeds 160 characters" do let(:long_description) { "a" * 200 } before do product.update!(description: long_description) end it "truncates description to 160 characters" do data = product.structured_data expect(data["description"].length).to be <= 160 expect(data["description"]).to end_with("...") end end context "when description contains HTML tags" do before do product.update!(description: "<p>This is <strong>bold</strong> text</p>") end it "strips HTML tags from description" do data = product.structured_data expect(data["description"]).to eq("This is bold text") end end end context "with product files" do context "when there are no product files" do it "does not include workExample" do data = product.structured_data expect(data).not_to have_key("workExample") end end context "when there are product files that support ISBN" do context "with PDF file" do let!(:pdf_file) do create(:readable_document, link: product, filetype: "pdf") end it "includes workExample for the PDF" do data = product.structured_data expect(data["workExample"]).to be_an(Array) expect(data["workExample"].length).to eq(1) expect(data["workExample"].first).to include( "@type" => "Book", "bookFormat" => "EBook", "name" => "My Great Book (PDF)" ) end context "when PDF has ISBN" do before do pdf_file.update!(isbn: "978-3-16-148410-0") end it "includes the ISBN in workExample" do data = product.structured_data expect(data["workExample"].first["isbn"]).to eq("978-3-16-148410-0") end end context "when PDF does not have ISBN" do before do pdf_file.update!(isbn: nil) end it "does not include ISBN in workExample" do data = product.structured_data expect(data["workExample"].first).not_to have_key("isbn") end end end context "with EPUB file" do let!(:epub_file) do create(:non_readable_document, link: product, filetype: "epub") end it "includes workExample for the EPUB" do data = product.structured_data expect(data["workExample"]).to be_an(Array) expect(data["workExample"].length).to eq(1) expect(data["workExample"].first).to include( "@type" => "Book", "bookFormat" => "EBook", "name" => "My Great Book (EPUB)" ) end context "when EPUB has ISBN" do before do epub_file.update!(isbn: "978-0-306-40615-7") end it "includes the ISBN in workExample" do data = product.structured_data expect(data["workExample"].first["isbn"]).to eq("978-0-306-40615-7") end end end context "with MOBI file" do let!(:mobi_file) do create(:product_file, link: product, filetype: "mobi", url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/test.mobi") end it "includes workExample for the MOBI" do data = product.structured_data expect(data["workExample"]).to be_an(Array) expect(data["workExample"].length).to eq(1) expect(data["workExample"].first).to include( "@type" => "Book", "bookFormat" => "EBook", "name" => "My Great Book (MOBI)" ) end end context "with multiple book files" do let!(:pdf_file) do create(:readable_document, link: product, filetype: "pdf", isbn: "978-3-16-148410-0") end let!(:epub_file) do create(:non_readable_document, link: product, filetype: "epub", isbn: "978-0-306-40615-7") end it "includes workExample for all book files" do data = product.structured_data expect(data["workExample"]).to be_an(Array) expect(data["workExample"].length).to eq(2) pdf_example = data["workExample"].find { |ex| ex["name"].include?("PDF") } epub_example = data["workExample"].find { |ex| ex["name"].include?("EPUB") } expect(pdf_example["isbn"]).to eq("978-3-16-148410-0") expect(epub_example["isbn"]).to eq("978-0-306-40615-7") end end end context "when there are product files that do not support ISBN" do let!(:video_file) do create(:streamable_video, link: product) end it "does not include workExample" do data = product.structured_data expect(data).not_to have_key("workExample") end end context "with mixed file types" do let!(:pdf_file) do create(:readable_document, link: product, filetype: "pdf", isbn: "978-3-16-148410-0") end let!(:video_file) do create(:streamable_video, link: product) end it "only includes workExample for files that support ISBN" do data = product.structured_data expect(data["workExample"]).to be_an(Array) expect(data["workExample"].length).to eq(1) expect(data["workExample"].first["name"]).to include("PDF") end end context "with deleted product files" do let!(:pdf_file) do create(:readable_document, link: product, filetype: "pdf", isbn: "978-3-16-148410-0") end before do pdf_file.update!(deleted_at: Time.current) end it "does not include deleted files in workExample" do data = product.structured_data expect(data).not_to have_key("workExample") 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/concerns/product/sorting_spec.rb
spec/models/concerns/product/sorting_spec.rb
# frozen_string_literal: true require "spec_helper" describe Product::Sorting do let!(:seller) { create(:recommendable_user) } describe ".sorted_by" do let!(:collaborator) { create(:collaborator, seller:) } let!(:product1) { create(:product, :is_collab, collaborator:, user: seller, name: "p1", display_product_reviews: true, taxonomy: create(:taxonomy), purchase_disabled_at: Time.current, created_at: Time.current, collaborator_cut: 45_00) } let!(:product2) { create(:product, :is_collab, collaborator:, user: seller, name: "p2", display_product_reviews: false, taxonomy: create(:taxonomy), created_at: Time.current + 1, collaborator_cut: 35_00) } let!(:product3) { create(:subscription_product, :is_collab, collaborator:, user: seller, name: "p3", display_product_reviews: false, purchase_disabled_at: Time.current, created_at: Time.current - 1, collaborator_cut: 15_00) } let!(:product4) { create(:subscription_product, :is_collab, collaborator:, user: seller, name: "p4", display_product_reviews: true, created_at: Time.current - 2, collaborator_cut: 25_00) } before do create_list(:purchase, 2, link: product1) create_list(:purchase, 3, link: product2) create(:purchase, is_original_subscription_purchase: true, link: product3, subscription: create(:subscription, link: product3, cancelled_at: nil)) index_model_records(Purchase) index_model_records(Link) [product1, product2, product3, product4].each { _1.product_cached_values.create! } end it "returns products sorted by name" do order = [product1, product2, product3, product4].map(&:name) expect(seller.products.sorted_by(key: "name", direction: "asc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order) expect(seller.products.sorted_by(key: "name", direction: "desc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order.reverse) end it "returns products sorted by successful sales count" do order = [product4, product3, product1, product2].map(&:name) expect(seller.products.sorted_by(key: "successful_sales_count", direction: "asc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order) expect(seller.products.sorted_by(key: "successful_sales_count", direction: "desc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order.reverse) end it "returns products sorted by status" do unpublished = [product1, product3].map(&:name) published = [product2, product4].map(&:name) order = unpublished + published order_reverse = published + unpublished expect(seller.products.sorted_by(key: "status", direction: "asc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order) expect(seller.products.sorted_by(key: "status", direction: "desc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order_reverse) end it "returns products sorted by collaborator cut" do seller_collaborator = create(:collaborator, seller: collaborator.affiliate_user, affiliate_user: seller) collaborator_product1 = create(:product, :is_collab, collaborator: seller_collaborator, user: collaborator.affiliate_user, collaborator_cut: 30_00) collaborator_product2 = create(:product, :is_collab, collaborator: seller_collaborator, user: collaborator.affiliate_user, collaborator_cut: 20_00) seller_order_asc = [collaborator_product2, collaborator_product1, product1, product2, product4, product3].map(&:name) collaborator_order_asc = [product3, collaborator_product2, product4, collaborator_product1, product2, product1].map(&:name) expect(Link.sorted_by(key: "cut", direction: "asc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(seller_order_asc) expect(Link.sorted_by(key: "cut", direction: "desc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(seller_order_asc.reverse) expect(Link.sorted_by(key: "cut", direction: "asc", user_id: collaborator.id).order(created_at: :desc).map(&:name)).to eq(collaborator_order_asc) expect(Link.sorted_by(key: "cut", direction: "desc", user_id: collaborator.id).order(created_at: :desc).map(&:name)).to eq(collaborator_order_asc.reverse) end it "returns products sorted by whether a taxonomy is present" do has_taxonomy = [product2, product1].map(&:name) has_no_taxonomy = [product3, product4].map(&:name) order = has_taxonomy + has_no_taxonomy order_reverse = has_no_taxonomy + has_taxonomy expect(seller.products.sorted_by(key: "taxonomy", direction: "asc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order) expect(seller.products.sorted_by(key: "taxonomy", direction: "desc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order_reverse) end it "returns products sorted by whether displaying product reviews is enabled" do without_reviews = [product2, product3].map(&:name) with_reviews = [product1, product4].map(&:name) order = without_reviews + with_reviews order_reverse = with_reviews + without_reviews expect(seller.products.sorted_by(key: "display_product_reviews", direction: "asc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order) expect(seller.products.sorted_by(key: "display_product_reviews", direction: "desc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order_reverse) end it "returns products sorted by revenue" do order = [product4, product3, product1, product2].map(&:name) expect(seller.products.sorted_by(key: "revenue", direction: "asc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order) expect(seller.products.sorted_by(key: "revenue", direction: "desc", user_id: seller.id).order(created_at: :desc).map(&:name)).to eq(order.reverse) end end describe ".elasticsearch_sorted_and_paginated_by" do let!(:product1) { create(:product, :recommendable, price_cents: 400, user: seller, name: "p1", display_product_reviews: true, taxonomy: create(:taxonomy), created_at: 2.days.ago) } let!(:product2) { create(:product, :recommendable, price_cents: 900, user: seller, name: "p2", display_product_reviews: true, taxonomy: create(:taxonomy), created_at: Time.current) } let!(:product3) { create(:subscription_product, :recommendable, price_cents: 1000, user: seller, name: "p3", taxonomy: nil, display_product_reviews: false, created_at: 3.days.ago) } let!(:product4) { create(:subscription_product, :recommendable, price_cents: 600, user: seller, name: "p4", taxonomy: nil, display_product_reviews: false, created_at: 4.days.ago) } before do create_list(:purchase, 2, link: product1) create_list(:purchase, 3, link: product2) create(:purchase, is_original_subscription_purchase: true, link: product3, subscription: create(:subscription, link: product3, cancelled_at: nil)) index_model_records(Purchase) index_model_records(Link) end it "returns products sorted by price" do recurrence_price_values = [ { BasePrice::Recurrence::MONTHLY => { enabled: true, price: 6 }, BasePrice::Recurrence::YEARLY => { enabled: true, price: 20 } }, { BasePrice::Recurrence::MONTHLY => { enabled: true, price: 4 }, BasePrice::Recurrence::YEARLY => { enabled: true, price: 3 } } ] tiered_membership1 = create(:membership_product_with_preset_tiered_pricing, name: "t1", user: seller, subscription_duration: BasePrice::Recurrence::YEARLY, recurrence_price_values:) recurrence_price_values = [ { BasePrice::Recurrence::MONTHLY => { enabled: true, price: 5 }, BasePrice::Recurrence::YEARLY => { enabled: true, price: 15 } }, { BasePrice::Recurrence::MONTHLY => { enabled: true, price: 6 }, BasePrice::Recurrence::YEARLY => { enabled: true, price: 35 } } ] tiered_membership2 = create(:membership_product_with_preset_tiered_pricing, name: "t2", user: seller, subscription_duration: BasePrice::Recurrence::YEARLY, recurrence_price_values:) subscription1 = create(:subscription_product, name: "Subscription 1", user: seller, price_cents: 1100, created_at: 4.days.ago) variant_category = create(:variant_category, link: product3) create(:variant, price_difference_cents: 200, variant_category:, name: "V1") create(:variant, price_difference_cents: 300, variant_category:, name: "V2") index_model_records(Link) order = [tiered_membership1, product1, tiered_membership2, product4, product2, subscription1, product3].map(&:name) pagination, products = seller.products.elasticsearch_sorted_and_paginated_by(key: "display_price_cents", direction: "asc", page: 1, per_page: 7, user_id: seller.id) expect(pagination).to eq({ page: 1, pages: 1 }) expect(products.map(&:name)).to eq(order) pagination, products = seller.products.elasticsearch_sorted_and_paginated_by(key: "display_price_cents", direction: "desc", page: 1, per_page: 7, user_id: seller.id) expect(pagination).to eq({ page: 1, pages: 1 }) expect(products.map(&:name)).to eq(order.reverse) end it "returns products sorted by whether the product is recommendable" do recommendable = [product2, product1].map(&:name) non_recommendable = [product3, product4].map(&:name) pagination, products = seller.products.elasticsearch_sorted_and_paginated_by(key: "is_recommendable", direction: "asc", page: 1, per_page: 4, user_id: seller.id) expect(pagination).to eq({ page: 1, pages: 1 }) expect(products.map(&:name)).to eq(non_recommendable + recommendable) pagination, products = seller.products.elasticsearch_sorted_and_paginated_by(key: "is_recommendable", direction: "desc", page: 1, per_page: 4, user_id: seller.id) expect(pagination).to eq({ page: 1, pages: 1 }) expect(products.map(&:name)).to eq(recommendable + non_recommendable) end end describe ".elasticsearch_key?" do it "returns true only for ElasticSearch sort keys" do expect(Product::Sorting::ES_SORT_KEYS.all? { seller.products.elasticsearch_key?(_1) }).to eq(true) expect(Product::Sorting::SQL_SORT_KEYS.any? { seller.products.elasticsearch_key?(_1) }).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/concerns/product/staff_picked_spec.rb
spec/models/concerns/product/staff_picked_spec.rb
# frozen_string_literal: true require "spec_helper" describe Product::StaffPicked do let(:product) { create(:product) } describe "#staff_picked?" do context "when there is no staff_picked_product record" do it "returns false" do expect(product.staff_picked?).to eq(false) end end context "when there is a staff_picked_product record" do let!(:staff_picked_product) { product.create_staff_picked_product! } context "when the staff_picked_product record is not deleted" do it "returns true" do expect(product.staff_picked?).to eq(true) end end context "when the staff_picked_product record is deleted" do before do staff_picked_product.update_as_deleted! end it "returns false" do expect(product.staff_picked?).to eq(false) end end end end describe "#staff_picked_at" do context "when there is no staff_picked_product record" do it "returns nil" do expect(product.staff_picked_at).to eq(nil) end end context "when there is a staff_picked_product record" do let!(:staff_picked_product) { product.create_staff_picked_product! } before do staff_picked_product.touch end context "when the staff_picked_product record is not deleted" do it "returns correct timestamp" do expect(product.staff_picked_at).to eq(staff_picked_product.updated_at) end end context "when the staff_picked_product record is deleted" do before do staff_picked_product.update_as_deleted! end it "returns nil" do expect(product.staff_picked_at).to eq(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/concerns/product/as_json_spec.rb
spec/models/concerns/product/as_json_spec.rb
# frozen_string_literal: true require "spec_helper" describe Product::AsJson, :vcr do describe "as_json method" do before do @product = create(:product, name: "some link", require_shipping: true) end it "returns the correct has for default (public)" do expect(@product.as_json.key?("name")).to be(true) expect(@product.as_json.key?("require_shipping")).to be(true) expect(@product.as_json.key?("url")).to be(false) end context "for api" do context "[:view_public] scope" do it "returns the correct hash" do json = @product.as_json(api_scopes: ["view_public"]) %w[ name description require_shipping preview_url url max_purchase_count custom_receipt customizable_price custom_summary deleted custom_fields ].each do |key| expect(json.key?(key)).to be(true) end end it "includes pricing data for a tiered membership product" do product = create(:membership_product_with_preset_tiered_pricing) json = product.as_json(api_scopes: ["view_public"]) expect(json["is_tiered_membership"]).to eq true expect(json["recurrences"]).to eq ["monthly"] tiers_json = json["variants"][0][:options] tiers_json.map do |tier_json| expect(tier_json[:is_pay_what_you_want]).to eq false expect(tier_json[:recurrence_prices].keys).to eq ["monthly"] expect(tier_json[:recurrence_prices]["monthly"].keys).to match_array [:price_cents, :suggested_price_cents] end end it "returns thumbnail_url information" do thumbnail = create(:thumbnail) product = thumbnail.product json = product.as_json(api_scopes: ["view_public"]) expect(json["thumbnail_url"]).to eq thumbnail.url end it "returns tags" do @product.tag!("one") @product.tag!("two") json = @product.as_json(api_scopes: ["view_public"]) expect(json["tags"]).to contain_exactly("one", "two") end end end it "returns the correct text for custom_summary" do @product.save_custom_summary("test") json = @product.as_json(api_scopes: ["view_public"]) expect(json["custom_summary"]).to eq "test" @product.save_custom_summary(nil) json = @product.as_json(api_scopes: ["view_public"]) expect(json["custom_summary"]).to eq nil @product.save_custom_summary("") json = @product.as_json(api_scopes: ["view_public"]) expect(json["custom_summary"]).to eq "" end it "returns the correct values for custom_fields" do json = @product.as_json(api_scopes: ["view_public"]) expect(json["custom_fields"]).to eq [] @product.custom_fields << create(:custom_field, name: "I'm custom!") json = @product.as_json(api_scopes: ["view_public"]) expect(json["custom_fields"]).to eq [ { id: @product.custom_fields.last.external_id, type: "text", name: "I'm custom!", required: false, collect_per_product: false }, ].as_json end it "returns the correct hash for api, :view_public,:edit_products" do json = @product.as_json(api_scopes: %w[view_public edit_products]) %w[ name description require_shipping preview_url url max_purchase_count custom_receipt customizable_price custom_summary deleted custom_fields ].each do |key| expect(json.key?(key)).to be(true) end %w[ sales_count sales_usd_cents view_count ].each do |key| expect(json.key?(key)).to be(false) end end it "returns the correct value for max_purchase_count if it is not set by the user" do expect(@product.as_json(api_scopes: %w[view_public edit_products])["max_purchase_count"]).to be(nil) end it "returns the correct value for max_purchase_count if it is set by the user" do @product.update(max_purchase_count: 10) expect(@product.reload.as_json(api_scopes: %w[view_public edit_products])["max_purchase_count"]).to eq 10 end it "returns the correct hash for api, :view_sales" do %w[name description require_shipping url file_info sales_count sales_usd_cents].each do |key| expect(@product.as_json(api_scopes: ["view_sales"]).key?(key)).to be(true) end end it "includes the preorder_link information for an unreleased link" do @product.update(is_in_preorder_state: true) @preorder_link = create(:preorder_link, link: @product, release_at: 2.days.from_now) link_json = @product.as_json expect(link_json["is_preorder"]).to be(true) expect(link_json["is_in_preorder_state"]).to be(true) expect(link_json["release_at"].present?).to be(true) end it "includes the preorder_link information for a released link" do @preorder_link = create(:preorder_link, link: @product, release_at: 2.days.from_now) # can't create a preorder with a release_at in the past @preorder_link.update(release_at: Date.yesterday) link_json = @product.as_json expect(link_json["is_preorder"]).to be(true) expect(link_json["is_in_preorder_state"]).to be(false) expect(link_json["release_at"].present?).to be(true) end it "includes deprecated `custom_delivery_url` attribute" do expect(@product.as_json).to include("custom_delivery_url" => nil) end it "includes deprecated `url` attribute" do expect(@product.as_json(api_scopes: %w[view_public edit_products])).to include("url" => nil) end describe "as_json_for_api" do context "for a product with variants" do let(:product) { create(:product) } let(:category) { create(:variant_category, link: product, title: "Color") } let!(:blue_variant) { create(:variant, variant_category: category, name: "Blue") } let!(:green_variant) { create(:variant, variant_category: category, name: "Green") } it "returns deprecated `url` attribute" do result = product.as_json(api_scopes: %w[view_public edit_products]) expect(result.dig("variants", 0, :options)).to include( hash_including(name: "Blue", url: nil), hash_including(name: "Green", url: nil), ) end end context "when user has purchasing_power_parity_enabled" do before do @product.user.update!(purchasing_power_parity_enabled: true) @product.update!(price_cents: 300) PurchasingPowerParityService.new.set_factor("MX", 0.5) end it "includes PPP prices for every country" do result = @product.as_json(api_scopes: %w[view_sales]) expect(result["purchasing_power_parity_prices"].keys).to eq(Compliance::Countries.mapping.keys) expect(result["purchasing_power_parity_prices"]["MX"]).to eq(150) end context "when injecting a preloaded factors" do it "includes PPP prices for every country without calling PurchasingPowerParityService" do expect_any_instance_of(PurchasingPowerParityService).not_to receive(:get_all_countries_factors) result = @product.as_json( api_scopes: %w[view_sales], preloaded_ppp_factors: { "MX" => 0.8, "CA" => 0.9 } ) expect(result["purchasing_power_parity_prices"]).to eq("MX" => 240, "CA" => 270) end end end context "when user has purchasing_power_parity_enabled and product has purchasing_power_parity_disabled" do before do @product.user.update!(purchasing_power_parity_enabled: true) @product.update!(price_cents: 300, purchasing_power_parity_disabled: true) PurchasingPowerParityService.new.set_factor("MX", 0.5) end it "doesn't include PPP prices for every country" do result = @product.as_json(api_scopes: %w[view_sales]) expect(result["purchasing_power_parity_prices"]).to be_nil end end context "when api_scopes includes 'view_sales'", :sidekiq_inline, :elasticsearch_wait_for_refresh do it "includes sales data" do product = create(:product) create(:purchase, link: product) create(:failed_purchase, link: product) result = product.as_json(api_scopes: %w[view_sales]) expect(result["sales_count"]).to eq(1) expect(result["sales_usd_cents"]).to eq(100) end end end describe "as_json_for_mobile_api" do it "returns proper json for a product" do link = create(:product, preview: fixture_file_upload("kFDzu.png", "image/png"), content_updated_at: Time.current) json_hash = link.as_json(mobile: true) %w[name description unique_permalink created_at updated_at content_updated_at preview_url].each do |attr| attr = attr.to_sym unless %w[name description unique_permalink].include?(attr) expect(json_hash[attr]).to eq link.send(attr) end expect(json_hash[:preview_oembed_url]).to eq "" expect(json_hash[:preview_height]).to eq 210 expect(json_hash[:preview_width]).to eq 670 expect(json_hash[:has_rich_content]).to eq true end it "returns thumbnail information" do thumbnail = create(:thumbnail) product = thumbnail.product json_hash = product.as_json(mobile: true) expect(json_hash[:thumbnail_url]).to eq thumbnail.url end it "returns creator info for a product" do user = create(:named_user, :with_avatar) product = create(:product, user:) json_hash = product.as_json(mobile: true) expect(json_hash[:creator_name]).to eq user.name_or_username expect(json_hash[:creator_profile_picture_url]).to eq user.avatar_url expect(json_hash[:creator_profile_url]).to eq user.profile_url end it "returns a blank preview_url if there is no preview for the product" do link = create(:product, preview: fixture_file_upload("kFDzu.png", "image/png")) link.asset_previews.each { |preview| preview.update(deleted_at: Time.current) } json_hash = link.as_json(mobile: true) expect(json_hash[:preview_url]).to eq "" end it "returns proper json for a product with a youtube preview" do link = create(:product, preview_url: "https://youtu.be/blSl487coFg") expect(link.as_json(mobile: true)[:preview_oembed_url]).to eq("https://www.youtube.com/embed/blSl487coFg?feature=oembed&showinfo=0&controls=0&rel=0&enablejsapi=1") end it "returns proper json for a product with a soundcloud preview" do link = create(:product, preview_url: "https://soundcloud.com/cade-turner/cade-turner-symphony-of-light", user: create(:user, username: "elliomax")) json_hash = link.as_json(mobile: true) %w[name description unique_permalink created_at updated_at].each do |attr| attr = attr.to_sym unless %w[name description unique_permalink].include?(attr) expect(json_hash[attr]).to eq link.send(attr) end expect(json_hash[:creator_name]).to eq "elliomax" expect(json_hash[:preview_url]).to eq "https://i1.sndcdn.com/artworks-000053047348-b62qv1-t500x500.jpg" expect(json_hash[:preview_oembed_url]).to eq( "https://w.soundcloud.com/player/?visual=true&url=https%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F101276036&auto_play=false" \ "&show_artwork=false&show_comments=false&buying=false&sharing=false&download=false&show_playcount=false&show_user=false&liking=false&maxwidth=670" ) end it "returns proper json for a product with a vimeo preview" do link = create(:product, preview_url: "https://vimeo.com/30698649", user: create(:user, username: "elliomax")) json_hash = link.as_json(mobile: true) %w[name description unique_permalink created_at updated_at].each do |attr| attr = attr.to_sym unless %w[name description unique_permalink].include?(attr) expect(json_hash[attr]).to eq link.send(attr) end expect(json_hash[:creator_name]).to eq "elliomax" expect(json_hash[:preview_url]).to eq "https://i.vimeocdn.com/video/212645621-df44232fa6e6b46afd643f7e733a7bfe2cc7cb97486158998bfbc601231722e9-d_640?region=us" expect(json_hash[:preview_oembed_url]).to eq "https://player.vimeo.com/video/30698649?app_id=122963" end it "does not return preview heights less than 204 pixels" do link = create(:product, preview: fixture_file_upload("kFDzu.png", "image/png")) allow_any_instance_of(Link).to receive(:preview_height).and_return(100) json_hash = link.as_json(mobile: true) %w[name description unique_permalink created_at updated_at preview_url].each do |attr| attr = attr.to_sym unless %w[name description unique_permalink].include?(attr) expect(json_hash[attr]).to eq link.send(attr) end expect(json_hash[:creator_name]).to eq link.user.username expect(json_hash[:preview_oembed_url]).to eq "" expect(json_hash[:preview_height]).to eq 0 expect(json_hash[:preview_width]).to eq 670 end it "returns 'has_rich_content' true" do product = create(:product) expect(product.as_json(mobile: true)[:has_rich_content]).to eq(true) end end describe "as_json_variant_details_only" do context "for a product with variants" do it "includes a hash of variants data under 'categories'" do circle_integration = create(:circle_integration) discord_integration = create(:discord_integration) product = create(:product, active_integrations: [circle_integration, discord_integration]) category = create(:variant_category, link: product, title: "Color") blue_variant = create(:variant, variant_category: category, name: "Blue", active_integrations: [circle_integration]) green_variant = create(:variant, variant_category: category, name: "Green", active_integrations: [discord_integration]) result = product.as_json(variant_details_only: true) expect(result).to eq( categories: { category.external_id => { title: "Color", options: { blue_variant.external_id => { "option" => blue_variant.name, "name" => blue_variant.name, "description" => nil, "id" => blue_variant.external_id, "max_purchase_count" => nil, "price_difference_cents" => 0, "price_difference_in_currency_units" => 0.0, "showing" => false, "quantity_left" => nil, "amount_left_title" => "", "displayable" => blue_variant.name, "sold_out" => false, "price_difference" => "0", "currency_symbol" => "$", "product_files_ids" => [], "integrations" => { "circle" => true, "discord" => false, "zoom" => false, "google_calendar" => false }, }, green_variant.external_id => { "option" => green_variant.name, "name" => green_variant.name, "description" => nil, "id" => green_variant.external_id, "max_purchase_count" => nil, "price_difference_cents" => 0, "price_difference_in_currency_units" => 0.0, "showing" => false, "quantity_left" => nil, "amount_left_title" => "", "displayable" => green_variant.name, "sold_out" => false, "price_difference" => "0", "currency_symbol" => "$", "product_files_ids" => [], "integrations" => { "circle" => false, "discord" => true, "zoom" => false, "google_calendar" => false }, } } } }, skus: {}, skus_enabled: false ) end it "sets category title to \"Version\" if there is no title" do product = create(:product) category = create(:variant_category, link: product, title: "") result = product.as_json(variant_details_only: true) expect(result).to eq( categories: { category.external_id => { title: "Version", options: {} } }, skus: {}, skus_enabled: false ) end end context "for a tiered membership" do it "includes a hash of tier data under 'categories'" do circle_integration = create(:circle_integration) discord_integration = create(:discord_integration) product = create(:membership_product, name: "My Membership", active_integrations: [circle_integration, discord_integration]) category = product.tier_category first_tier = category.variants.first first_tier.active_integrations << circle_integration second_tier = create(:variant, variant_category: category, name: "2nd Tier", active_integrations: [discord_integration]) result = product.as_json(variant_details_only: true) expect(result).to eq( categories: { category.external_id => { title: "Tier", options: { first_tier.external_id => { "option" => "Untitled", "name" => "My Membership", "description" => nil, "id" => first_tier.external_id, "max_purchase_count" => nil, "price_difference_cents" => nil, "price_difference_in_currency_units" => 0.0, "showing" => true, "quantity_left" => nil, "amount_left_title" => "", "displayable" => "Untitled", "sold_out" => false, "price_difference" => 0, "currency_symbol" => "$", "product_files_ids" => [], "is_customizable_price" => false, "recurrence_price_values" => { "monthly" => { enabled: true, price: "1", price_cents: 100, suggested_price_cents: nil }, "quarterly" => { enabled: false }, "biannually" => { enabled: false }, "yearly" => { enabled: false }, "every_two_years" => { enabled: false }, }, "integrations" => { "circle" => true, "discord" => false, "zoom" => false, "google_calendar" => false }, }, second_tier.external_id => { "option" => second_tier.name, "name" => second_tier.name, "description" => nil, "id" => second_tier.external_id, "max_purchase_count" => nil, "price_difference_cents" => 0, "price_difference_in_currency_units" => 0.0, "showing" => false, "quantity_left" => nil, "amount_left_title" => "", "displayable" => second_tier.name, "sold_out" => false, "price_difference" => "0", "currency_symbol" => "$", "product_files_ids" => [], "is_customizable_price" => false, "recurrence_price_values" => { "monthly" => { enabled: false }, "quarterly" => { enabled: false }, "biannually" => { enabled: false }, "yearly" => { enabled: false }, "every_two_years" => { enabled: false }, }, "integrations" => { "circle" => false, "discord" => true, "zoom" => false, "google_calendar" => false }, } } } }, skus: {}, skus_enabled: false ) end end context "for a product with skus_enabled" do it "includes a hash of SKUs data under 'skus'" do product = create(:physical_product) category_1 = create(:variant_category, link: product, title: "Color") category_2 = create(:variant_category, link: product, title: "Size") skus_title = "#{category_1.title} - #{category_2.title}" sku = create(:sku, link: product, name: "Blue - large") result = product.as_json(variant_details_only: true) expect(result).to eq( categories: { category_1.external_id => { title: category_1.title, options: {} }, category_2.external_id => { title: category_2.title, options: {} } }, skus: { sku.external_id => { "option" => sku.name, "name" => sku.name, "description" => nil, "id" => sku.external_id, "max_purchase_count" => nil, "price_difference_cents" => 0, "price_difference_in_currency_units" => 0.0, "showing" => false, "quantity_left" => nil, "amount_left_title" => "", "displayable" => sku.name, "sold_out" => false, "price_difference" => "0", "currency_symbol" => "$", "product_files_ids" => [], "integrations" => { "circle" => false, "discord" => false, "zoom" => false, "google_calendar" => false }, } }, skus_title:, skus_enabled: true ) end end context "for a product without variants" do it "returns empty objects" do product = create(:product) result = product.as_json(variant_details_only: true) expect(result).to eq( categories: {}, skus: {}, skus_enabled: false ) end end end describe "recommendable attribute" do it "returns true if the product is recommendable" do product = create(:product, :recommendable) json = product.as_json expect(json["recommendable"]).to eq true end it "returns false otherwise" do product = create(:product) json = product.as_json expect(json["recommendable"]).to eq false end end describe "rated_as_adult attribute" do it "returns true if the product is rated_as_adult" do product = create(:product, is_adult: true) json = product.as_json expect(json["rated_as_adult"]).to eq true end it "returns false otherwise" do product = create(:product) json = product.as_json expect(json["rated_as_adult"]).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/concerns/user/payout_info_spec.rb
spec/models/concerns/user/payout_info_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::PayoutInfo do let(:user) { create(:user, payment_address: "test@example.com", payouts_paused_internally: true) } let(:manual_payout_end_date) { Date.today } before do allow(User::PayoutSchedule).to receive(:manual_payout_end_date).and_return(manual_payout_end_date) end describe "#payout_info" do let!(:bank_account) { create(:uk_bank_account, user:) } let!(:comment) { create(:comment, commentable: user, comment_type: Comment::COMMENT_TYPE_PAYOUTS_PAUSED, content: "Paused due to review") } it "includes payout information" do result = user.payout_info expect(result[:active_bank_account]).to eq( "type" => bank_account.type, "account_holder_full_name" => bank_account.account_holder_full_name, "formatted_account" => bank_account.formatted_account ) expect(result[:payment_address]).to eq("test@example.com") expect(result[:payouts_paused_by_source]).to eq(User::PAYOUT_PAUSE_SOURCE_ADMIN) expect(result[:payouts_paused_for_reason]).to eq("Paused due to review") end context "when there is no active bank account" do before do bank_account.destroy! end it "returns nil for active_bank_account" do result = user.payout_info expect(result[:active_bank_account]).to be_nil end end context "when there are no payouts_paused comments" do let!(:comment) { nil } it "returns nil for payouts_paused_for_reason" do result = user.payout_info expect(result[:payouts_paused_for_reason]).to be_nil end end context "when last payout is nil" do let!(:stripe_account) { create(:merchant_account, user:) } before do allow(user).to receive(:unpaid_balance_cents_up_to_date).with(manual_payout_end_date).and_return(10_000) end context "when user is payable via stripe from admin" do before do allow(Payouts).to receive(:is_user_payable) .with(user, manual_payout_end_date, processor_type: PayoutProcessorType::STRIPE, from_admin: true) .and_return(true) allow(Payouts).to receive(:is_user_payable) .with(user, manual_payout_end_date, processor_type: PayoutProcessorType::PAYPAL, from_admin: true) .and_return(false) allow(Payouts).to receive(:is_user_payable) .with(user, manual_payout_end_date, processor_type: PayoutProcessorType::STRIPE) .and_return(true) allow(user).to receive(:unpaid_balance_cents_up_to_date_held_by_gumroad).with(manual_payout_end_date).and_return(5_000) allow(user).to receive(:unpaid_balance_holding_cents_up_to_date_held_by_stripe).with(manual_payout_end_date).and_return(5_000) end it "includes manual payout info with stripe information" do result = user.payout_info expect(result[:manual_payout_info]).to eq( stripe: { unpaid_balance_held_by_gumroad: "$50", unpaid_balance_held_by_stripe: "50 USD" }, paypal: nil, unpaid_balance_up_to_date: 10_000, currency: stripe_account.currency, manual_payout_period_end_date: manual_payout_end_date, ask_confirmation: false ) end end context "when user is payable via paypal from admin" do before do allow(Payouts).to receive(:is_user_payable) .with(user, manual_payout_end_date, processor_type: PayoutProcessorType::STRIPE, from_admin: true) .and_return(false) allow(Payouts).to receive(:is_user_payable) .with(user, manual_payout_end_date, processor_type: PayoutProcessorType::PAYPAL, from_admin: true) .and_return(true) allow(Payouts).to receive(:is_user_payable) .with(user, manual_payout_end_date, processor_type: PayoutProcessorType::STRIPE) .and_return(false) allow(Payouts).to receive(:is_user_payable) .with(user, manual_payout_end_date, processor_type: PayoutProcessorType::PAYPAL) .and_return(true) allow(user).to receive(:should_paypal_payout_be_split?).and_return(true) allow(PaypalPayoutProcessor).to receive(:split_payment_by_cents).with(user).and_return(5_000) end it "includes manual payout info with paypal information" do result = user.payout_info expect(result[:manual_payout_info]).to eq( stripe: nil, paypal: { should_payout_be_split: true, split_payment_by_cents: 5_000 }, unpaid_balance_up_to_date: 10_000, currency: stripe_account.currency, manual_payout_period_end_date: manual_payout_end_date, ask_confirmation: false ) end end context "when user is not payable via stripe or paypal from admin" do before do allow(Payouts).to receive(:is_user_payable) .with(user, manual_payout_end_date, processor_type: PayoutProcessorType::STRIPE, from_admin: true) .and_return(false) allow(Payouts).to receive(:is_user_payable) .with(user, manual_payout_end_date, processor_type: PayoutProcessorType::PAYPAL, from_admin: true) .and_return(false) end it "does not include manual payout info" do result = user.payout_info expect(result[:manual_payout_info]).to be_nil end end end context "when last payout exists" do let!(:payment) { create(:payment, user:) } it "does not include manual payout info" do result = user.payout_info expect(result[:manual_payout_info]).to be_nil end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/user/team_spec.rb
spec/models/concerns/user/team_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::Team do let(:user) { create(:user) } let(:other_seller) { create(:user) } describe "#member_of?" do context "with self as seller" do it "returns true" do expect(user.member_of?(user)).to be(true) end end context "with other seller as seller" do it "returns false without team membership" do expect(user.member_of?(other_seller)).to be(false) end context "with deleted team membership" do let(:team_membership) { create(:team_membership, user:, seller: other_seller) } before do team_membership.update_as_deleted! end it "returns false" do expect(user.member_of?(other_seller)).to be(false) end end context "with alive team membership" do before do create(:team_membership, user:, seller: other_seller) end it "returns true" do expect(user.member_of?(other_seller)).to be(true) end end end end describe "#role_admin_for?" do it "returns true for owner" do expect(user.role_admin_for?(user)).to be(true) end context "with alive team membership" do context "with admin role" do before do create(:team_membership, user:, seller: other_seller) end it "returns true for other_seller" do expect(user.role_admin_for?(other_seller)).to be(true) end end TeamMembership::ROLES.excluding(TeamMembership::ROLE_OWNER, TeamMembership::ROLE_ADMIN).each do |role| context "with #{role} role" do before do create(:team_membership, user:, seller: other_seller, role:) end it "returns false for other_seller" do expect(user.role_admin_for?(other_seller)).to be(false) end end end end end TeamMembership::ROLES.excluding(TeamMembership::ROLE_OWNER, TeamMembership::ROLE_ADMIN).each do |role| describe "#role_#{role}_for?" do it "returns true for owner" do expect(user.send(:"role_#{role}_for?", user)).to be(true) end context "with alive team membership" do context "with #{role} role" do before do create(:team_membership, user:, seller: other_seller, role:) end it "returns true for other_seller" do expect(user.send(:"role_#{role}_for?", other_seller)).to be(true) end end context "with admin role" do before do create(:team_membership, user:, seller: other_seller) end it "returns false for other_seller" do expect(user.send(:"role_#{role}_for?", other_seller)).to be(false) end end end end end describe "#user_memberships" do context "with no team_membership records" do it "returns empty collection" do expect(user.user_memberships.count).to eq(0) end end context "with team_membership records" do let!(:owner_membership) { TeamMembership.create!(user:, seller: user, role: TeamMembership::ROLE_OWNER) } let!(:admin_membership) { TeamMembership.create!(user:, seller: other_seller, role: TeamMembership::ROLE_ADMIN) } let!(:other_membership) { TeamMembership.create!(user: other_seller, seller: other_seller, role: TeamMembership::ROLE_OWNER) } it "returns correct association" do expect(user.reload.user_memberships).to eq([owner_membership, admin_membership]) expect(owner_membership.user).to eq(user) expect(admin_membership.user).to eq(user) end end end describe "#seller_memberships" do context "with no team_membership records" do it "returns empty collection" do expect(user.seller_memberships.count).to eq(0) end end context "with team_membership records" do let!(:owner_membership) { TeamMembership.create!(user:, seller: user, role: TeamMembership::ROLE_OWNER) } let!(:admin_membership) { TeamMembership.create!(user:, seller: other_seller, role: TeamMembership::ROLE_ADMIN) } let!(:other_membership) { TeamMembership.create!(user: other_seller, seller: other_seller, role: TeamMembership::ROLE_OWNER) } it "returns correct association" do expect(user.seller_memberships).to eq([owner_membership]) expect(owner_membership.seller).to eq(user) end end end describe "#create_owner_membership_if_needed!" do context "when owner membership is missing" do it "creates owner membership" do expect do user.create_owner_membership_if_needed! end.to change { user.user_memberships.count }.by(1) owner_membership = user.user_memberships.last expect(owner_membership.role_owner?).to be(true) end end context "when owner membership exists" do before do user.user_memberships.create!(seller: user, role: TeamMembership::ROLE_OWNER) end it "doesn't create a record" do expect do user.create_owner_membership_if_needed! end.not_to change { user.user_memberships.count } end end end describe "#gumroad_account?" do context "when the user's email is not #{ApplicationMailer::ADMIN_EMAIL}" do it "returns false" do user = create(:user) expect(user.gumroad_account?).to be(false) end end context "when the user's email is #{ApplicationMailer::ADMIN_EMAIL}" do it "returns true" do user = create(:user, email: ApplicationMailer::ADMIN_EMAIL) expect(user.gumroad_account?).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/concerns/user/low_balance_fraud_check_spec.rb
spec/models/concerns/user/low_balance_fraud_check_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::LowBalanceFraudCheck do before do @creator = create(:user) @purchase = create(:refunded_purchase, link: create(:product, user: @creator)) end describe "#enable_refunds!" do before do @creator.refunds_disabled = true end it "enables refunds for the creator" do @creator.enable_refunds! expect(@creator.reload.refunds_disabled?).to eq(false) end it "is called when a creator is marked as compliant" do @creator.mark_compliant!(author_name: "test") expect(@creator.reload.refunds_disabled?).to eq(false) end end describe "#disable_refunds!" do before do @creator.refunds_disabled = false end it "disables refunds for the creator" do @creator.disable_refunds! expect(@creator.reload.refunds_disabled?).to eq(true) end end describe "#check_for_low_balance_and_probate" do context "when the unpaid balance is above threshold" do before do allow(@creator).to receive(:unpaid_balance_cents).and_return(-40_00) end it "doesn't probate the creator" do @creator.check_for_low_balance_and_probate(@purchase.id) expect(@creator.reload.on_probation?).to eq(false) end end context "when the unpaid balance is below threshold" do before do allow(@creator).to receive(:unpaid_balance_cents).and_return(-200_00) end context "when the creator is under enforcement action" do context "when suspended for fraud" do before do @creator.flag_for_fraud!(author_name: "admin", content: "fraud detected") @creator.suspend_for_fraud!(author_name: "admin", content: "confirmed fraud") end it "does not probate the creator" do expect do @creator.check_for_low_balance_and_probate(@purchase.id) end.to have_enqueued_mail(AdminMailer, :low_balance_notify).with(@creator.id, @purchase.id) expect(@creator.reload.suspended_for_fraud?).to eq(true) expect(@creator.reload.on_probation?).to eq(false) end end context "when suspended for TOS violation" do before do product = create(:product, user: @creator) @creator.flag_for_tos_violation!(author_name: "admin", content: "tos violation", product_id: product.id) @creator.suspend_for_tos_violation!(author_name: "admin", content: "confirmed tos violation") end it "does not probate the creator" do expect do @creator.check_for_low_balance_and_probate(@purchase.id) end.to have_enqueued_mail(AdminMailer, :low_balance_notify).with(@creator.id, @purchase.id) expect(@creator.reload.suspended_for_tos_violation?).to eq(true) expect(@creator.reload.on_probation?).to eq(false) end end end context "when the creator is not on probation" do context "when the creator is not recently probated for low balance" do it "probates the creator" do expect do @creator.check_for_low_balance_and_probate(@purchase.id) end.to have_enqueued_mail(AdminMailer, :low_balance_notify).with(@creator.id, @purchase.id) expect(@creator.reload.on_probation?).to eq(true) expect(@creator.comments.last.content).to eq("Probated (payouts suspended) automatically on #{Time.current.to_fs(:formatted_date_full_month)} because of suspicious refund activity") end end context "when the creator is recently probated" do context "when creator was probated before LOW_BALANCE_PROBATION_WAIT_TIME" do before do @creator.send(:disable_refunds_and_put_on_probation!) comment = @creator.comments.with_type_on_probation.order(:created_at).last comment.update_attribute(:created_at, 3.months.ago) @creator.mark_compliant(author_name: "test") end it "probates the creator" do expect do @creator.check_for_low_balance_and_probate(@purchase.id) end.to have_enqueued_mail(AdminMailer, :low_balance_notify).with(@creator.id, @purchase.id) expect(@creator.reload.on_probation?).to eq(true) expect(@creator.comments.last.content).to eq("Probated (payouts suspended) automatically on #{Time.current.to_fs(:formatted_date_full_month)} because of suspicious refund activity") end end context "when creator was probated after LOW_BALANCE_PROBATION_WAIT_TIME" do before do @creator.send(:disable_refunds_and_put_on_probation!) comment = @creator.comments.with_type_on_probation.order(:created_at).last comment.update_attribute(:created_at, 1.months.ago) @creator.mark_compliant(author_name: "test") end it "doesn't probate the creator" do expect do @creator.check_for_low_balance_and_probate(@purchase.id) end.to have_enqueued_mail(AdminMailer, :low_balance_notify).with(@creator.id, @purchase.id) expect(@creator.reload.on_probation?).to eq(false) end end end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/user/social_google_mobile_spec.rb
spec/models/concerns/user/social_google_mobile_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::SocialGoogleMobile do let(:key_source) { instance_double(Google::Auth::IDTokens::JwkHttpKeySource) } let(:verifier) { instance_double(Google::Auth::IDTokens::Verifier) } let(:user) { create(:user) } let(:payload) { { "aud" => GlobalConfig.get("GOOGLE_CLIENT_ID"), "email" => user.email, "email_verified" => true } } before do allow(Google::Auth::IDTokens::JwkHttpKeySource).to receive(:new).and_return(key_source) allow(Google::Auth::IDTokens::Verifier).to receive(:new).and_return(verifier) allow(verifier).to receive(:verify).and_return(payload) end describe ".find_for_google_mobile_auth" do context "when audience matches the client_id" do context "when the email is verified" do it "returns the user" do expect(User.find_for_google_mobile_auth(google_id_token: "token")).to eq user end end context "when the email is not verified" do let(:payload) { { "aud" => GlobalConfig.get("GOOGLE_CLIENT_ID"), "email" => user.email, "email_verified" => false } } it "returns nil" do expect(User.find_for_google_mobile_auth(google_id_token: "token")).to be_nil end end end context "when the audience does not match the client_id" do let(:payload) { { "aud" => "different_client_id", "email" => user.email } } it "returns nil" do expect(User.find_for_google_mobile_auth(google_id_token: "token")).to be_nil end end context "when the token is invalid" do before do allow(verifier).to receive(:verify).and_raise(Google::Auth::IDTokens::ExpiredTokenError) end it "returns nil" do expect(User.find_for_google_mobile_auth(google_id_token: "token")).to be_nil end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/user/as_json_spec.rb
spec/models/concerns/user/as_json_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::AsJson do describe "#as_json" do let(:user) { create(:named_user, *user_traits) } let(:user_traits) { [] } let(:options) { {} } subject(:as_json) { user.as_json(options) } before do create(:product, user:, custom_permalink: "boo") end context "for api :edit_products" do let(:options) { { api_scopes: ["edit_products"] } } it "returns the correct hash" do %w[name email].each do |key| expect(as_json.key?(key)).to be(true) end expect(as_json["links"]).to eq(["boo"]) end it "returns an alphanumeric id in all situations" do expect(as_json["user_id"]).to eq ObfuscateIds.encrypt(user.id) end end context "for public" do it "returns the correct hash" do expect(as_json.key?("name")).to be(true) end it "returns an alphanumeric id" do expect(as_json["user_id"]).to eq ObfuscateIds.encrypt(user.id) end end context "if the 'view_sales' API scope is present" do let(:options) { { api_scopes: ["view_sales"] } } it "returns the email" do expect(as_json.key?("email")).to be(true) end end context "for 'view_profile' scope" do let(:options) { { api_scopes: ["view_profile"] } } it "returns values for 'view_profile' scope" do expect(as_json).to include("email", "profile_url", "display_name", "id") end end describe "returned keys" do subject(:returned_keys) { as_json.keys.collect(&:to_s) } let(:options) { {} } let(:common_keys) { %w[name bio twitter_handle id user_id url links] } let(:api_scope_keys) { %w[currency_type profile_url email] } let(:internal_use_keys) { %w[created_at sign_in_count current_sign_in_at last_sign_in_at current_sign_in_ip last_sign_in_ip purchases_count successful_purchases_count] } context "when no options are provided" do context "when the bio and twitter_handle are NOT set" do it "returns common values" do expect(returned_keys).to contain_exactly(*common_keys - %w[bio twitter_handle]) end end context "when the bio is set" do let(:user_traits) { [:with_bio] } it "returns common values expect twitter_handle" do expect(returned_keys).to contain_exactly(*common_keys - %w[twitter_handle]) end end context "when the twitter_handle is set" do let(:user_traits) { [:with_twitter_handle] } it "returns common values expect bio" do expect(returned_keys).to contain_exactly(*common_keys - %w[bio]) end end end context "when only the :internal_use option is provided" do let(:options) { { internal_use: true } } it { expect(returned_keys).to contain_exactly(*(common_keys + api_scope_keys + internal_use_keys)) } end %w[edit_products view_sales revenue_share ifttt view_profile].each do |api_scope| context "when the '#{api_scope}' api scope is provided" do context "when :internal_use is provided" do let(:options) { { api_scopes: [api_scope], internal_use: true } } if api_scope == "view_profile" it { expect(returned_keys).to contain_exactly(*(common_keys + (api_scope_keys + %w[display_name]) + internal_use_keys)) } else it { expect(returned_keys).to contain_exactly(*(common_keys + api_scope_keys + internal_use_keys)) } end end context "when :internal_use is NOT provided" do let(:options) { { api_scopes: [api_scope] } } if api_scope == "view_profile" it { expect(returned_keys).to contain_exactly(*(common_keys + (api_scope_keys + %w[display_name]))) } else it { expect(returned_keys).to contain_exactly(*(common_keys + api_scope_keys)) } end end end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/user/taxation_spec.rb
spec/models/concerns/user/taxation_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::Taxation do include PaymentsHelper before do @user = create(:user) end describe "#eligible_for_1099_k?", :vcr do let(:year) { Date.current.year } before do create(:merchant_account_stripe, user: @user) create(:tos_agreement, user: @user) 10.times do create(:purchase, seller: @user, total_transaction_cents: [10_00, 15_00, 20_00].sample, created_at: Date.current.in_time_zone(@user.timezone), succeeded_at: Date.current.in_time_zone(@user.timezone), link: create(:product, user: @user)) end # To simulate eligibility stub_const("#{described_class}::MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING", 100_00) end context "when user is not from the US" do before do create(:user_compliance_info_singapore, user: @user) end it "returns false" do expect(@user.eligible_for_1099_k?(year)).to eq(false) end end context "when user is from an invalid compliance country" do before do create(:user_compliance_info, user: @user, country: "Aland Islands") end it "returns false" do expect(@user.eligible_for_1099_k?(year)).to eq(false) end end context "when user doesn't meet the minimum sales amount" do it "returns false" do stub_const("User::Taxation::MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING", 100_000) expect(@user.eligible_for_1099_k?(year)).to eq(false) end end context "when user is suspended" do before do create(:user_compliance_info, user: @user) @user.user_risk_state = "suspended_for_fraud" @user.save! end it "returns false" do expect(@user.eligible_for_1099_k?(year)).to eq(false) end end context "when user is compliant" do before do create(:user_compliance_info, user: @user) end it "returns true" do expect(@user.eligible_for_1099_k?(year)).to eq(true) end end context "when sales amount is above threshold but non-refunded sales amount is not" do before do create(:user_compliance_info, user: @user) @user.sales.each { _1.update!(stripe_refunded: true) } end it "returns false" do expect(@user.eligible_for_1099_k?(year)).to eq(false) end end context "when sales amount is above threshold but non-disputed sales amount is not" do before do create(:user_compliance_info, user: @user) @user.sales.each { _1.update!(chargeback_date: Date.current) } end it "returns false" do expect(@user.eligible_for_1099_k?(year)).to eq(false) end end context "when sales amount is above threshold but non-Connect sales amount is not" do before do create(:user_compliance_info, user: @user) @user.sales.each { _1.id % 2 == 0 ? _1.update!(paypal_order_id: SecureRandom.hex) : _1.update!(merchant_account_id: create(:merchant_account_stripe_connect, user: @user).id) } stub_const("#{described_class}::MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING", 1) end it "returns false" do expect(@user.eligible_for_1099_k?(year)).to eq(false) end end context "when sales amount is above state filing threshold" do before do create(:user_compliance_info, user: @user, state: "VA") stub_const("#{described_class}::MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING", 1000_00) stub_const("#{described_class}::MIN_SALE_AMOUNTS_FOR_1099_K_STATE_FILINGS", { "VA" => 60_00 }) end it "returns true" do expect(@user.eligible_for_1099_k_federal_filing?(year)).to eq(false) expect(@user.eligible_for_1099_k_state_filing?(year)).to eq(true) expect(@user.eligible_for_1099_k?(year)).to eq(true) end end end describe "#eligible_for_1099_misc?", :vcr do let(:year) { Date.current.year } before do create(:merchant_account_stripe, user: @user) create(:tos_agreement, user: @user) @affiliate = create( :direct_affiliate, affiliate_user: @user, affiliate_basis_points: [15_00, 20_00].sample ) 10.times do create(:purchase, price_cents: 100_00, affiliate: @affiliate, created_at: Date.current.in_time_zone(@user.timezone), succeeded_at: Date.current.in_time_zone(@user.timezone)) end # To simulate eligibility stub_const("#{described_class}::MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING", 100_00) end context "when user is not from the US" do before do create(:user_compliance_info_singapore, user: @user) end it "returns false" do expect(@user.eligible_for_1099_misc?(year)).to eq(false) end end context "when user is from an invalid compliance country" do before do create(:user_compliance_info, user: @user, country: "Aland Islands") end it "returns false" do expect(@user.eligible_for_1099_misc?(year)).to eq(false) end end context "when user doesn't meet the minimum affiliate sales amount" do it "returns false" do stub_const("User::Taxation::MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING", 250_00) expect(@user.eligible_for_1099_misc?(year)).to eq(false) end end context "when user is suspended" do before do @user.user_risk_state = "suspended_for_fraud" @user.save! end it "returns false" do expect(@user.eligible_for_1099_misc?(year)).to eq(false) end end context "when user is compliant" do before do create(:user_compliance_info, user: @user) end it "returns true" do expect(@user.eligible_for_1099_misc?(year)).to eq(true) end end context "when affiliate sales amount is above threshold but non-refunded amount is not" do before do create(:user_compliance_info, user: @user) Purchase.where(affiliate_id: @affiliate.id).each { _1.update!(stripe_refunded: true) } end it "returns false" do expect(@user.eligible_for_1099_misc?(year)).to eq(false) end end context "when affiliate sales amount is above threshold but non-disputed amount is not" do before do create(:user_compliance_info, user: @user) Purchase.where(affiliate_id: @affiliate.id).each { _1.update!(chargeback_date: Date.current) } end it "returns false" do expect(@user.eligible_for_1099_misc?(year)).to eq(false) end end context "when affiliate amount is above state filing threshold" do before do create(:user_compliance_info, user: @user, state: "AR") stub_const("#{described_class}::MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING", 1000_00) stub_const("#{described_class}::MIN_AFFILIATE_AMOUNTS_FOR_1099_MISC_STATE_FILINGS", { "AR" => 10_00 }) end it "returns true" do expect(@user.eligible_for_1099_misc_federal_filing?(year)).to eq(false) expect(@user.eligible_for_1099_misc_state_filing?(year)).to eq(true) expect(@user.eligible_for_1099_misc?(year)).to eq(true) end end end describe "#eligible_for_1099?", :vcr do let(:year) { Date.current.year } before do allow_any_instance_of(User).to receive(:is_a_non_suspended_creator_from_usa?).and_return(true) end it "returns true if eligible for 1099-K and not 1099-MISC" do allow_any_instance_of(User).to receive(:eligible_for_1099_k?).and_return(true) allow_any_instance_of(User).to receive(:eligible_for_1099_misc?).and_return(false) expect(create(:user).eligible_for_1099?(year)).to be true end it "returns true if eligible for 1099-MISC and not 1099-K" do allow_any_instance_of(User).to receive(:eligible_for_1099_k?).and_return(false) allow_any_instance_of(User).to receive(:eligible_for_1099_misc?).and_return(true) expect(create(:user).eligible_for_1099?(year)).to be true end it "returns false if eligible for neither 1099-K nor 1099-MISC" do allow_any_instance_of(User).to receive(:eligible_for_1099_k?).and_return(false) allow_any_instance_of(User).to receive(:eligible_for_1099_misc?).and_return(false) expect(create(:user).eligible_for_1099?(year)).to be false end it "returns true if eligible for both 1099-K and 1099-MISC" do allow_any_instance_of(User).to receive(:eligible_for_1099_k?).and_return(true) allow_any_instance_of(User).to receive(:eligible_for_1099_misc?).and_return(true) expect(create(:user).eligible_for_1099?(year)).to be true end end describe "#is_a_non_suspended_creator_from_usa?", :vcr do let(:year) { Date.current.year } context "when user is not from the US" do before do create(:user_compliance_info_singapore, user: @user) end it "returns false" do expect(@user.is_a_non_suspended_creator_from_usa?).to eq(false) end end context "when user is from an invalid compliance country" do before do create(:user_compliance_info, user: @user, country: "Aland Islands") end it "returns false" do expect(@user.is_a_non_suspended_creator_from_usa?).to eq(false) end end context "when user is compliant and from US" do before do create(:user_compliance_info, user: @user) end it "returns true" do expect(@user.is_a_non_suspended_creator_from_usa?).to eq(true) end end end describe "#from_us?" do context "when user is from the United States" do before do create(:user_compliance_info, user: @user) end it "returns true" do expect(@user.from_us?).to eq(true) end end context "when user is from Singapore" do before do create(:user_compliance_info_singapore, user: @user) end it "returns false" do expect(@user.from_us?).to eq(false) end end context "when user compliance is empty" do before do create(:user_compliance_info_empty, user: @user) end it "returns false" do expect(@user.from_us?).to eq(false) end end context "when user compliance is missing" do it "returns false" do expect(@user.from_us?).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/concerns/user/money_balance_spec.rb
spec/models/concerns/user/money_balance_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::MoneyBalance, :vcr do describe "balance_formatted" do before do @user = create(:user, unpaid_balance_cents: 1_00) end it "returns the user's balance" do expect(@user.unpaid_balance_cents).to eq 100 expect(@user.balance_formatted).to eq "$1" end end describe "#instantly_payable_unpaid_balances" do it "returns maximum unpaid balances whose sum is less than instantly payable amount available on Stripe" do user = create(:user) merchant_account = create(:merchant_account_stripe, user:) bal1 = create(:balance, user:, merchant_account:, date: Date.current - 3.days, amount_cents: 500_00, holding_amount_cents: 500_00) bal2 = create(:balance, user:, merchant_account:, date: Date.current - 2.days, amount_cents: 400_00, holding_amount_cents: 400_00) bal3 = create(:balance, user:, merchant_account:, date: Date.current - 1.days, amount_cents: 300_00, holding_amount_cents: 300_00) bal4 = create(:balance, user:, merchant_account:, date: Date.current, amount_cents: 200_00, holding_amount_cents: 200_00) bal5 = create(:balance, user:, date: Date.current - 3.days, amount_cents: 500_00, holding_amount_cents: 500_00) bal6 = create(:balance, user:, date: Date.current - 2.days, amount_cents: 500_00, holding_amount_cents: 500_00) bal7 = create(:balance, user:, date: Date.current - 1.days, amount_cents: 500_00, holding_amount_cents: 500_00) bal8 = create(:balance, user:, date: Date.current, amount_cents: 500_00, holding_amount_cents: 500_00) allow(StripePayoutProcessor).to receive(:instantly_payable_amount_cents_on_stripe).with(user).and_return(1400_00) expect(user.instantly_payable_unpaid_balances).to match_array([bal1, bal2, bal3, bal4, bal5, bal6, bal7, bal8]) allow(StripePayoutProcessor).to receive(:instantly_payable_amount_cents_on_stripe).with(user).and_return(1000_00) expect(user.instantly_payable_unpaid_balances).to match_array([bal1, bal2, bal5, bal6]) allow(StripePayoutProcessor).to receive(:instantly_payable_amount_cents_on_stripe).with(user).and_return(1200_00) expect(user.instantly_payable_unpaid_balances).to match_array([bal1, bal2, bal3, bal5, bal6, bal7]) allow(StripePayoutProcessor).to receive(:instantly_payable_amount_cents_on_stripe).with(user).and_return(600_00) expect(user.instantly_payable_unpaid_balances).to match_array([bal1, bal5]) allow(StripePayoutProcessor).to receive(:instantly_payable_amount_cents_on_stripe).with(user).and_return(1500_00) expect(user.instantly_payable_unpaid_balances).to match_array([bal1, bal2, bal3, bal4, bal5, bal6, bal7, bal8]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/user/followers_spec.rb
spec/models/concerns/user/followers_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::Followers do describe "#following" do let(:following_user) { create(:user, email: "follower@example.com") } let(:not_following_user) { create(:user) } let(:creator_one) { create(:user) } let(:creator_two) { create(:user) } let!(:following_relationship_one) { create(:active_follower, user: creator_one, email: "follower@example.com") } let!(:following_relationship_two) { create(:active_follower, user: creator_one, email: "different@example.com", follower_user_id: following_user.id) } let!(:following_relationship_three) { create(:deleted_follower, email: "follower@example.com") } let!(:following_relationship_four) { create(:active_follower, user: creator_two, email: "follower@example.com") } let!(:following_relationship_five) { create(:active_follower, user: following_user, email: "follower@example.com") } it "returns users being followed" do expect(following_user.following).to match_array([ { external_id: following_relationship_one.external_id, creator: creator_one }, { external_id: following_relationship_four.external_id, creator: creator_two }, ]) expect(not_following_user.following).to match_array([]) end end describe "#follower_by_email" do it "returns the active follower matching the provided email" do user = create(:user) active_follower = create(:active_follower, user:) expect(user.follower_by_email(active_follower.email)).to eq(active_follower) unconfirmed_follower = create(:follower, user:) expect(user.follower_by_email(unconfirmed_follower.email)).to eq(nil) deleted_follower = create(:deleted_follower, user:) expect(user.follower_by_email(deleted_follower.email)).to eq(nil) end end describe "#followed_by?" do it "returns true if user has confirmed follower with that email" do user = create(:user) active_follower = create(:active_follower, user:) expect(user.followed_by?(active_follower.email)).to eq(true) unconfirmed_follower = create(:follower, user:) expect(user.followed_by?(unconfirmed_follower.email)).to eq(false) deleted_follower = create(:deleted_follower, user:) expect(user.followed_by?(deleted_follower.email)).to eq(false) end end describe "#add_follower" do let(:followed_user) { create(:user) } let(:follower_email) { "follower@example.com" } let(:logged_in_user) { create(:user, email: follower_email) } let(:follow_source) { "welcome-greeter" } it "calls Follower::CreateService and returns the follower object" do expect(Follower::CreateService).to receive(:perform).with( followed_user:, follower_email:, follower_attributes: { source: follow_source }, logged_in_user: ).and_call_original follower = followed_user.add_follower(follower_email, source: follow_source, logged_in_user:) expect(follower).to be_kind_of(Follower) end it "updates source when the user is already following the same creator using the same email" do follower = create(:active_follower, user: followed_user, email: follower_email, follower_user_id: logged_in_user.id, source: Follower::From::FOLLOW_PAGE) expect do followed_user.add_follower(follower_email, source: Follower::From::CSV_IMPORT) end.to change { follower.reload.source }.from(Follower::From::FOLLOW_PAGE).to(Follower::From::CSV_IMPORT) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/user/social_apple_spec.rb
spec/models/concerns/user/social_apple_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::SocialApple do let(:user) { create(:user) } let(:id_token_double) { double(verify!: double, email_verified?: true, email: user.email) } describe ".find_for_apple_auth" do before do @apple_id_client = double("apple_id_client") allow(@apple_id_client).to receive(:authorization_code=) allow(AppleID::Client).to receive(:new).and_return(@apple_id_client) @access_token_double = double("access token") token_response_double = double(id_token: id_token_double, access_token: @access_token_double) allow(@apple_id_client).to receive(:access_token!).and_return(token_response_double) end shared_examples_for "finds user using Apple's authorization_code" do |app_type| context "when the email is verified" do it "finds the user using Apple authorization code" do expect(id_token_double).to receive(:verify!) do |options| expect(options[:client]).to eq @apple_id_client expect(options[:access_token]).to eq @access_token_double expect(options[:verify_signature]).to eq false end fetched_user = User.find_for_apple_auth(authorization_code: "auth_code", app_type:) expect(fetched_user).to eq user end end context "when the email is not verified" do let(:id_token_double) { double(verify!: double, email_verified?: false, email: user.email) } it "doesn't return the user" do fetched_user = User.find_for_apple_auth(authorization_code: "auth_code", app_type:) expect(fetched_user).to be_nil end end end context "when the request is from consumer app" do it "initializes AppleID client using consumer app credentials" do expect(AppleID::Client).to receive(:new) do |options| expect(options[:identifier]).to eq GlobalConfig.get("IOS_CONSUMER_APP_APPLE_LOGIN_IDENTIFIER") expect(options[:team_id]).to eq GlobalConfig.get("IOS_CONSUMER_APP_APPLE_LOGIN_TEAM_ID") expect(options[:key_id]).to eq GlobalConfig.get("IOS_CONSUMER_APP_APPLE_LOGIN_KEY_ID") expect(options[:private_key]).to be_a(OpenSSL::PKey::EC) end.and_return(@apple_id_client) User.find_for_apple_auth(authorization_code: "auth_code", app_type: "consumer") end it_behaves_like "finds user using Apple's authorization_code", "consumer" end context "when the request is from creator app" do it "initializes AppleID client using creator app credentials" do expect(AppleID::Client).to receive(:new) do |options| expect(options[:identifier]).to eq GlobalConfig.get("IOS_CREATOR_APP_APPLE_LOGIN_IDENTIFIER") expect(options[:team_id]).to eq GlobalConfig.get("IOS_CREATOR_APP_APPLE_LOGIN_TEAM_ID") expect(options[:key_id]).to eq GlobalConfig.get("IOS_CREATOR_APP_APPLE_LOGIN_KEY_ID") expect(options[:private_key]).to be_a(OpenSSL::PKey::EC) end.and_return(@apple_id_client) User.find_for_apple_auth(authorization_code: "auth_code", app_type: "creator") end it_behaves_like "finds user using Apple's authorization_code", "creator" end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/user/affiliated_products_spec.rb
spec/models/concerns/user/affiliated_products_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::AffiliatedProducts, :vcr do describe "#directly_affiliated_products" do let(:affiliate_user) { create(:affiliate_user) } let(:creator_one) { create(:named_user) } let(:creator_two) { create(:named_user) } let!(:product_one) { create(:product, name: "Product 1", user: creator_one) } let!(:product_two) { create(:product, name: "Product 2", user: creator_one) } let!(:product_three) { create(:product, name: "Product 3", deleted_at: DateTime.current, user: creator_one) } let!(:product_four) { create(:product, name: "Product 4", user: creator_two) } let!(:product_five) { create(:product, name: "Product 5", user: creator_two) } let!(:product_six) { create(:product, name: "Product 6", user: creator_two) } let!(:product_seven) { create(:product, name: "Product 7", user: creator_two) } let!(:product_eight) { create(:product, name: "Product 8") } let!(:direct_affiliate_one) { create(:direct_affiliate, affiliate_user:, seller: creator_one, affiliate_basis_points: 1500, products: [product_one, product_two, product_three]) } let!(:direct_affiliate_two) { create(:direct_affiliate, affiliate_user:, seller: creator_two, affiliate_basis_points: 1000, products: [product_four], deleted_at: DateTime.current) } let!(:direct_affiliate_three) { create(:direct_affiliate, affiliate_user:, seller: creator_two, affiliate_basis_points: 500, products: [product_five, product_six, product_seven]) } let!(:purchase_one) { create(:purchase_in_progress, seller: creator_one, link: product_one, affiliate: direct_affiliate_one) } let!(:purchase_two) { create(:purchase_in_progress, seller: creator_one, link: product_one, affiliate: direct_affiliate_one, chargeable: create(:chargeable)) } let!(:purchase_three) { create(:purchase_in_progress, seller: creator_one, link: product_three, affiliate: direct_affiliate_one) } let!(:purchase_four) { create(:purchase_in_progress, seller: creator_two, link: product_four, affiliate: direct_affiliate_two) } let!(:purchase_five) { create(:purchase_in_progress, seller: creator_two, link: product_six, affiliate: direct_affiliate_three) } let!(:purchase_six) { create(:purchase_in_progress, seller: creator_two, link: product_six, affiliate: direct_affiliate_three) } let!(:purchase_seven) { create(:purchase_in_progress, link: product_eight) } let(:select_columns) { "name, affiliates.id AS affiliate_id" } let(:affiliated_products) do affiliate_user.directly_affiliated_products(alive:) .select(select_columns) .map { |product| product.slice(:name, :affiliate_id) } end before(:each) do [purchase_one, purchase_two, purchase_three, purchase_four, purchase_five, purchase_six, purchase_seven].each do |purchase| purchase.process! purchase.update_balance_and_mark_successful! end purchase_two.refund_and_save!(nil) purchase_six.update!(chargeback_date: Date.today) end context "when alive flag is set to true" do let(:alive) { true } it "returns only alive affiliated products" do expect(affiliated_products).to match_array( [ { "name" => "Product 1", "affiliate_id" => direct_affiliate_one.id }, { "name" => "Product 2", "affiliate_id" => direct_affiliate_one.id }, { "name" => "Product 5", "affiliate_id" => direct_affiliate_three.id }, { "name" => "Product 6", "affiliate_id" => direct_affiliate_three.id }, { "name" => "Product 7", "affiliate_id" => direct_affiliate_three.id } ] ) end end context "when alive flag is set to false" do let(:alive) { false } it "returns both alive and non-alive affiliated products" do expect(affiliated_products).to match_array( [ { "name" => "Product 1", "affiliate_id" => direct_affiliate_one.id }, { "name" => "Product 2", "affiliate_id" => direct_affiliate_one.id }, { "name" => "Product 3", "affiliate_id" => direct_affiliate_one.id }, { "name" => "Product 4", "affiliate_id" => direct_affiliate_two.id }, { "name" => "Product 5", "affiliate_id" => direct_affiliate_three.id }, { "name" => "Product 6", "affiliate_id" => direct_affiliate_three.id }, { "name" => "Product 7", "affiliate_id" => direct_affiliate_three.id } ] ) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/user/stripe_connect_spec.rb
spec/models/concerns/user/stripe_connect_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::StripeConnect do describe ".find_or_create_for_stripe_connect_account" do before do @data = { "provider" => "stripe_connect", "uid" => "acct_1MbJuNSAp3rt4s0F", "info" => { "name" => "Gum Bot", "email" => "bot@gum.co", "nickname" => "gumbot", "scope" => "read_write", "livemode" => false }, "extra" => { "extra_info" => { "id" => "acct_1MbJuNSAp3rt4s0F", "object" => "account", "country" => "IN", "created" => 1676363450, "default_currency" => "inr" } } } end it "returns the user associated with the Stripe Connect account if one exists" do creator = create(:user) create(:merchant_account_stripe_connect, user: creator, charge_processor_merchant_id: @data["uid"]) expect(User.find_or_create_for_stripe_connect_account(@data)).to eq(creator) end it "does not return the user associated with the email and does not create a new one as email is already taken" do create(:user, email: @data["info"]["email"]) expect do expect do expect(User.find_or_create_for_stripe_connect_account(@data)).to be nil end.not_to change { User.count } end.not_to change { UserComplianceInfo.count } end it "creates a new user account and sets email and country" do expect do expect do User.find_or_create_for_stripe_connect_account(@data) end.to change { User.count }.by(1) end.to change { UserComplianceInfo.count }.by(1) expect(User.last.email).to eq(@data["info"]["email"]) expect(User.last.alive_user_compliance_info.country).to eq(Compliance::Countries.mapping[@data["extra"]["extra_info"]["country"]]) expect(User.last.confirmed?).to be true end it "associates past purchases with the same email to the new user" do email = @data["info"]["email"] purchase1 = create(:purchase, email:) purchase2 = create(:purchase, email:) expect(purchase1.purchaser_id).to be_nil expect(purchase2.purchaser_id).to be_nil user = User.find_or_create_for_stripe_connect_account(@data) expect(user.email).to eq("bot@gum.co") expect(purchase1.reload.purchaser_id).to eq(user.id) expect(purchase2.reload.purchaser_id).to eq(user.id) end end describe "#has_brazilian_stripe_connect_account?" do let(:user) { create(:user_compliance_info).user } it "returns true if user has a Brazilian Stripe Connect merchant account" do merchant_account = create(:merchant_account_stripe_connect, user:, country: Compliance::Countries::BRA.alpha2) allow(user).to receive(:merchant_account).with(StripeChargeProcessor.charge_processor_id).and_return(merchant_account) expect(user.has_brazilian_stripe_connect_account?).to be true end it "returns false if user has a non-Brazilian Stripe Connect merchant account" do merchant_account = create(:merchant_account_stripe_connect, user:, country: Compliance::Countries::USA.alpha2) allow(user).to receive(:merchant_account).with(StripeChargeProcessor.charge_processor_id).and_return(merchant_account) expect(user.has_brazilian_stripe_connect_account?).to be false end it "returns false if user has no Stripe Connect merchant account" do expect(user.has_brazilian_stripe_connect_account?).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/concerns/user/mailer_level_spec.rb
spec/models/concerns/user/mailer_level_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::MailerLevel do describe "#mailer_level" do before do @creator = create(:user) end context "when creator belongs to level_1" do it "returns :level_1" do expect(@creator.mailer_level).to eq :level_1 end it "returns :level_1 for negative sales_cents_total" do allow(@creator).to receive(:sales_cents_total).and_return(-20_000_00) # $-20K expect(@creator.mailer_level).to eq :level_1 end end context "when creator belongs to level_2" do it "returns :level_2" do allow(@creator).to receive(:sales_cents_total).and_return(60_000_00) # $60K expect(@creator.mailer_level).to eq :level_2 end it "returns :level_2 for very large sales_cents_total number" do allow(@creator).to receive(:sales_cents_total).and_return(800_000_000_00) # $800M expect(@creator.mailer_level).to eq :level_2 end end describe "caching" do before do @redis_namespace = Redis::Namespace.new(:user_mailer_redis_namespace, redis: $redis) end it "sets the level in redis" do @creator.mailer_level expect(@redis_namespace.get(@creator.send(:mailer_level_cache_key))).to eq "level_1" end it "doesn't query elasticsearch when level is available in redis" do @redis_namespace.set("creator_mailer_level_#{@creator.id}", "level_2") expect(@creator).not_to receive(:sales_cents_total) level = @creator.mailer_level expect(level).to eq :level_2 end it "caches the level in Memcached" do @creator.mailer_level expect(Rails.cache.read("creator_mailer_level_#{@creator.id}")).to eq :level_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/concerns/user/purchases_spec.rb
spec/models/concerns/user/purchases_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::Purchases do describe "#transfer_purchases!" do let(:user) { create(:user) } let(:new_user) { create(:user) } let!(:purchases) { create_list(:purchase, 3, email: user.email, purchaser: user) } it "transfers purchases to the new user" do user.transfer_purchases!(new_email: new_user.email) purchases.each do |purchase| expect(purchase.reload.email).to eq(new_user.email) expect(purchase.reload.purchaser).to eq(new_user) end end it "raises ActiveRecord::RecordNotFound if the new user does not exist" do expect do user.transfer_purchases!(new_email: Faker::Internet.email) end.to raise_error(ActiveRecord::RecordNotFound) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/user/vip_creator_spec.rb
spec/models/concerns/user/vip_creator_spec.rb
# frozen_string_literal: true require "spec_helper" describe User::VipCreator do let(:user) { create(:user) } describe "#vip_creator?" do context "when gross sales are above $5,000" do it "returns true" do create(:purchase, link: create(:product, user:, price_cents: 1_00)) create_list(:purchase, 2, link: create(:product, user:, price_cents: 2500_00)) index_model_records(Purchase) expect(user.vip_creator?).to be true end end context "when gross sales are less than or equal to $5,000" do it "returns false" do expect(user.sales).to be_empty expect(user.vip_creator?).to be false create_list(:purchase, 2, link: create(:product, user:, price_cents: 2500_00)) index_model_records(Purchase) expect(user.vip_creator?).to be false end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/affiliate/sorting_spec.rb
spec/models/concerns/affiliate/sorting_spec.rb
# frozen_string_literal: true require "spec_helper" describe Affiliate::Sorting do describe ".sorted_by" do let!(:seller) { create(:named_seller) } let!(:product1) { create(:product, user: seller, name: "p1") } let!(:product2) { create(:product, user: seller, name: "p2") } let!(:product3) { create(:product, user: seller, name: "p3") } let!(:affiliate_user_1) { create(:direct_affiliate, seller:, affiliate_user: create(:user, name: "aff1"), products: [product1]) } let!(:affiliate_user_2) { create(:direct_affiliate, seller:, affiliate_user: create(:user, name: "aff2"), products: [product1, product2, product3]) } let!(:affiliate_user_3) { create(:direct_affiliate, seller:, affiliate_user: create(:user, name: "aff3"), products: [product1, product3]) } before do ProductAffiliate.where(affiliate_id: affiliate_user_1.id).each.with_index do |affiliate, idx| affiliate.update_columns(affiliate_basis_points: 3000 + 100 * idx) end ProductAffiliate.where(affiliate_id: affiliate_user_2.id).each.with_index do |affiliate, idx| affiliate.update_columns(affiliate_basis_points: 2000 + 100 * idx) end ProductAffiliate.where(affiliate_id: affiliate_user_3.id).each.with_index do |affiliate, idx| affiliate.update_columns(affiliate_basis_points: 1000 + 100 * idx) end create_list(:purchase_with_balance, 2, link: product1, affiliate_credit_cents: 100, affiliate: affiliate_user_1) create_list(:purchase_with_balance, 3, link: product2, affiliate_credit_cents: 100, affiliate: affiliate_user_2) create(:purchase_with_balance, link: product3, affiliate_credit_cents: 100, affiliate: affiliate_user_3) end it "returns affiliates sorted by the affiliate user's name" do order = [affiliate_user_1, affiliate_user_2, affiliate_user_3] expect(seller.direct_affiliates.sorted_by(key: "affiliate_user_name", direction: "asc")).to eq(order) expect(seller.direct_affiliates.sorted_by(key: "affiliate_user_name", direction: "desc")).to eq(order.reverse) end context "affiliate username is their external_id because a custom username has not been set" do it "returns affiliates sorted by the affiliate user's unconfirmed e-mail if present" do affiliate_user_1.affiliate_user.update_columns(name: nil, username: nil, unconfirmed_email: "bob@example.com", email: nil) affiliate_user_2.affiliate_user.update_columns(name: nil, username: nil, unconfirmed_email: "charlie@example.com", email: nil) affiliate_user_3.affiliate_user.update_columns(name: nil, username: nil, unconfirmed_email: "alice@example.com", email: nil) order = [affiliate_user_3, affiliate_user_1, affiliate_user_2] expect(seller.direct_affiliates.sorted_by(key: "affiliate_user_name", direction: "asc")).to eq(order) expect(seller.direct_affiliates.sorted_by(key: "affiliate_user_name", direction: "desc")).to eq(order.reverse) end it "returns affiliates sorted by the affiliate user's e-mail if unconfirmed e-mail is not present" do affiliate_user_1.affiliate_user.update_columns(name: nil, username: nil, email: "bob@example.com", unconfirmed_email: nil) affiliate_user_2.affiliate_user.update_columns(name: nil, username: nil, email: "charlie@example.com", unconfirmed_email: nil) affiliate_user_3.affiliate_user.update_columns(name: nil, username: nil, email: "alice@example.com", unconfirmed_email: nil) order = [affiliate_user_3, affiliate_user_1, affiliate_user_2] expect(seller.direct_affiliates.sorted_by(key: "affiliate_user_name", direction: "asc")).to eq(order) expect(seller.direct_affiliates.sorted_by(key: "affiliate_user_name", direction: "desc")).to eq(order.reverse) end end it "returns affiliates sorted by the affiliate user's username if name is not present and a custom username is set" do affiliate_user_1.affiliate_user.update_columns(name: nil, email: nil, username: "charlie", unconfirmed_email: nil) affiliate_user_2.affiliate_user.update_columns(name: nil, email: nil, username: "bob", unconfirmed_email: nil) affiliate_user_3.affiliate_user.update_columns(name: nil, email: nil, username: "alice", unconfirmed_email: nil) order = [affiliate_user_3, affiliate_user_2, affiliate_user_1] expect(seller.direct_affiliates.sorted_by(key: "affiliate_user_name", direction: "asc")).to eq(order) expect(seller.direct_affiliates.sorted_by(key: "affiliate_user_name", direction: "desc")).to eq(order.reverse) end it "returns affiliates sorted by # of products" do order = [affiliate_user_1, affiliate_user_3, affiliate_user_2] expect(seller.direct_affiliates.sorted_by(key: "products", direction: "asc")).to eq(order) expect(seller.direct_affiliates.sorted_by(key: "products", direction: "desc")).to eq(order.reverse) end it "returns affiliates sorted by the lowest product commission percentage" do order = [affiliate_user_3, affiliate_user_2, affiliate_user_1] expect(seller.direct_affiliates.sorted_by(key: "fee_percent", direction: "asc")).to eq(order) expect(seller.direct_affiliates.sorted_by(key: "fee_percent", direction: "desc")).to eq(order.reverse) end it "returns affiliates sorted by total sales" do order = [affiliate_user_3, affiliate_user_1, affiliate_user_2] expect(seller.direct_affiliates.sorted_by(key: "volume_cents", direction: "asc")).to eq(order) expect(seller.direct_affiliates.sorted_by(key: "volume_cents", direction: "desc")).to eq(order.reverse) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/affiliate/cookies_spec.rb
spec/models/concerns/affiliate/cookies_spec.rb
# frozen_string_literal: true require "spec_helper" describe Affiliate::Cookies do let(:affiliate) { create(:direct_affiliate) } let(:another_affiliate) { create(:direct_affiliate) } describe "instance methods" do describe "#cookie_key" do it "generates cookie key with proper prefix and encrypted ID" do expected_key = "#{Affiliate::AFFILIATE_COOKIE_NAME_PREFIX}#{affiliate.cookie_id}" expect(affiliate.cookie_key).to eq(expected_key) end it "generates different keys for different affiliates" do expect(affiliate.cookie_key).not_to eq(another_affiliate.cookie_key) end end describe "#cookie_id" do it "returns encrypted ID without padding" do encrypted_id = affiliate.cookie_id expect(encrypted_id).not_to include("=") expect(encrypted_id).to be_present end it "can be decrypted back to original ID" do encrypted_id = affiliate.cookie_id decrypted_id = ObfuscateIds.decrypt(encrypted_id) expect(decrypted_id).to eq(affiliate.id) end it "generates deterministic IDs for the same affiliate" do id1 = affiliate.cookie_id id2 = affiliate.cookie_id expect(id1).to eq(id2) end end end describe "class methods" do describe ".by_cookies" do let(:cookies) do { affiliate.cookie_key => Time.current.to_i.to_s, another_affiliate.cookie_key => (Time.current - 1.hour).to_i.to_s, "_other_cookie" => "value", "_gumroad_guid" => "some-guid" } end it "returns affiliates found in cookies" do result = Affiliate.by_cookies(cookies) expect(result).to contain_exactly(affiliate, another_affiliate) end it "ignores non-affiliate cookies" do cookies_with_noise = cookies.merge("_random_cookie" => "value") result = Affiliate.by_cookies(cookies_with_noise) expect(result).to contain_exactly(affiliate, another_affiliate) end it "returns empty array when no affiliate cookies present" do empty_cookies = { "_gumroad_guid" => "some-guid" } result = Affiliate.by_cookies(empty_cookies) expect(result).to be_empty end it "handles empty cookies hash" do result = Affiliate.by_cookies({}) expect(result).to be_empty end it "sorts affiliates by cookie recency (newest first)" do # affiliate has newer timestamp, another_affiliate has older timestamp result = Affiliate.by_cookies(cookies) # Should return affiliate first (newer cookie) expect(result.first).to eq(affiliate) expect(result.second).to eq(another_affiliate) end end describe ".ids_from_cookies" do let(:cookies) do { affiliate.cookie_key => "1234567890", another_affiliate.cookie_key => "0987654321", "_other_cookie" => "value" } end it "extracts decrypted affiliate IDs from affiliate cookies" do result = Affiliate.ids_from_cookies(cookies) expect(result).to contain_exactly(affiliate.id, another_affiliate.id) end it "sorts cookies by timestamp descending" do newer_time = Time.current.to_i older_time = (Time.current - 1.hour).to_i sorted_cookies = { affiliate.cookie_key => older_time.to_s, another_affiliate.cookie_key => newer_time.to_s } result = Affiliate.ids_from_cookies(sorted_cookies) # Should return newer cookie first expect(result.first).to eq(another_affiliate.id) expect(result.second).to eq(affiliate.id) end it "handles URL-encoded cookie names" do encoded_cookie_name = CGI.escape(affiliate.cookie_key) cookies = { encoded_cookie_name => "1234567890" } result = Affiliate.ids_from_cookies(cookies) expect(result).to contain_exactly(affiliate.id) end it "ignores non-affiliate cookies" do cookies = { affiliate.cookie_key => "1234567890", "_random_cookie" => "value", "_gumroad_guid" => "guid-value" } result = Affiliate.ids_from_cookies(cookies) expect(result).to contain_exactly(affiliate.id) end end describe ".extract_cookie_id_from_cookie_name" do it "extracts cookie ID from valid affiliate cookie names" do cookie_name = affiliate.cookie_key result = Affiliate.extract_cookie_id_from_cookie_name(cookie_name) expect(result).to eq(affiliate.cookie_id) end it "handles URL-encoded cookie names" do encoded_cookie_name = CGI.escape(affiliate.cookie_key) result = Affiliate.extract_cookie_id_from_cookie_name(encoded_cookie_name) expect(result).to eq(affiliate.cookie_id) end end describe ".decrypt_cookie_id" do it "decrypts encrypted cookie ID back to raw affiliate ID" do encrypted_id = affiliate.cookie_id decrypted_id = Affiliate.decrypt_cookie_id(encrypted_id) expect(decrypted_id).to eq(affiliate.id) end it "handles both padded and unpadded base64 formats" do # Generate both formats for the same affiliate padded_id = ObfuscateIds.encrypt(affiliate.id, padding: true) unpadded_id = ObfuscateIds.encrypt(affiliate.id, padding: false) # Both should decrypt to the same raw ID padded_result = Affiliate.decrypt_cookie_id(padded_id) unpadded_result = Affiliate.decrypt_cookie_id(unpadded_id) expect(padded_result).to eq(affiliate.id) expect(unpadded_result).to eq(affiliate.id) expect(padded_result).to eq(unpadded_result) end it "returns nil for invalid encrypted IDs" do result = Affiliate.decrypt_cookie_id("invalid_id") expect(result).to be_nil end end end describe "integration: full cookie workflow" do it "can set and read cookies for multiple affiliates" do # Simulate setting cookies (like in affiliate redirect) cookies = {} # Set cookies with different timestamps cookies[affiliate.cookie_key] = Time.current.to_i.to_s cookies[another_affiliate.cookie_key] = (Time.current - 1.hour).to_i.to_s # Read affiliates from cookies (like in purchase flow) found_affiliates = Affiliate.by_cookies(cookies) expect(found_affiliates).to contain_exactly(affiliate, another_affiliate) end it "handles legacy cookies with padding during migration" do # Simulate having both old (padded) and new (unpadded) cookies for same affiliate old_cookie_key = "#{Affiliate::AFFILIATE_COOKIE_NAME_PREFIX}#{ObfuscateIds.encrypt(affiliate.id, padding: true)}" new_cookie_key = affiliate.cookie_key cookies = { old_cookie_key => (Time.current - 1.hour).to_i.to_s, new_cookie_key => Time.current.to_i.to_s } # Should find the affiliate twice (which gets deduplicated by business logic) found_affiliates = Affiliate.by_cookies(cookies) affiliate_ids = found_affiliates.map(&:id) # Both cookies resolve to the same affiliate expect(affiliate_ids).to eq([affiliate.id]) end it "handles sorting with mismatched cookie formats without errors" do # Create a padded cookie ID that won't match the affiliate's current cookie_id format old_cookie_key = "#{Affiliate::AFFILIATE_COOKIE_NAME_PREFIX}#{ObfuscateIds.encrypt(affiliate.id, padding: true)}" cookies = { old_cookie_key => 1.hour.ago.to_i.to_s, another_affiliate.cookie_key => 2.hours.ago.to_i.to_s } # This should not raise an exception even though affiliate.cookie_id won't match the old_cookie_key format expect { Affiliate.by_cookies(cookies) }.not_to raise_error found_affiliates = Affiliate.by_cookies(cookies) expect(found_affiliates.map(&:id)).to contain_exactly(affiliate.id, another_affiliate.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/concerns/upsell/sorting_spec.rb
spec/models/concerns/upsell/sorting_spec.rb
# frozen_string_literal: true require "spec_helper" describe Upsell::Sorting do describe ".sorted_by" do let(:seller) { create(:named_seller) } let(:product1) { create(:product_with_digital_versions, user: seller, price_cents: 2000, name: "Product 1") } let(:product2) { create(:product_with_digital_versions, user: seller, price_cents: 500, name: "Product 2") } let!(:upsell1) { create(:upsell, product: product1, variant: product1.alive_variants.second, name: "Upsell 1", seller:, cross_sell: true, paused: false, offer_code: create(:offer_code, user: seller, products: [product1])) } let!(:upsell2) { create(:upsell, product: product2, name: "Upsell 2", seller:, paused: true) } let!(:upsell2_variant) { create(:upsell_variant, upsell: upsell2, selected_variant: product2.alive_variants.first, offered_variant: product2.alive_variants.second) } before do build_list :product, 2, user: seller do |product, i| product.name = "Product #{i + 3}" create_list(:upsell_purchase, 2, upsell: upsell1, selected_product: product) upsell1.selected_products << product end create_list(:upsell_purchase, 5, upsell: upsell2, selected_product: product2, upsell_variant: upsell2_variant) end it "returns upsells sorted by name" do order = [upsell1, upsell2] expect(seller.upsells.sorted_by(key: "name", direction: "asc")).to eq(order) expect(seller.upsells.sorted_by(key: "name", direction: "desc")).to eq(order.reverse) end it "returns upsells sorted by uses" do order = [upsell1, upsell2] expect(seller.upsells.sorted_by(key: "uses", direction: "asc")).to eq(order) expect(seller.upsells.sorted_by(key: "uses", direction: "desc")).to eq(order.reverse) end it "returns upsells sorted by revenue" do order = [upsell2, upsell1] expect(seller.upsells.sorted_by(key: "revenue", direction: "asc")).to eq(order) expect(seller.upsells.sorted_by(key: "revenue", direction: "desc")).to eq(order.reverse) end it "returns upsells sorted by status" do order = [upsell1, upsell2] expect(seller.upsells.sorted_by(key: "status", direction: "asc")).to eq(order) expect(seller.upsells.sorted_by(key: "status", direction: "desc")).to eq(order.reverse) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/offer_code/sorting_spec.rb
spec/models/concerns/offer_code/sorting_spec.rb
# frozen_string_literal: true require "spec_helper" describe OfferCode::Sorting do describe ".sorted_by" do let(:seller) { create(:named_seller) } let(:product1) { create(:product, name: "Product 1", user: seller, price_cents: 1000) } let(:product2) { create(:product, name: "Product 2", user: seller, price_cents: 500) } let!(:offer_code1) { create(:offer_code, name: "Discount 1", code: "code1", products: [product1, product2], user: seller, max_purchase_count: 12, valid_at: ActiveSupport::TimeZone[seller.timezone].parse("January 1 #{Time.current.year - 1}"), expires_at: ActiveSupport::TimeZone[seller.timezone].parse("February 1 #{Time.current.year - 1}")) } let!(:offer_code2) { create(:offer_code, name: "Discount 2", code: "code2", products: [product2], user: seller, max_purchase_count: 20, amount_cents: 200, valid_at: ActiveSupport::TimeZone[seller.timezone].parse("January 1 #{Time.current.year + 1}")) } let!(:offer_code3) { create(:percentage_offer_code, name: "Discount 3", code: "code3", universal: true, products: [], user: seller, amount_percentage: 50) } before do 10.times { create(:purchase, link: product1, offer_code: offer_code1) } 5.times { create(:purchase, link: product2, offer_code: offer_code2) } create(:purchase, link: product1, offer_code: offer_code3) create(:purchase, link: product2, offer_code: offer_code3) end it "returns offer codes sorted by name" do expect(seller.offer_codes.sorted_by(key: "name", direction: "asc")).to eq([offer_code1, offer_code2, offer_code3]) expect(seller.offer_codes.sorted_by(key: "name", direction: "desc")).to eq([offer_code3, offer_code2, offer_code1]) end it "returns offer codes sorted by uses" do expect(seller.offer_codes.sorted_by(key: "uses", direction: "asc")).to eq([offer_code3, offer_code2, offer_code1]) expect(seller.offer_codes.sorted_by(key: "uses", direction: "desc")).to eq([offer_code1, offer_code2, offer_code3]) end it "returns offer codes sorted by revenue" do expect(seller.offer_codes.sorted_by(key: "uses", direction: "asc")).to eq([offer_code3, offer_code2, offer_code1]) expect(seller.offer_codes.sorted_by(key: "uses", direction: "desc")).to eq([offer_code1, offer_code2, offer_code3]) end it "returns offer codes sorted by term" do expect(seller.offer_codes.sorted_by(key: "uses", direction: "asc")).to eq([offer_code3, offer_code2, offer_code1]) expect(seller.offer_codes.sorted_by(key: "uses", direction: "desc")).to eq([offer_code1, offer_code2, offer_code3]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/charge/disputable_spec.rb
spec/models/concerns/charge/disputable_spec.rb
# frozen_string_literal: true require "spec_helper" describe Charge::Disputable, :vcr do let(:stripe_purchase) do create(:purchase, charge_processor_id: StripeChargeProcessor.charge_processor_id, stripe_transaction_id: "ch_12345", total_transaction_cents: 10_00, succeeded_at: Date.new(2024, 2, 27)) end let(:paypal_purchase) do create(:purchase, charge_processor_id: PaypalChargeProcessor.charge_processor_id, stripe_transaction_id: "pp_12345", total_transaction_cents: 20_00, succeeded_at: Date.new(2024, 2, 28)) end let(:braintree_purchase) do create(:purchase, charge_processor_id: BraintreeChargeProcessor.charge_processor_id, stripe_transaction_id: "bt_12345", total_transaction_cents: 30_00, succeeded_at: Date.new(2024, 2, 29)) end let(:stripe_charge) do create(:charge, processor: StripeChargeProcessor.charge_processor_id, processor_transaction_id: "ch_12345", amount_cents: 10_00) end let(:paypal_charge) do create(:charge, processor: PaypalChargeProcessor.charge_processor_id, processor_transaction_id: "pp_12345", amount_cents: 20_00) end let(:braintree_charge) do create(:charge, processor: BraintreeChargeProcessor.charge_processor_id, processor_transaction_id: "bt_12345", amount_cents: 30_00) end describe "#charge_processor" do it "returns the charge processor id of the purchase" do expect(stripe_purchase.charge_processor).to eq("stripe") expect(paypal_purchase.charge_processor).to eq("paypal") expect(braintree_purchase.charge_processor).to eq("braintree") end it "returns the processor of the charge" do expect(stripe_charge.charge_processor).to eq("stripe") expect(paypal_charge.charge_processor).to eq("paypal") expect(braintree_charge.charge_processor).to eq("braintree") end end describe "#charge_processor_transaction_id" do it "returns the Stripe/PayPal transaction id of the purchase" do expect(stripe_purchase.charge_processor_transaction_id).to eq("ch_12345") expect(paypal_purchase.charge_processor_transaction_id).to eq("pp_12345") expect(braintree_purchase.charge_processor_transaction_id).to eq("bt_12345") end it "returns the Stripe/PayPal transaction id of the charge" do expect(stripe_charge.charge_processor_transaction_id).to eq("ch_12345") expect(paypal_charge.charge_processor_transaction_id).to eq("pp_12345") expect(braintree_charge.charge_processor_transaction_id).to eq("bt_12345") end end describe "#purchase_for_dispute_evidence" do it "returns the purchase object itself" do expect(stripe_purchase.purchase_for_dispute_evidence).to eq(stripe_purchase) expect(paypal_purchase.purchase_for_dispute_evidence).to eq(paypal_purchase) expect(braintree_purchase.purchase_for_dispute_evidence).to eq(braintree_purchase) end describe "for a Charge" do let!(:charge) { create(:charge) } context "includes a subscription purchase with a refund policy" do before do membership_product = create(:membership_product) @membership_purchase_with_refund_policy = create(:membership_purchase, total_transaction_cents: 10_00, link: membership_product) @membership_purchase_with_refund_policy.create_purchase_refund_policy!(title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30) product = create(:product) regular_purchase = create(:purchase, total_transaction_cents: 150_00, link: product) regular_purchase.create_purchase_refund_policy!(title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30) charge.purchases << create(:membership_purchase, total_transaction_cents: 100_00) charge.purchases << @membership_purchase_with_refund_policy charge.purchases << regular_purchase end it "returns it" do expect(charge.purchase_for_dispute_evidence).to eq @membership_purchase_with_refund_policy end it "returns the purchase with highest total amount if there are multiple" do membership_product = create(:membership_product) membership_purchase_with_refund_policy = create(:membership_purchase, total_transaction_cents: 15_00, link: membership_product) membership_purchase_with_refund_policy.create_purchase_refund_policy!(title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30) charge.purchases << membership_purchase_with_refund_policy expect(charge.purchase_for_dispute_evidence).to eq membership_purchase_with_refund_policy end end context "includes a regular purchase with a refund policy" do before do product = create(:product) @regular_purchase_with_refund_policy = create(:purchase, total_transaction_cents: 10_00, link: product) @regular_purchase_with_refund_policy.create_purchase_refund_policy!(title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30) charge.purchases << create(:purchase, total_transaction_cents: 100_00, link: product) charge.purchases << @regular_purchase_with_refund_policy end it "returns it if dispute reason is not subscription canceled" do expect(charge.purchase_for_dispute_evidence).to eq @regular_purchase_with_refund_policy end it "returns the purchase with highest total amount if there are multiple" do product = create(:product) regular_purchase_with_refund_policy = create(:purchase, total_transaction_cents: 15_00, link: product) regular_purchase_with_refund_policy.create_purchase_refund_policy!(title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30) charge.purchases << regular_purchase_with_refund_policy expect(charge.purchase_for_dispute_evidence).to eq regular_purchase_with_refund_policy end end context "includes a subscription purchase without a refund policy" do before do create(:dispute_on_charge, charge:, reason: Dispute::REASON_SUBSCRIPTION_CANCELED) @membership_purchase = create(:membership_purchase, total_transaction_cents: 10_00) charge.purchases << @membership_purchase regular_purchase_with_refund_policy = create(:purchase, total_transaction_cents: 100_00) regular_purchase_with_refund_policy.create_purchase_refund_policy!(title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30) charge.purchases << regular_purchase_with_refund_policy end it "returns it if dispute reason is subscription canceled" do expect(charge.purchase_for_dispute_evidence).to eq @membership_purchase end it "returns the purchase with highest total amount if there are multiple" do membership_purchase = create(:membership_purchase, total_transaction_cents: 15_00) charge.purchases << membership_purchase expect(charge.purchase_for_dispute_evidence).to eq membership_purchase end end context "includes a regular purchase without a refund policy" do before do @regular_purchase = create(:purchase, total_transaction_cents: 15_00) charge.purchases << @regular_purchase charge.purchases << create(:purchase, total_transaction_cents: 10_00) end it "returns the purchase with highest total amount if there are multiple" do expect(charge.purchase_for_dispute_evidence).to eq @regular_purchase end end end end describe "#first_product_without_refund_policy" do it "returns the product associated with the purchase object" do expect(stripe_purchase.first_product_without_refund_policy).to eq(stripe_purchase.link) expect(paypal_purchase.first_product_without_refund_policy).to eq(paypal_purchase.link) expect(braintree_purchase.first_product_without_refund_policy).to eq(braintree_purchase.link) end describe "for a Charge" do it "returns a purchase that does not have a refund policy" do charge = create(:charge) purchase_with_refund_policy = create(:purchase) create(:product_refund_policy, seller: purchase_with_refund_policy.seller, product: purchase_with_refund_policy.link) purchase_with_refund_policy.link.update!(product_refund_policy_enabled: true) purchase_without_refund_policy = create(:purchase, link: create(:product, user: purchase_with_refund_policy.seller)) charge.purchases << purchase_without_refund_policy charge.purchases << purchase_with_refund_policy expect(charge.first_product_without_refund_policy).to eq(purchase_without_refund_policy.link) end end end describe "#disputed_amount_cents" do it "returns the total transaction cents of the purchase" do expect(stripe_purchase.disputed_amount_cents).to eq(10_00) expect(paypal_purchase.disputed_amount_cents).to eq(20_00) expect(braintree_purchase.disputed_amount_cents).to eq(30_00) end it "returns the amount_cents of the Charge" do expect(stripe_charge.disputed_amount_cents).to eq(10_00) expect(paypal_charge.disputed_amount_cents).to eq(20_00) expect(braintree_charge.disputed_amount_cents).to eq(30_00) end end describe "#formatted_disputed_amount" do it "returns the total transaction cents of the purchase" do expect(stripe_purchase.formatted_disputed_amount).to eq("$10") expect(paypal_purchase.formatted_disputed_amount).to eq("$20") expect(braintree_purchase.formatted_disputed_amount).to eq("$30") end it "returns the amount_cents of the Charge" do expect(stripe_charge.formatted_disputed_amount).to eq("$10") expect(paypal_charge.formatted_disputed_amount).to eq("$20") expect(braintree_charge.formatted_disputed_amount).to eq("$30") end end describe "#customer_email" do it "returns the email of the Purchase" do expect(stripe_purchase.customer_email).to eq(stripe_purchase.email) expect(paypal_purchase.customer_email).to eq(paypal_purchase.email) expect(braintree_purchase.customer_email).to eq(braintree_purchase.email) end it "returns the email of the Purchase selected for dispute evidence for a Charge" do stripe_charge.purchases << stripe_purchase expect(stripe_charge.customer_email).to eq(stripe_purchase.email) paypal_charge.purchases << paypal_purchase expect(paypal_charge.customer_email).to eq(paypal_purchase.email) braintree_charge.purchases << braintree_purchase expect(braintree_charge.customer_email).to eq(braintree_purchase.email) end end describe "#disputed_purchases" do it "returns an array containing the purchase object" do expect(stripe_purchase.disputed_purchases).to eq([stripe_purchase]) expect(paypal_purchase.disputed_purchases).to eq([paypal_purchase]) expect(braintree_purchase.disputed_purchases).to eq([braintree_purchase]) end end describe "#dispute_balance_date" do it "returns the succeeded date of the purchase" do expect(stripe_purchase.dispute_balance_date).to eq(Date.new(2024, 2, 27)) expect(paypal_purchase.dispute_balance_date).to eq(Date.new(2024, 2, 28)) expect(braintree_purchase.dispute_balance_date).to eq(Date.new(2024, 2, 29)) end end describe "handles dispute events" do describe "dispute formalized" do let(:initial_balance) { 200 } let(:seller) { create(:user, unpaid_balance_cents: initial_balance) } let(:product) { create(:product, user: seller) } let!(:purchase) do create(:purchase, link: product, seller: product.user, stripe_transaction_id: "ch_zitkxbhds3zqlt", price_cents: 100, total_transaction_cents: 100, fee_cents: 30) end let(:event) { build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt") } before do sample_image = File.read(Rails.root.join("spec", "support", "fixtures", "test-small.jpg")) allow(DisputeEvidence::GenerateReceiptImageService).to receive(:perform).with(purchase).and_return(sample_image) end it "doesn't deduct Gumroad fees from the seller's balance" do Purchase.handle_charge_event(event) purchase.reload seller.reload expect(seller.unpaid_balance_cents).to eq initial_balance - purchase.payment_cents expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id) end context "when the product is a subscription" do let(:product) { create(:subscription_product, user: seller) } let!(:purchase) do subscription = create(:subscription, link: product, cancelled_at: nil) purchase = create(:purchase, link: product, is_original_subscription_purchase: true, subscription:, stripe_transaction_id: "ch_zitkxbhds3zqlt") purchase.update(is_original_subscription_purchase: true, subscription:) purchase end it "cancels the subscription if the product is a subscription" do Purchase.handle_charge_event(event) purchase.reload expect(purchase.subscription.cancelled_at).to_not be(nil) expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id) end end it "sends emails to admin, creator, and customer" do mail = double("mail") expect(mail).to receive(:deliver_later).exactly(3).times expect(AdminMailer).to receive(:chargeback_notify).and_return(mail) expect(ContactingCreatorMailer).to receive(:chargeback_notice).and_return(mail) expect(CustomerLowPriorityMailer).to receive(:chargeback_notice_to_customer).and_return(mail) Purchase.handle_charge_event(event) expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id) end it "enqueues the post to ping job for 'dispute' resource" do Purchase.handle_charge_event(event) expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(purchase.id, nil, ResourceSubscription::DISPUTE_RESOURCE_NAME) expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id) end it "calls pause_payouts_for_seller_based_on_chargeback_rate! for each purchase" do expect_any_instance_of(Purchase).to receive(:pause_payouts_for_seller_based_on_chargeback_rate!) Purchase.handle_charge_event(event) expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id) end describe "purchase involves an affiliate" do let(:merchant_account) { create(:merchant_account, user: seller) } let(:affiliate_user) { create(:affiliate_user) } let(:direct_affiliate) { create(:direct_affiliate, affiliate_user:, seller:, affiliate_basis_points: 2000, products: [product]) } let(:purchase) do issued_amount = FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100) settled_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110) gumroad_amount = FlowOfFunds::Amount.new(currency: Currency::USD, cents: 30) merchant_account_gross_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110) merchant_account_net_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 80) create( :purchase_with_balance, link: product, seller:, stripe_transaction_id: "ch_zitkxbhds3zqlt", merchant_account:, total_transaction_cents: 100, fee_cents: 30, affiliate: direct_affiliate, flow_of_funds: FlowOfFunds.new( issued_amount:, settled_amount:, gumroad_amount:, merchant_account_gross_amount:, merchant_account_net_amount: ) ) end let(:event_flow_of_funds) do issued_amount = FlowOfFunds::Amount.new(currency: Currency::USD, cents: -100) settled_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: -110) gumroad_amount = FlowOfFunds::Amount.new(currency: Currency::USD, cents: -30) merchant_account_gross_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: -110) merchant_account_net_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: -80) FlowOfFunds.new( issued_amount:, settled_amount:, gumroad_amount:, merchant_account_gross_amount:, merchant_account_net_amount: ) end let(:event) { build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt", flow_of_funds: event_flow_of_funds) } before do purchase.reload expect(purchase.purchase_success_balance.amount_cents).to eq(6) # 100c - 20c (affiliate fees) + 19c (affiliate's share of Gumroad fee) - 10c (10% flat fee) -50c (fixed fee) - 3c (2.9% cc fee) - (30c fixed cc fee) expect(purchase.affiliate_credit.affiliate_credit_success_balance.amount_cents).to eq(1) allow_any_instance_of(Purchase).to receive(:fight_chargeback).and_return(true) Purchase.handle_charge_event(event) purchase.reload end it "updates the balance of the creator" do expect(purchase.purchase_chargeback_balance).to eq(purchase.purchase_success_balance) expect(purchase.purchase_chargeback_balance.amount_cents).to eq(0) expect(purchase.purchase_chargeback_balance.merchant_account_id).to eq(purchase.merchant_account_id) expect(purchase.purchase_chargeback_balance.merchant_account_id).to eq(purchase.purchase_success_balance.merchant_account_id) end it "updates the balance of the affiliate" do expect(purchase.affiliate_credit.affiliate_credit_chargeback_balance).to eq(purchase.affiliate_credit.affiliate_credit_success_balance) expect(purchase.affiliate_credit.affiliate_credit_chargeback_balance.amount_cents).to eq(0) expect(purchase.affiliate_credit.affiliate_credit_chargeback_balance.merchant_account_id).to eq(MerchantAccount.gumroad(purchase.charge_processor_id).id) expect(purchase.affiliate_credit.affiliate_credit_chargeback_balance.merchant_account_id).to eq(purchase.affiliate_credit.affiliate_credit_success_balance.merchant_account_id) end it "creates two balance transactions for the dispute formalized" do balance_transaction_1, balance_transaction_2 = BalanceTransaction.last(2) expect(balance_transaction_1.user).to eq(affiliate_user) expect(balance_transaction_1.merchant_account).to eq(purchase.affiliate_merchant_account) expect(balance_transaction_1.merchant_account).to eq(MerchantAccount.gumroad(purchase.charge_processor_id)) expect(balance_transaction_1.refund).to eq(purchase.refunds.last) expect(balance_transaction_1.issued_amount_currency).to eq(Currency::USD) expect(balance_transaction_1.issued_amount_gross_cents).to eq(-1 * purchase.affiliate_credit_cents) expect(balance_transaction_1.issued_amount_net_cents).to eq(-1 * purchase.affiliate_credit_cents) expect(balance_transaction_1.holding_amount_currency).to eq(Currency::USD) expect(balance_transaction_1.holding_amount_gross_cents).to eq(-1 * purchase.affiliate_credit_cents) expect(balance_transaction_1.holding_amount_net_cents).to eq(-1 * purchase.affiliate_credit_cents) expect(balance_transaction_2.user).to eq(seller) expect(balance_transaction_2.merchant_account).to eq(purchase.merchant_account) expect(balance_transaction_2.merchant_account).to eq(merchant_account) expect(balance_transaction_2.refund).to eq(purchase.refunds.last) expect(balance_transaction_2.issued_amount_currency).to eq(Currency::USD) expect(balance_transaction_2.issued_amount_currency).to eq(event_flow_of_funds.issued_amount.currency) expect(balance_transaction_2.issued_amount_gross_cents).to eq(-1 * purchase.total_transaction_cents) expect(balance_transaction_2.issued_amount_gross_cents).to eq(event_flow_of_funds.issued_amount.cents) expect(balance_transaction_2.issued_amount_net_cents).to eq(-1 * (purchase.payment_cents - purchase.affiliate_credit_cents)) expect(balance_transaction_2.holding_amount_currency).to eq(Currency::CAD) expect(balance_transaction_2.holding_amount_currency).to eq(event_flow_of_funds.merchant_account_gross_amount.currency) expect(balance_transaction_2.holding_amount_currency).to eq(event_flow_of_funds.merchant_account_net_amount.currency) expect(balance_transaction_2.holding_amount_gross_cents).to eq(event_flow_of_funds.merchant_account_gross_amount.cents) expect(balance_transaction_2.holding_amount_net_cents).to eq(event_flow_of_funds.merchant_account_net_amount.cents) end end describe "dispute object" do let!(:purchase) { create(:purchase, link: product, seller: product.user, stripe_transaction_id: "1", price_cents: 100, fee_cents: 30, total_transaction_cents: 100) } let(:event) { build(:charge_event_dispute_formalized, charge_id: "1", extras: { reason: "fraud", charge_processor_dispute_id: "2" }) } let(:frozen_time) { Time.zone.local(2015, 9, 8, 4, 57) } describe "dispute object already exists for purchase" do describe "existing disput object has formalized state" do before do Purchase.handle_charge_event(event) purchase.dispute.state = :formalized purchase.dispute.save! travel_to(frozen_time) do Purchase.handle_charge_event(event) end end it "does not decrement the seller's balance" do expect(purchase).to_not receive(:decrement_balance_for_refund_or_chargeback!) end end context "when the purchase has a dispute in created state" do before do Purchase.handle_charge_event(event) purchase.dispute.state = :created purchase.dispute.save! end it "does not create a new dispute" do travel_to(frozen_time) do Purchase.handle_charge_event(event) end expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id) expect(Dispute.where(purchase_id: purchase.id).count).to eq(1) end it "does not mark the dispute as formalized" do travel_to(frozen_time) do Purchase.handle_charge_event(event) end expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id) purchase.reload expect(purchase.dispute.state).to eq("formalized") expect(purchase.dispute.formalized_at).to eq(frozen_time) end end end context "when the purchase doesn't have a dispute" do before do Purchase.handle_charge_event(event) end it "creates a dispute" do expect(purchase.dispute).to be_a(Dispute) end it "sets the dispute's event creation time from the event" do expect(purchase.dispute.event_created_at.iso8601(6)).to eq(event.created_at.in_time_zone.iso8601(6)) end it "sets the disputes reason from the event" do expect(purchase.dispute.reason).to eq(event.extras[:reason]) end it "sets the disputes charge processor id from the purchase" do expect(purchase.dispute.charge_processor_id).to eq(purchase.charge_processor_id) end it "sets the dipsutes charge processor dispute id from the event" do expect(purchase.dispute.charge_processor_dispute_id).to eq(event.extras[:charge_processor_dispute_id]) end it "marks the dispute as formalized" do expect(purchase.dispute.state).to eq("formalized") expect(purchase.dispute.formalized_at).not_to be(nil) end end end context "when the purchase is partially refunded" do before do purchase.refund_and_save!(product.user.id, amount_cents: 50) end it "deducts only remaining balance" do Purchase.handle_charge_event(event) expect(seller.reload.unpaid_balance_cents).to eq initial_balance - purchase.reload.payment_cents end end end describe "dispute closed" do describe "dispute won" do before do @initial_balance = 200 @u = create(:user, unpaid_balance_cents: @initial_balance) @l = create(:product, user: @u) @p = create(:purchase, link: @l, seller: @l.user, stripe_transaction_id: "ch_zitkxbhds3zqlt", price_cents: 100, total_transaction_cents: 100, fee_cents: 30, chargeback_date: Date.today - 10) @e = build(:charge_event_dispute_won, charge_id: "ch_zitkxbhds3zqlt") end describe "purchase is partially refunded" do let(:refund_flow_of_funds) { FlowOfFunds.build_simple_flow_of_funds(Currency::USD, -50) } before do unpaid_balance_before = @u.unpaid_balance_cents @p.refund_purchase!(refund_flow_of_funds, nil) @p.reload @difference_cents = unpaid_balance_before - @u.unpaid_balance_cents end it "credits only remaining balance" do Purchase.handle_charge_event(@e) @u.reload expect(Credit.last.user).to eq @p.seller expect(Credit.last.amount_cents).to eq 4 expect(Credit.last.chargebacked_purchase_id).to eq @p.id end end it "credits the creator" do count = Credit.all.count Purchase.handle_charge_event(@e) expect(Credit.last.user).to eq @p.seller expect(Credit.last.amount_cents).to eq @p.payment_cents expect(Credit.last.chargebacked_purchase_id).to eq @p.id expect(Credit.all.count).to eq count + 1 end it "emails the creator" do mail_double = double allow(mail_double).to receive(:deliver_later) expect(ContactingCreatorMailer).to receive(:chargeback_won).and_return(mail_double) expect(ContactingCreatorMailer).to_not receive(:credit_notification).with(@u.id, 100) Purchase.handle_charge_event(@e) end it "enqueues the post to ping job for 'dispute_won' resource" do Purchase.handle_charge_event(@e) expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(@p.id, nil, ResourceSubscription::DISPUTE_WON_RESOURCE_NAME) end it "sets the chargeback reversed flag" do Purchase.handle_charge_event(@e) expect(@p.reload.chargeback_reversed).to be(true) end describe "purchase involves an affiliate" do let(:user) { @u } let(:merchant_account) { create(:merchant_account, user:) } let(:link) { @l } let(:affiliate_user) { create(:affiliate_user) } let(:direct_affiliate) { create(:direct_affiliate, affiliate_user:, seller: user, affiliate_basis_points: 2000, products: [link]) } let(:purchase) do issued_amount = FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100) settled_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110) gumroad_amount = FlowOfFunds::Amount.new(currency: Currency::USD, cents: 30) merchant_account_gross_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110) merchant_account_net_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 80) create( :purchase_with_balance, link:, seller: user, stripe_transaction_id: "ch_zitkxbhds3zqlt", merchant_account:, total_transaction_cents: 100, fee_cents: 30, affiliate: direct_affiliate, flow_of_funds: FlowOfFunds.new( issued_amount:, settled_amount:, gumroad_amount:, merchant_account_gross_amount:, merchant_account_net_amount: ) ) end let(:event_1_flow_of_funds) do issued_amount = FlowOfFunds::Amount.new(currency: Currency::USD, cents: -100) settled_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: -110) gumroad_amount = FlowOfFunds::Amount.new(currency: Currency::USD, cents: -30) merchant_account_gross_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: -110) merchant_account_net_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: -80) FlowOfFunds.new( issued_amount:, settled_amount:, gumroad_amount:, merchant_account_gross_amount:, merchant_account_net_amount: ) end let(:event_1) { build(:charge_event_dispute_formalized, charge_id: "ch_zitkxbhds3zqlt", flow_of_funds: event_1_flow_of_funds) } let(:event_2_flow_of_funds) do issued_amount = FlowOfFunds::Amount.new(currency: Currency::USD, cents: 100) settled_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110) gumroad_amount = FlowOfFunds::Amount.new(currency: Currency::USD, cents: 30) merchant_account_gross_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 110) merchant_account_net_amount = FlowOfFunds::Amount.new(currency: Currency::CAD, cents: 80) FlowOfFunds.new( issued_amount:, settled_amount:, gumroad_amount:, merchant_account_gross_amount:, merchant_account_net_amount: ) end let(:event_2) { build(:charge_event_dispute_won, charge_id: "ch_zitkxbhds3zqlt", flow_of_funds: event_2_flow_of_funds) } before do purchase.reload expect(purchase.purchase_success_balance.amount_cents).to eq(6) # 100c - 20c (affiliate fees) + 19c (affiliate's share of Gumroad fee) - 10c (10% flat fee) - 50c - 3c (2.9% cc fee) - (30c fixed cc fee) expect(purchase.affiliate_credit.affiliate_credit_success_balance.amount_cents).to eq(1) allow_any_instance_of(Purchase).to receive(:fight_chargeback).and_return(true) Purchase.handle_charge_event(event_1) purchase.reload expect(purchase.purchase_chargeback_balance.amount_cents).to eq(0) expect(purchase.affiliate_credit.affiliate_credit_chargeback_balance.amount_cents).to eq(0) end it "creates two credits" do expect { Purchase.handle_charge_event(event_2) }.to change { Credit.count }.by(2) end it "credits the creator" do Purchase.handle_charge_event(event_2) expect(purchase.seller.credits.last.amount_cents).to eq(purchase.payment_cents - purchase.affiliate_credit_cents) expect(purchase.seller.credits.last.chargebacked_purchase_id).to eq(purchase.id) expect(purchase.seller.credits.last.merchant_account_id).to eq(purchase.merchant_account_id) end it "credits the affiliate" do Purchase.handle_charge_event(event_2) expect(purchase.affiliate_credit.affiliate_user.credits.last.amount_cents).to eq(purchase.affiliate_credit_cents) expect(purchase.affiliate_credit.affiliate_user.credits.last.chargebacked_purchase_id).to eq purchase.id expect(purchase.affiliate_credit.affiliate_user.credits.last.merchant_account_id).to eq(MerchantAccount.gumroad(purchase.charge_processor_id).id) end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/charge/chargeable_spec.rb
spec/models/concerns/charge/chargeable_spec.rb
# frozen_string_literal: true require "spec_helper" describe Charge::Chargeable do describe ".find_by_stripe_event" do describe "for an event on a Purchase" do it "finds the purchase using charge reference that is purchase's external id" do purchase = create(:purchase, id: 12345) event = build(:charge_event_dispute_formalized, charge_reference: purchase.external_id) expect(Charge::Chargeable.find_by_stripe_event(event)).to eq(purchase) end it "finds the purchase using charge id that is purchase's stripe transaction id" do purchase = create(:purchase, stripe_transaction_id: "ch_12345") event = build(:charge_event_dispute_formalized, charge_reference: nil, charge_id: "ch_12345") expect(Charge::Chargeable.find_by_stripe_event(event)).to eq(purchase) end it "finds the purchase using processor payment intent id" do purchase = create(:purchase) processor_payment_intent_id = "pi_123456" purchase.create_processor_payment_intent!(intent_id: processor_payment_intent_id) event = build(:charge_event_dispute_formalized, charge_reference: nil, charge_id: nil, processor_payment_intent_id:) expect(Charge::Chargeable.find_by_stripe_event(event)).to eq(purchase) end end describe "for an event on a Charge" do it "finds the charge using charge reference that is charge's id" do charge = create(:charge, id: 12345) event = build(:charge_event_dispute_formalized, charge_reference: "CH-12345") expect(Charge::Chargeable.find_by_stripe_event(event)).to eq(charge) end it "finds the charge using charge id that is charge's processor transaction id" do charge = create(:charge, processor_transaction_id: "ch_12345") event = build(:charge_event_dispute_formalized, charge_reference: "CH-12345", charge_id: "ch_12345") expect(Charge::Chargeable.find_by_stripe_event(event)).to eq(charge) end it "finds the charge using processor payment intent id" do charge = create(:charge, stripe_payment_intent_id: "pi_123456") event = build(:charge_event_dispute_formalized, charge_reference: "CH-12345", charge_id: nil, processor_payment_intent_id: "pi_123456") expect(Charge::Chargeable.find_by_stripe_event(event)).to eq(charge) end end end describe ".find_by_processor_transaction_id!" do let(:processor_transaction_id) { "ch_123456" } context "without a matching processor_transaction_id" do it "raises an error" do expect do Charge::Chargeable.find_by_processor_transaction_id!(processor_transaction_id) end.to raise_error(ActiveRecord::RecordNotFound) end end context "with a matching processor_transaction_id for a purchase" do let!(:purchase) { create(:purchase, stripe_transaction_id: processor_transaction_id) } it "returns the purchase" do expect(Charge::Chargeable.find_by_processor_transaction_id!(processor_transaction_id)).to eq(purchase) end context "with a matching processor_transaction_id for a charge" do let!(:charge) { create(:charge, processor_transaction_id:, purchases: [purchase]) } it "returns the charge" do expect(Charge::Chargeable.find_by_processor_transaction_id!(processor_transaction_id)).to eq(charge) end end end end describe ".find_by_purchase_or_charge!" do context "when both arguments are nil" do it "raises an error" do expect do Charge::Chargeable.find_by_purchase_or_charge!(purchase: nil, charge: nil) end.to raise_error(ArgumentError).with_message("Either purchase or charge must be present") end end let(:purchase) { create(:purchase) } context "when the purchase belongs to a charge" do let(:charge) { create(:charge) } before do charge.purchases << purchase end context "when both arguments are present" do it "raises an error" do expect do Charge::Chargeable.find_by_purchase_or_charge!(purchase:, charge:) end.to raise_error(ArgumentError).with_message("Only one of purchase or charge must be present") end end context "when the charge_id is provided" do it "returns the purchase's charge" do expect(Charge::Chargeable.find_by_purchase_or_charge!(purchase:)).to eq(charge) end end end context "when the purchase does not belong to a charge" do it "returns the purchase" do expect(Charge::Chargeable.find_by_purchase_or_charge!(purchase:)).to eq(purchase) end end end describe "#support_email" do let(:user_level_support_email) { "user-level-support@example.com" } let(:product_level_support_email) { "product-level-support@example.com" } let(:seller) { create(:named_seller, support_email: user_level_support_email) } context "on a purchase" do let(:chargeable) { create(:purchase, link: product, seller:) } context "when link's support email is set" do let(:product) { create(:product, support_email: product_level_support_email, user: seller) } it "returns support_email of the link" do expect(chargeable.support_email).to eq(product_level_support_email) end end context "when link's support email is not set" do let(:product) { create(:product, support_email: nil, user: seller) } it "returns seller.support_or_form_email" do expect(chargeable.support_email).to eq(user_level_support_email) end end end context "on a charge" do context "when all purchases links have the same support email" do let(:chargeable) { create(:charge, purchases: [purchase1, purchase2], seller:) } let(:product1) { create(:product, support_email: product_level_support_email, user: seller) } let(:product2) { create(:product, support_email: product_level_support_email, user: seller) } let(:purchase1) { create(:purchase, link: product1, seller:) } let(:purchase2) { create(:purchase, link: product2, seller:) } it "returns the product level support email" do expect(chargeable.support_email).to eq(product_level_support_email) end end context "when not all purchases links have the same support email" do let(:chargeable) { create(:charge, purchases: [purchase1, purchase2], seller:) } let(:product1) { create(:product, support_email: product_level_support_email, user: seller) } let(:product2) { create(:product, support_email: nil, user: seller) } let(:purchase1) { create(:purchase, link: product1, seller:) } let(:purchase2) { create(:purchase, link: product2, seller:) } it "returns the user level support email" do expect(chargeable.support_email).to eq(user_level_support_email) end end end end describe "#charged_purchases" do describe "for a Charge" do it "returns an array containing all non-free purchases included in the Charge" do purchase1 = create(:purchase) purchase2 = create(:purchase) purchase3 = create(:purchase) free_purchase = create(:free_purchase) free_trial_membership_purchase = create(:free_trial_membership_purchase) charge = create(:charge, purchases: [purchase1, purchase2, purchase3, free_purchase, free_trial_membership_purchase]) expect(charge.charged_purchases).to eq([purchase1, purchase2, purchase3]) end end describe "for a Purchase" do it "returns a single-item array containing purchase itself" do purchase = create(:purchase) create(:purchase) expect(purchase.charged_purchases).to eq([purchase]) end end end describe "#successful_purchases" do describe "for a Charge" do it "returns an array containing all purchases included in the Charge" do charge = create(:charge) purchase1 = create(:purchase) purchase2 = create(:purchase) purchase3 = create(:purchase, purchase_state: "failed") charge.purchases << purchase1 charge.purchases << purchase2 charge.purchases << purchase3 expect(charge.successful_purchases).to eq([purchase1, purchase2]) end end describe "for a Purchase" do it "returns the purchase itself" do purchase = create(:purchase) create(:purchase) expect(purchase.successful_purchases).to eq([purchase]) end end end describe "#update_processor_fee_cents!", :vcr do describe "for a Purchase" do it "updates processor_fee_cents on the purchase" do purchase = create(:purchase, total_transaction_cents: 20_00) purchase.update_processor_fee_cents!(processor_fee_cents: 2_00) expect(purchase.processor_fee_cents).to eq 2_00 end end describe "for a Charge" do it "does nothing if input processor_fee_cents is nil" do charge = create(:charge, amount_cents: 100_00, processor_fee_cents: nil) purchase = create(:purchase, total_transaction_cents: 20_00) charge.purchases << purchase expect { charge.update_processor_fee_cents!(processor_fee_cents: nil) }.not_to raise_error expect(charge.reload.processor_fee_cents).to be nil expect(purchase.reload.processor_fee_cents).to be nil end it "updates processor_fee_cents on included purchases in proper ratio" do charge = create(:charge, amount_cents: 100_00) purchase1 = create(:purchase, total_transaction_cents: 20_00) purchase2 = create(:purchase, total_transaction_cents: 30_00) purchase3 = create(:purchase, total_transaction_cents: 50_00) charge.purchases << purchase1 charge.purchases << purchase2 charge.purchases << purchase3 charge.update_processor_fee_cents!(processor_fee_cents: 10_00) expect(charge.reload.processor_fee_cents).to eq 10_00 expect(purchase1.reload.processor_fee_cents).to eq 2_00 expect(purchase2.reload.processor_fee_cents).to eq 3_00 expect(purchase3.reload.processor_fee_cents).to eq 5_00 end end end describe "#charged_amount_cents" do context "then the chargeable is a charge" do let(:charge) { create(:charge, amount_cents: 123_00) } let(:purchase1) { create(:purchase, total_transaction_cents: 20_00) } let(:purchase2) { create(:purchase, total_transaction_cents: 30_00) } let(:purchase3) { create(:purchase, total_transaction_cents: 50_00, purchase_state: "failed") } before do charge.purchases << purchase1 charge.purchases << purchase2 charge.purchases << purchase3 end it "returns the sum of successful purchases" do expect(charge.charged_amount_cents).to eq(50_00) end end it "returns the total_transaction_cents for a Purchase" do purchase = create(:purchase, total_transaction_cents: 3210) expect(purchase.charged_amount_cents).to eq(3210) end end describe "#charged_gumroad_amount_cents" do it "returns the gumroad_amount_cents for a Charge" do charge = create(:charge, gumroad_amount_cents: 230) expect(charge.charged_gumroad_amount_cents).to eq(230) end it "returns the total_transaction_amount_for_gumroad_cents for a Purchase" do purchase = create(:purchase, total_transaction_cents: 2000, affiliate_credit_cents: 500, fee_cents: 300) expect(purchase.charged_gumroad_amount_cents).to eq(purchase.total_transaction_amount_for_gumroad_cents) end end describe "#unbundled_purchases" do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller, is_bundle: true) } let(:chargeable) { create(:purchase, link: product, seller:) } context "when is not a bundle purchase" do before do product.update!(is_bundle: false) end it "returns the same purchase" do expect(chargeable.unbundled_purchases).to eq([chargeable]) end end context "when is a bundle purchase" do let!(:bundled_product_one) { create(:bundle_product, bundle: product, product: create(:product, user: seller)) } let!(:bundled_product_two) { create(:bundle_product, bundle: product, product: create(:product, user: seller)) } before do chargeable.create_artifacts_and_send_receipt! end it "returns purchases for bundled products" do expect(chargeable.unbundled_purchases.size).to eq(2) expect(chargeable.unbundled_purchases.first.link).to eq(bundled_product_one.product) expect(chargeable.unbundled_purchases.second.link).to eq(bundled_product_two.product) end end end describe "#is_recurring_subscription_charge" do context "when is a Charge" do let(:charge) { create(:charge) } it "returns false" do expect(charge.is_recurring_subscription_charge).to eq(false) end end context "when is a Purchase" do let(:original_membership_purchase) { create(:membership_purchase) } let!(:recurring_membership_purchase) do create(:purchase, link: original_membership_purchase.link, subscription: original_membership_purchase.subscription) end context "when the purchase is the original purchase" do it "returns false" do expect(original_membership_purchase.is_recurring_subscription_charge).to eq(false) end end context "when the purchase is a recurring purchase" do it "returns true" do expect(recurring_membership_purchase.is_recurring_subscription_charge).to eq(true) end end end end describe "#taxable?" do context "when is a Charge" do let(:charge) { create(:charge) } before do allow(charge).to receive(:taxable?).and_return("super") end it "calls super" do expect(charge.taxable?).to eq("super") end end context "when is a Purchase" do let(:purchase) { create(:purchase) } before do allow_any_instance_of(Purchase).to receive(:was_purchase_taxable?).and_return("super") end it "calls super" do expect(purchase.taxable?).to eq("super") end end end describe "#multi_item_charge?" do context "when is a Charge" do context "with one purchase" do let(:charge) { create(:charge, purchases: [create(:purchase)]) } it "returns false" do expect(charge.multi_item_charge?).to eq(false) end end context "with multiple purchases" do let(:charge) { create(:charge, purchases: [create(:purchase), create(:purchase)]) } it "returns true" do expect(charge.multi_item_charge?).to eq(true) end end end context "when is a Purchase" do let(:purchase) { create(:purchase) } it "returns false" do expect(purchase.multi_item_charge?).to eq(false) end end end describe "#taxed_by_gumroad?" do context "when is a Charge" do let!(:charge) { create(:charge) } before do allow(charge).to receive(:taxed_by_gumroad?).and_return("super") end it "calls super" do expect(charge.taxed_by_gumroad?).to eq("super") end end context "when is a Purchase" do let(:purchase) { create(:purchase) } context "when gumroad_tax_cents is zero" do before do purchase.update!(gumroad_tax_cents: 0) end it "returns false" do expect(purchase.taxed_by_gumroad?).to eq(false) end end context "when gumroad_tax_cents is greater than zero" do before do purchase.update!(gumroad_tax_cents: 100) end it "returns true" do expect(purchase.taxed_by_gumroad?).to eq(true) end end end end describe "#external_id_for_invoice" do context "when is a Charge" do let!(:charge) { create(:charge) } before do allow(charge).to receive(:external_id_for_invoice).and_return("super") end it "calls super" do expect(charge.external_id_for_invoice).to eq("super") end end context "when is a Purchase" do let(:purchase) { create(:purchase) } before do allow_any_instance_of(Purchase).to receive(:external_id).and_return("super") end it "calls super" do expect(purchase.external_id_for_invoice).to eq("super") end end end describe "#external_id_numeric_for_invoice" do context "when is a Charge" do let!(:charge) { create(:charge) } before do allow(charge).to receive(:external_id_numeric_for_invoice).and_return("super") end it "calls super" do expect(charge.external_id_numeric_for_invoice).to eq("super") end end context "when is a Purchase" do let(:purchase) { create(:purchase) } before do allow_any_instance_of(Purchase).to receive(:external_id_numeric).and_return("super") end it "calls super" do expect(purchase.external_id_numeric_for_invoice).to eq("super") end end end describe "#subscription" do context "when is a Charge" do let!(:charge) { build(:charge) } it "returns nil" do expect(charge.subscription).to eq(nil) end end context "when is a Purchase" do let(:subscription) { build(:subscription) } let!(:purchase) { build(:purchase, subscription:) } it "returns subscription" do expect(purchase.subscription).to eq(subscription) 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/concerns/video_file/has_thumbnail_spec.rb
spec/models/concerns/video_file/has_thumbnail_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe VideoFile::HasThumbnail do subject(:video_file) { build(:video_file) } let(:jpg_image) { fixture_file_upload("test.jpg") } let(:png_image) { fixture_file_upload("test.png") } let(:gif_image) { fixture_file_upload("test.gif") } describe "validations" do context "when no thumbnail is attached" do it "is valid" do expect(video_file.valid?).to eq(true) end end context "when a valid thumbnail is attached" do it "is valid with a JPG image" do video_file.thumbnail.attach(jpg_image) expect(video_file.valid?).to eq(true) end it "is valid with a PNG image" do video_file.thumbnail.attach(png_image) expect(video_file.valid?).to eq(true) end it "is valid with a GIF image" do video_file.thumbnail.attach(gif_image) expect(video_file.valid?).to eq(true) end end context "when the thumbnail has an invalid content type" do let(:txt_file) { fixture_file_upload("blah.txt") } let(:mp4_file) { fixture_file_upload("test.mp4") } it "is invalid with a text file" do video_file.thumbnail.attach(txt_file) expect(video_file.valid?).to eq(false) expect(video_file.errors[:thumbnail]).to include("must be a JPG, PNG, or GIF image.") end it "is invalid with a video file" do video_file.thumbnail.attach(mp4_file) expect(video_file.valid?).to eq(false) expect(video_file.errors[:thumbnail]).to include("must be a JPG, PNG, or GIF image.") end end context "when the thumbnail is too large" do let(:large_image_over_5mb) { fixture_file_upload("P1110259.JPG") } it "is invalid with a file over 5MB" do video_file.thumbnail.attach(large_image_over_5mb) expect(video_file.valid?).to eq(false) expect(video_file.errors[:thumbnail]).to include("must be smaller than 5 MB.") end end end describe "#preview_thumbnail_url" do context "when a thumbnail is attached" do it "returns a valid representation URL" do video_file.thumbnail.attach(jpg_image) video_file.save! expect(video_file.thumbnail_url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{video_file.thumbnail.key}") video_file.thumbnail.variant(:preview).processed expect(video_file.thumbnail_url).to eq("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{video_file.thumbnail.variant(:preview).key}") end end context "when no thumbnail is attached" do it "returns nil" do expect(video_file.thumbnail_url).to be_nil end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/payment/failure_reason_spec.rb
spec/models/concerns/payment/failure_reason_spec.rb
# frozen_string_literal: true require "spec_helper" describe Payment::FailureReason do let(:payment) { create(:payment) } describe "#add_payment_failure_reason_comment" do context "when failure_reason is not present" do it "doesn't add payout note to the user" do expect do payment.mark_failed! end.to_not change { payment.user.comments.count } end end context "when failure_reason is present" do context "when processor is PAYPAL" do context "when solution is present" do it "adds payout note to the user" do expect do payment.mark_failed!("PAYPAL 11711") end.to change { payment.user.comments.count }.by(1) payout_note = "Payout via Paypal on #{payment.created_at} failed because per-transaction sending limit exceeded. " payout_note += "Solution: Contact PayPal to get receiving limit on the account increased. " payout_note += "If that's not possible, Gumroad can split their payout, please contact Gumroad Support." expect(payment.user.comments.last.content).to eq payout_note end end context "when solution is not present" do it "doesn't add payout note to the user" do expect do payment.mark_failed!("PAYPAL unknown_failure_reason") end.to_not change { payment.user.comments.count } end end end context "when processor is Stripe" do before do payment.update!(processor: PayoutProcessorType::STRIPE) end context "when solution is present" do it "adds payout note to the user" do expect do payment.mark_failed!("account_closed") end.to change { payment.user.comments.count }.by(1) payout_note = "Payout via Stripe on #{payment.created_at} failed because the bank account has been closed. " payout_note += "Solution: Use another bank account." expect(payment.user.comments.last.content).to eq payout_note end end context "when solution is not present" do it "doesn't add payout note to the user" do expect do payment.mark_failed!("unknown_failure_reason") end.to_not change { payment.user.comments.count } 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/concerns/order/orderable_spec.rb
spec/models/concerns/order/orderable_spec.rb
# frozen_string_literal: true require "spec_helper" describe Order::Orderable do describe "For Purchase" do let(:purchase) { create(:purchase) } describe "#require_shipping?" do context "when the product is not physical" do it "returns false" do expect(purchase.require_shipping?).to be(false) end end context "when the purchase if for a physical product" do let(:product) { create(:product, :is_physical) } let(:purchase) { create(:physical_purchase, link: product) } it "returns true" do expect(purchase.require_shipping?).to be(true) end end end describe "#receipt_for_gift_receiver?" do context "when the purchase is not for a gift receiver" do it "returns false" do expect(purchase.receipt_for_gift_receiver?).to be(false) end end context "when the purchase is for a gift receiver" do let(:gift) { create(:gift) } let!(:gifter_purchase) { create(:purchase, link: gift.link, gift_given: gift, is_gift_sender_purchase: true) } let(:purchase) { create(:purchase, link: gift.link, gift_received: gift, is_gift_receiver_purchase: true) } it "returns true" do expect(purchase.receipt_for_gift_receiver?).to be(true) end end end describe "#receipt_for_gift_sender?" do context "when the purchase is not for a gift sender" do it "returns false" do expect(purchase.receipt_for_gift_sender?).to be(false) end end context "when the purchase is for a gift sender" do let(:gift) { create(:gift) } before do purchase.update!(is_gift_sender_purchase: true, gift_given: gift) end it "returns true" do expect(purchase.receipt_for_gift_sender?).to be(true) end end end describe "#test?" do context "when the purchase is not a test purchase" do it "returns false" do expect(purchase.test?).to be(false) end end context "when the purchase is a test purchase" do let(:purchase) { create(:test_purchase) } it "returns true" do expect(purchase.test?).to be(true) end end end describe "#seller_receipt_enabled?" do it "returns false" do expect(purchase.seller_receipt_enabled?).to be(false) end end end describe "For Order" do let(:failed_purchase) { create(:failed_purchase) } let(:purchase) { create(:purchase) } let(:order) { create(:order, purchases: [failed_purchase, purchase]) } describe "#require_shipping?" do before do allow(order).to receive(:require_shipping?).and_return("super") end it "calls super" do expect(order.require_shipping?).to eq("super") end end describe "#receipt_for_gift_receiver?" do before do allow(order).to receive(:receipt_for_gift_receiver?).and_return("super") end it "calls super" do expect(order.receipt_for_gift_receiver?).to eq("super") end end describe "#receipt_for_gift_sender?" do before do allow(order).to receive(:receipt_for_gift_sender?).and_return("super") end it "calls super" do expect(order.receipt_for_gift_sender?).to eq("super") end end describe "#test?" do before do allow(order).to receive(:test?).and_return("super") end it "calls super" do expect(order.test?).to eq("super") end end describe "#seller_receipt_enabled?" do before do allow(order).to receive(:seller_receipt_enabled?).and_return("super") end it "calls super" do expect(order.seller_receipt_enabled?).to eq("super") end end end describe "#uses_charge_receipt?" do context "when is an Order" do let(:order) { create(:order) } it "returns true" do expect(order.uses_charge_receipt?).to eq(true) end end context "when is a Purchase" do let(:purchase) { create(:purchase) } context "when there is no charge associated" do it "returns false" do expect(purchase.uses_charge_receipt?).to eq(false) end end context "when there is an order associated without a charge" do let(:order) { create(:order) } before do order.purchases << purchase end it "returns false" do expect(purchase.charge).to be(nil) expect(purchase.uses_charge_receipt?).to eq(false) end end context "when there is a charge associated" do let(:charge) { create(:charge) } before do charge.purchases << purchase end it "returns true" do expect(purchase.uses_charge_receipt?).to eq(true) 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/concerns/balance/refund_eligibility_underwriter_spec.rb
spec/models/concerns/balance/refund_eligibility_underwriter_spec.rb
# frozen_string_literal: true require "spec_helper" describe Balance::RefundEligibilityUnderwriter do describe "#update_seller_refund_eligibility" do let(:user) { create(:user) } # Eagerly create this so `expect` block doesn't enqueue any jobs due to creating this. let!(:balance) { create(:balance, user: user, amount_cents: 1000) } context "when user_id is blank" do before do balance.user_id = nil end it "does not enqueue the job" do expect { balance.update!(holding_amount_cents: 5000) }.not_to enqueue_sidekiq_job(UpdateSellerRefundEligibilityJob) end end context "when amount_cents changes" do context "when balance increases and refunds are disabled" do before { user.disable_refunds! } it "enqueues the job" do expect { balance.update!(amount_cents: 2000) } .to enqueue_sidekiq_job(UpdateSellerRefundEligibilityJob).with(user.id) end end context "when balance increases and refunds are enabled" do before { user.enable_refunds! } it "does not enqueue the job" do expect { balance.update!(amount_cents: 2000) } .not_to enqueue_sidekiq_job(UpdateSellerRefundEligibilityJob) end end context "when balance decreases and refunds are disabled" do before { user.disable_refunds! } it "does not enqueue the job" do expect { balance.update!(amount_cents: 500) } .not_to enqueue_sidekiq_job(UpdateSellerRefundEligibilityJob) end end context "when balance decreases and refunds are enabled" do before { user.enable_refunds! } it "enqueues the job" do expect { balance.update!(amount_cents: 500) } .to enqueue_sidekiq_job(UpdateSellerRefundEligibilityJob).with(user.id) end end end context "when amount_cents does not change" do it "does not enqueue the job" do expect { balance.mark_processing! } .not_to enqueue_sidekiq_job(UpdateSellerRefundEligibilityJob) 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/concerns/balance/searchable_spec.rb
spec/models/concerns/balance/searchable_spec.rb
# frozen_string_literal: true require "spec_helper" describe Balance::Searchable do describe "#as_indexed_json" do let(:balance) { create(:balance, amount_cents: 123, state: "unpaid") } it "includes all fields" do expect(balance.as_indexed_json).to eq( "user_id" => balance.user_id, "amount_cents" => 123, "state" => "unpaid" ) end it "allows only a selection of fields to be used" do expect(balance.as_indexed_json(only: ["amount_cents"])).to eq( "amount_cents" => 123 ) end end describe ".amount_cents_sum_for", :sidekiq_inline, :elasticsearch_wait_for_refresh do before do @user_1 = create(:user) @user_2 = create(:user) end it "returns sum of unpaid balance in cents" do create(:balance, user: @user_1, amount_cents: 100, state: "unpaid", date: 1.day.ago) create(:balance, user: @user_2, amount_cents: 100, state: "unpaid", date: 2.days.ago) create(:balance, user: @user_1, amount_cents: 150, state: "unpaid", date: 3.days.ago) create(:balance, user: @user_1, amount_cents: 150, state: "paid", date: 4.days.ago) expect(Balance.amount_cents_sum_for(@user_1)).to eq(250) expect(Balance.amount_cents_sum_for(@user_2)).to eq(100) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/purchase/charge_events_handler_spec.rb
spec/models/concerns/purchase/charge_events_handler_spec.rb
# frozen_string_literal: true require "spec_helper" describe Purchase::ChargeEventsHandler, :vcr do include CurrencyHelper include ProductsHelper describe "charge event looked up by external ID" do let(:purchase) { create(:purchase, price_cents: 100, total_transaction_cents: 100, fee_cents: 30) } let(:event) { build(:charge_event_dispute_formalized, charge_reference: purchase.external_id) } before do allow_any_instance_of(Purchase).to receive(:create_dispute_evidence_if_needed!).and_return(nil) end it "uses charge_reference which is expected to be the purchase external ID" do Purchase.handle_charge_event(event) purchase.reload expect(purchase.stripe_status).to eq(event.comment) expect(purchase.chargeback_date.to_i).to eq(event.created_at.to_i) end end describe "setting the purchase fee from a charge event" do before do @l = create(:product) @p = create(:purchase, link: @l, seller: @l.user, price_cents: 100, total_transaction_cents: 100) @p.processor_fee_cents = 0 @p.save! @e = build(:charge_event_informational, charge_reference: @p.external_id, extras: { "fee_cents" => 30_00 }) end it "set the fee on the purchase if the information charge event has the info" do expect(@p.processor_fee_cents).to eq(0) Purchase.handle_charge_event(@e) @p.reload expect(@p.stripe_status).to eq(@e.comment) expect(@p.processor_fee_cents).to eq(@e.extras["fee_cents"]) end end describe "informational charge event for purchase" do before do @initial_balance = 200 @u = create(:user, unpaid_balance_cents: @initial_balance) @l = create(:product, user: @u) @p = create(:purchase, link: @l, seller: @l.user, stripe_transaction_id: "ch_zitkxbhds3zqlt", price_cents: 100, total_transaction_cents: 100, fee_cents: 30) @e = build(:charge_event_informational, charge_id: "ch_zitkxbhds3zqlt") allow_any_instance_of(Purchase).to receive(:fight_chargeback).and_return(true) end it "does not affect seller balance" do Purchase.handle_charge_event(@e) @p.reload @u.reload verify_balance(@u, @initial_balance) end it "updates purchase current status" do Purchase.handle_charge_event(@e) @p.reload expect(@p.stripe_status).to eq @e.comment end end describe "charge succeeded event for purchase" do let(:initial_balance) { 200 } let(:seller) { create(:user, unpaid_balance_cents: initial_balance) } let!(:recurring_purchase) do create( :recurring_membership_purchase, stripe_transaction_id: "ch_2ORDpK9e1RjUNIyY0eJyh91P", price_cents: 100, total_transaction_cents: 100, fee_cents: 30, purchase_state: "in_progress", card_country: Compliance::Countries::IND.alpha2 ) end let(:event) { build(:charge_event_charge_succeeded, charge_id: "ch_2ORDpK9e1RjUNIyY0eJyh91P") } before do expect_any_instance_of(Purchase).to receive(:handle_event_informational!).and_call_original expect_any_instance_of(Purchase).to receive(:save_charge_data) expect_any_instance_of(Purchase).to receive(:update_balance_and_mark_successful!) end it "does not affect seller balance" do Purchase.handle_charge_event(event) recurring_purchase.reload seller.reload verify_balance(seller, initial_balance) end it "updates purchase current status" do Purchase.handle_charge_event(event) recurring_purchase.reload expect(recurring_purchase.stripe_status).to eq event.comment end end describe "payment failed event for purchase" do before do @initial_balance = 200 @u = create(:user, unpaid_balance_cents: @initial_balance) @l = create(:product, user: @u) subscription = create(:subscription) create(:membership_purchase, subscription:) purchase_external_id = "q3jUBQrrGrIId3SjC4VJ0g==" @p = create(:purchase, id: ObfuscateIds.decrypt(purchase_external_id), link: @l, seller: @l.user, price_cents: 100, total_transaction_cents: 100, fee_cents: 30, purchase_state: "in_progress", card_country: "IN", subscription:) @e = build(:charge_event_payment_failed, charge_reference: purchase_external_id) allow(Purchase).to receive(:find_by_external_id).with(purchase_external_id).and_return(@p) expect_any_instance_of(Purchase).to receive(:handle_event_informational!).and_call_original expect_any_instance_of(Subscription).to receive(:handle_purchase_failure) end it "does not affect seller balance" do Purchase.handle_charge_event(@e) @p.reload @u.reload verify_balance(@u, @initial_balance) end it "updates purchase current status" do Purchase.handle_charge_event(@e) @p.reload expect(@p.stripe_status).to eq @e.comment end it "finds the purchase using processor_payment_intent and marks it as failed" do processor_payment_intent_id = "pi_123456" @p.create_processor_payment_intent!(intent_id: processor_payment_intent_id) event = build(:charge_event_payment_failed, charge_id: nil, processor_payment_intent_id:) expect(event.charge_reference).to be nil expect(event.charge_id).to be nil expect(event.processor_payment_intent_id).to eq processor_payment_intent_id expect_any_instance_of(Purchase).to receive(:handle_event_failed!).and_call_original Purchase.handle_charge_event(event) end end describe "handles charge event notification" do let(:charge_event) { build(:charge_event_informational) } it "calls purchase's handle_charge_event" do expect(Purchase).to receive(:handle_charge_event).with(charge_event).once expect(ServiceCharge).to_not receive(:handle_charge_processor_event) ActiveSupport::Notifications.instrument(ChargeProcessor::NOTIFICATION_CHARGE_EVENT, charge_event:) end end describe "#handle charge event" do let(:transaction_id) { "ch_zitkxbhds3zqlt" } let(:initial_balance) { 10_000 } let(:seller) { create(:user, unpaid_balance_cents: initial_balance) } let(:product) { create(:product, user: seller) } let(:balance) { seller.balances.reload.last } let(:purchase) { create(:purchase, stripe_transaction_id: transaction_id, link: product) } let!(:purchase_event) { create(:event, event_name: "purchase", purchase_id: purchase.id, link_id: product.id) } let(:calculated_fingerprint) { "3dfakl93klfdjsa09rn" } it "handles stripe events correctly - type informational" do charge_event = build(:charge_event, charge_id: transaction_id, comment: "charge.succeeded") Purchase.handle_charge_event(charge_event) purchase.reload expect(purchase.stripe_status).to eq "charge.succeeded" end it "sets the purchase chargeback_date flag and email us" do charge_event = build(:charge_event_dispute_formalized, charge_id: transaction_id) mail = double("mail") expect(mail).to receive(:deliver_later) allow(AdminMailer).to receive(:chargeback_notify).and_return(mail) Purchase.handle_charge_event(charge_event) expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id) expect(AdminMailer).to have_received(:chargeback_notify).with(purchase.dispute.id) purchase.reload seller.reload verify_balance(seller, initial_balance - purchase.payment_cents) expect(purchase.purchase_chargeback_balance).to eq balance expect(purchase.chargeback_date.to_i).to eq charge_event.created_at.to_i expect(Event.last.event_name).to eq "chargeback" expect(Event.last.purchase_id).to eq purchase.id end it "enqueues LowBalanceFraudCheckWorker" do charge_event = build(:charge_event_dispute_formalized, charge_id: transaction_id) Purchase.handle_charge_event(charge_event) expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id) expect(LowBalanceFraudCheckWorker).to have_enqueued_sidekiq_job(purchase.id) end it "enqueues UpdateSalesRelatedProductsInfosJob" do UpdateSalesRelatedProductsInfosJob.jobs.clear Purchase.handle_charge_event(build(:charge_event_dispute_formalized, charge_id: transaction_id)) expect(FightDisputeJob).to have_enqueued_sidekiq_job(purchase.dispute.id) expect(UpdateSalesRelatedProductsInfosJob).to have_enqueued_sidekiq_job(purchase.id, false) end it "updates dispute evidence as seller contacted" do charge_event = build(:charge_event_dispute_formalized, charge_id: transaction_id) Purchase.handle_charge_event(charge_event) expect(purchase.dispute.dispute_evidence.seller_contacted?).to eq(true) end context "when the purchase is not eligible for a dispute evidence" do before do allow_any_instance_of(Purchase).to receive(:eligible_for_dispute_evidence?).and_return(false) end it "doesn't enqueue FightDisputeJob job" do charge_event = build(:charge_event_dispute_formalized, charge_id: transaction_id) Purchase.handle_charge_event(charge_event) expect(FightDisputeJob).not_to have_enqueued_sidekiq_job(purchase.dispute.id) end end context "when a chargeback is reversed" do it "enqueues UpdateSalesRelatedProductsInfosJob" do purchase.update!(chargeback_date: 1.day.ago) UpdateSalesRelatedProductsInfosJob.jobs.clear Purchase.handle_charge_event(build(:charge_event_dispute_won, charge_id: transaction_id)) expect(UpdateSalesRelatedProductsInfosJob).to have_enqueued_sidekiq_job(purchase.id, true) end end it "handles dispute formalized event properly for partially refunded purchase" do partially_refunded_cents = 50 create(:refund, purchase:, amount_cents: 50, fee_cents: 15) purchase.stripe_partially_refunded = true purchase.save! amount_refundable_cents = purchase.amount_refundable_cents expect(amount_refundable_cents).to eq(purchase.price_cents - partially_refunded_cents) charge_event = build(:charge_event_dispute_formalized, charge_id: transaction_id) mail = double("mail") expect(mail).to receive(:deliver_later) expect(AdminMailer).to receive(:chargeback_notify).and_return(mail) Purchase.handle_charge_event(charge_event) # This will decrement 31c from seller balance purchase.reload seller.reload verify_balance(seller, initial_balance - (amount_refundable_cents * (1 - (purchase.fee_cents.to_f / purchase.price_cents.to_f))).ceil) # 10000 - (50 * (1 - (39 / 100))) = 9969 expect(purchase.purchase_chargeback_balance).to eq balance expect(purchase.chargeback_date.to_i).to eq charge_event.created_at.to_i expect(Event.last.event_name).to eq "chargeback" expect(Event.last.purchase_id).to eq purchase.id end describe "dispute formalized event for free trial subscriptions" do let(:charge_event) { build(:charge_event_dispute_formalized, charge_id: transaction_id) } let(:original_purchase) { create(:free_trial_membership_purchase, price_cents: 100, should_exclude_product_review: false) } let(:subscription) { original_purchase.subscription } let!(:purchase) do create(:purchase, stripe_transaction_id: transaction_id, subscription:, link: original_purchase.link, price_cents: 100, chargeback_date: Date.today - 10.days, url_redirect: create(:url_redirect)) end before do allow_any_instance_of(Purchase).to receive(:create_dispute_evidence_if_needed!).and_return(nil) end it "prevents the subscriber's review from being counted" do expect do Purchase.handle_charge_event(charge_event) end.to change { original_purchase.reload.should_exclude_product_review? }.from(false).to(true) end end # Can happen due to charge processor (Braintree) bugs describe "chargeback events for unsuccessful purchases" do let!(:purchase) do p = create(:purchase_with_balance) p.update!(purchase_state: "failed") p end describe "chargeback notification received" do it "does not process the message" do expect(purchase).to_not receive(:process_refund_or_chargeback_for_purchase_balance) expect(purchase).to_not receive(:process_refund_or_chargeback_for_affiliate_credit_balance) expect(Bugsnag).to receive(:notify) Purchase.handle_charge_event(build(:charge_event_dispute_formalized, charge_id: purchase.stripe_transaction_id)) end end describe "chargeback reversed notification received" do it "does not process the message" do expect(Credit).to_not receive(:create) expect(Bugsnag).to receive(:notify) Purchase.handle_charge_event(build(:charge_event_dispute_won, charge_id: purchase.stripe_transaction_id)) end end end describe "refunded purchase" do it "enqueues UpdateSalesRelatedProductsInfosJob" do purchase.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, 100), purchase.seller_id) expect(UpdateSalesRelatedProductsInfosJob).to have_enqueued_sidekiq_job(purchase.id, true) end end describe "settlement declined event" do let(:settlement_decline_flow_of_funds) { FlowOfFunds.build_simple_flow_of_funds(Currency::USD, -100) } describe "for a unsuccessful purchase" do before do purchase.purchase_state = "failed" purchase.save! end it "notifies bugsnag" do expect(Bugsnag).to receive(:notify) Purchase.handle_charge_event(build(:charge_event_dispute_formalized, charge_id: purchase.stripe_transaction_id)) end end describe "for a successful purchase" do it "marks the purchased as refunded, updates balances" do expect_any_instance_of(Purchase).to receive(:refund_purchase!).and_call_original expect_any_instance_of(Purchase).to receive(:process_refund_or_chargeback_for_purchase_balance) expect_any_instance_of(Purchase).to receive(:process_refund_or_chargeback_for_affiliate_credit_balance) expect_any_instance_of(Bugsnag).to_not receive(:notify) Purchase.handle_charge_event(build(:charge_event_settlement_declined, charge_id: purchase.stripe_transaction_id, flow_of_funds: settlement_decline_flow_of_funds)) end end end end def verify_balance(user, expected_balance) expect(user.unpaid_balance_cents).to eq expected_balance end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/purchase/reportable_spec.rb
spec/models/concerns/purchase/reportable_spec.rb
# frozen_string_literal: true require "spec_helper" describe Purchase::Reportable do let(:product) { create(:product) } let(:purchase) { create(:purchase, link: product) } describe "#price_cents_net_of_refunds" do it "returns the price" do expect(purchase.price_cents_net_of_refunds).to eq(100) end end context "when the purchase is chargedback" do before do purchase.update!(chargeback_date: Time.current) end it "returns 0" do expect(purchase.price_cents_net_of_refunds).to eq(0) end end context "when the purchase is fully refunded" do before do purchase.update!(stripe_refunded: true) end it "returns 0" do expect(purchase.price_cents_net_of_refunds).to eq(0) end end context "when the purchase is partially refunded" do before do purchase.update!(stripe_partially_refunded: true) end context "when the refunds don't have amounts" do before do create(:refund, purchase:, amount_cents: 0) end it "returns the price" do expect(purchase.price_cents_net_of_refunds).to eq(100) end end context "when refunds have amounts" do before do 2.times do create(:refund, purchase:, amount_cents: 10) end end it "returns the price minus refunded amount" do expect(purchase.price_cents_net_of_refunds).to eq(80) 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/concerns/purchase/custom_fields_spec.rb
spec/models/concerns/purchase/custom_fields_spec.rb
# frozen_string_literal: true require "spec_helper" describe Purchase::CustomFields do let(:purchase) { create(:purchase) } describe "validations" do it "invalidates the purchase when a custom field is invalid" do product = create(:product, custom_fields: [create(:custom_field, name: "http://test", type: "terms", required: true)]) purchase = build(:purchase, link: product) purchase.purchase_custom_fields << PurchaseCustomField.build_from_custom_field(custom_field: product.custom_fields.first, value: false) expect(purchase).to be_invalid expect(purchase.purchase_custom_fields.first.errors.full_messages).to contain_exactly("Value can't be blank") expect(purchase.errors.full_messages).to contain_exactly("Purchase custom fields is invalid") end end describe "#custom_fields" do context "when there are custom field records" do before do purchase.purchase_custom_fields << [ build(:purchase_custom_field, name: "Text", value: "Value", type: CustomField::TYPE_TEXT), build(:purchase_custom_field, name: "Truthy", value: true, type: CustomField::TYPE_CHECKBOX), build(:purchase_custom_field, name: "Falsy", value: false, type: CustomField::TYPE_CHECKBOX), build(:purchase_custom_field, name: "http://terms", value: true, type: CustomField::TYPE_TERMS) ] end it "returns the custom field records" do expect(purchase.custom_fields).to eq( [ { name: "Text", value: "Value", type: CustomField::TYPE_TEXT }, { name: "Truthy", value: true, type: CustomField::TYPE_CHECKBOX }, { name: "Falsy", value: false, type: CustomField::TYPE_CHECKBOX }, { name: "http://terms", value: true, type: CustomField::TYPE_TERMS } ] ) end end context "when there are no custom field records" do it "returns an empty array" do expect(purchase.custom_fields).to eq([]) 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/concerns/purchase/searchable_spec.rb
spec/models/concerns/purchase/searchable_spec.rb
# frozen_string_literal: true require "spec_helper" describe Purchase::Searchable do before do travel_to(Date.new(2019, 1, 1)) end describe "#indexed_json" do before do @product = create(:product, name: "My Product", user: create(:named_user)) @purchase = create(:purchase, :with_license, email: "buyer1@gmail.com", full_name: "Joe Buyer", chargeback_date: Time.utc(2019, 1, 2), is_gift_receiver_purchase: true, is_multi_buy: true, link: @product, ip_country: "Spain", variant_attributes: create_list(:variant, 2, variant_category: create(:variant_category, link: @product)), tax_cents: 29, card_type: "paypal", card_visual: "buyer1@paypal.com", purchaser: create(:user) ) end it "includes all fields" do json = @purchase.as_indexed_json expect(json).to eq( "id" => @purchase.id, "can_contact" => true, "chargeback_date" => "2019-01-02T00:00:00Z", "country_or_ip_country" => "Spain", "created_at" => "2019-01-01T00:00:00Z", "latest_charge_date" => nil, "email" => "buyer1@gmail.com", "email_domain" => "gmail.com", "paypal_email" => "buyer1@paypal.com", "fee_cents" => 93, # 100 * 0.129 + 50 + 30 "full_name" => "Joe Buyer", "not_chargedback_or_chargedback_reversed" => false, "not_refunded_except_subscriptions" => true, "not_subscription_or_original_subscription_purchase" => true, "successful_authorization_or_without_preorder" => true, "price_cents" => 100, "purchase_state" => "successful", "amount_refunded_cents" => 0, "fee_refunded_cents" => 0, "tax_refunded_cents" => 0, "selected_flags" => ["is_multi_buy", "is_gift_receiver_purchase"], "stripe_refunded" => false, "tax_cents" => 29, "monthly_recurring_revenue" => nil, "ip_country" => "Spain", "ip_state" => nil, "referrer_domain" => "direct", "variant_ids" => @purchase.variant_attributes.ids, "product_ids_from_same_seller_purchased_by_purchaser" => [@purchase.link_id], "variant_ids_from_same_seller_purchased_by_purchaser" => @purchase.variant_attributes.ids, "affiliate_credit_id" => nil, "affiliate_credit_affiliate_user_id" => nil, "affiliate_credit_amount_cents" => nil, "affiliate_credit_fee_cents" => nil, "affiliate_credit_amount_partially_refunded_cents" => nil, "affiliate_credit_fee_partially_refunded_cents" => nil, "product_id" => @product.id, "product_unique_permalink" => @product.unique_permalink, "product_name" => @product.name, "product_description" => @product.plaintext_description, "seller_id" => @purchase.seller.id, "seller_name" => @purchase.seller.name, "purchaser_id" => @purchase.purchaser.id, "subscription_id" => nil, "subscription_cancelled_at" => nil, "subscription_deactivated_at" => nil, "taxonomy_id" => nil, "license_serial" => @purchase.license.serial, ) @product.default_price.update!(recurrence: "yearly") @purchase.subscription = create(:subscription, link: @product, cancelled_at: Time.utc(2018, 1, 1), deactivated_at: Time.utc(2018, 1, 1)) @purchase.is_original_subscription_purchase = true @purchase.save! json = @purchase.as_indexed_json expect(json).to include( "subscription_id" => @purchase.subscription.id, "subscription_cancelled_at" => "2018-01-01T00:00:00Z", "subscription_deactivated_at" => "2018-01-01T00:00:00Z", "monthly_recurring_revenue" => 100.0 / 12, "not_refunded_except_subscriptions" => true, "not_subscription_or_original_subscription_purchase" => true, ) @purchase.is_original_subscription_purchase = false original_subscription_purchase = create(:purchase, is_original_subscription_purchase: true, subscription: @purchase.subscription) @purchase.save! json = @purchase.as_indexed_json expect(json).to include( "not_refunded_except_subscriptions" => true, "not_subscription_or_original_subscription_purchase" => false ) original_subscription_purchase.delete @purchase.subscription = nil @purchase.stripe_refunded = true @purchase.save! json = @purchase.as_indexed_json expect(json).to include( "stripe_refunded" => true, "not_refunded_except_subscriptions" => false, "not_subscription_or_original_subscription_purchase" => true ) @purchase.stripe_refunded = false @purchase.save! json = @purchase.as_indexed_json expect(json).to include( "stripe_refunded" => false, "not_refunded_except_subscriptions" => true, ) @purchase.chargeback_reversed = true @purchase.save! json = @purchase.as_indexed_json expect(json["not_chargedback_or_chargedback_reversed"]).to eq(true) @purchase.chargeback_date = nil @purchase.chargeback_reversed = false @purchase.save! json = @purchase.as_indexed_json expect(json["not_chargedback_or_chargedback_reversed"]).to eq(true) create(:refund, purchase: @purchase, amount_cents: 10, fee_cents: 1, creator_tax_cents: 3) create(:refund, purchase: @purchase, amount_cents: 20, fee_cents: 2, creator_tax_cents: 6) json = @purchase.as_indexed_json expect(json["amount_refunded_cents"]).to eq(30) expect(json["fee_refunded_cents"]).to eq(3) expect(json["tax_refunded_cents"]).to eq(9) affiliate_credit = create(:affiliate_credit, purchase: @purchase, amount_cents: 123, fee_cents: 15, affiliate_user: create(:user), ) create(:affiliate_partial_refund, affiliate_credit:, amount_cents: 11, fee_cents: 2) create(:affiliate_partial_refund, affiliate_credit:, amount_cents: 22, fee_cents: 4) json = @purchase.reload.as_indexed_json expect(json).to include( "affiliate_credit_id" => affiliate_credit.id, "affiliate_credit_affiliate_user_id" => affiliate_credit.affiliate_user.id, "affiliate_credit_amount_cents" => 123, "affiliate_credit_fee_cents" => 15, "affiliate_credit_amount_partially_refunded_cents" => 33, "affiliate_credit_fee_partially_refunded_cents" => 6, ) product_2 = create(:product, user: @purchase.seller) purchase_2 = create(:purchase, seller: @purchase.seller, email: @purchase.email, link: product_2, variant_attributes: [create(:variant, variant_category: create(:variant_category, link: product_2))], ) purchase_3 = create(:purchase, seller: @purchase.seller, link: product_2, variant_attributes: [create(:variant, variant_category: create(:variant_category, link: product_2))], ) json_1 = @purchase.as_indexed_json json_2 = purchase_2.as_indexed_json json_3 = purchase_3.as_indexed_json expect(json_1["product_ids_from_same_seller_purchased_by_purchaser"]).to match_array([@product.id, product_2.id]) expect(json_2["product_ids_from_same_seller_purchased_by_purchaser"]).to match_array([@product.id, product_2.id]) expect(json_3["product_ids_from_same_seller_purchased_by_purchaser"]).to match_array([product_2.id]) expect(json_1["variant_ids_from_same_seller_purchased_by_purchaser"]).to match_array(@purchase.variant_attributes.ids + purchase_2.variant_attributes.ids) expect(json_2["variant_ids_from_same_seller_purchased_by_purchaser"]).to match_array(@purchase.variant_attributes.ids + purchase_2.variant_attributes.ids) expect(json_3["variant_ids_from_same_seller_purchased_by_purchaser"]).to match_array(purchase_3.variant_attributes.ids) @purchase.subscription = create(:subscription) @purchase.is_original_subscription_purchase = true @purchase.save! purchase_2.purchase_state = "in_progress" purchase_2.subscription = @purchase.subscription purchase_2.created_at = Time.utc(2020, 6, 6) purchase_2.save! json = @purchase.as_indexed_json expect(json["latest_charge_date"]).to eq("2019-01-01T00:00:00Z") purchase_2.purchase_state = "successful" purchase_2.save! json = @purchase.as_indexed_json expect(json["latest_charge_date"]).to eq("2020-06-06T00:00:00Z") @purchase.update!(preorder: create(:preorder)) json = @purchase.as_indexed_json expect(json["successful_authorization_or_without_preorder"]).to eq(false) @purchase.update!(purchase_state: "preorder_authorization_successful") json = @purchase.as_indexed_json expect(json["successful_authorization_or_without_preorder"]).to eq(true) @purchase.update!(purchase_state: "preorder_concluded_unsuccessfully") json = @purchase.as_indexed_json expect(json["successful_authorization_or_without_preorder"]).to eq(false) @purchase.update!(purchase_state: "preorder_concluded_successfully") json = @purchase.as_indexed_json expect(json["successful_authorization_or_without_preorder"]).to eq(true) @purchase.update!(purchase_state: "failed") json = @purchase.as_indexed_json expect(json["successful_authorization_or_without_preorder"]).to eq(false) @purchase.update!(referrer: "https://twitter.com/gumroad") json = @purchase.as_indexed_json expect(json["referrer_domain"]).to eq("twitter.com") @purchase.was_product_recommended = true @purchase.save! json = @purchase.as_indexed_json expect(json["referrer_domain"]).to eq("recommended_by_gumroad") @purchase.update!(ip_country: "United States", ip_state: "CA") json = @purchase.as_indexed_json expect(json).to include( "ip_country" => "United States", "ip_state" => "CA" ) @purchase.update!(email: "name@yahoo.com") json = @purchase.as_indexed_json expect(json).to include( "email" => "name@yahoo.com", "email_domain" => "yahoo.com" ) @product.update!(taxonomy: create(:taxonomy)) json = @purchase.reload.as_indexed_json expect(json).to include( "taxonomy_id" => @product.taxonomy.id ) end it "supports only returning specific fields" do json = @purchase.as_indexed_json(only: ["full_name", "product_id"]) expect(json).to eq( "full_name" => "Joe Buyer", "product_id" => @product.id ) end end describe "Subscription Callbacks" do before do @subscription = create(:subscription) @purchase_1 = create(:purchase, subscription: @subscription, is_original_subscription_purchase: true) @purchase_2 = create(:purchase, subscription: @subscription) ElasticsearchIndexerWorker.jobs.clear end it "updates related purchases when deactivated_at changes" do @subscription.deactivate! expect(ElasticsearchIndexerWorker.jobs.size).to eq(2) expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("update", "record_id" => @purchase_1.id, "class_name" => "Purchase", "fields" => ["subscription_deactivated_at"]) expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("update", "record_id" => @purchase_2.id, "class_name" => "Purchase", "fields" => ["subscription_deactivated_at"]) end it "does not update related purchases when unrelated attributes changes" do @subscription.charge_occurrence_count = 123 @subscription.save! expect(ElasticsearchIndexerWorker.jobs.size).to eq(0) end end describe "RelatedPurchase Callbacks" do before do @seller = create(:user) @product = create(:product, user: @seller) @variant_1, @variant_2 = create_list(:variant, 2, variant_category: create(:variant_category, link: @product)) @purchase = create(:purchase, link: @product, variant_attributes: [@variant_1]) index_model_records(Purchase) ElasticsearchIndexerWorker.jobs.clear end context "when creating successful purchase" do before do @product_2 = create(:product, user: @seller) @purchase_2 = create(:purchase, seller: @seller, link: @product_2, email: @purchase.email) end it "queues update_by_query for related purchases documents" do expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job(*update_related_purchases_job_params(@purchase_2)) end it "updates related purchases documents", :sidekiq_inline, :elasticsearch_wait_for_refresh do purchase_1_doc = get_document_attributes(@purchase) expect(purchase_1_doc["product_ids_from_same_seller_purchased_by_purchaser"]).to eq([@product.id, @product_2.id]) expect(purchase_1_doc["variant_ids_from_same_seller_purchased_by_purchaser"]).to eq([@variant_1.id]) end end context "when creating non-successful purchase" do before do product_2 = create(:product, user: @seller) @purchase_2 = create(:purchase_in_progress, seller: @seller, link: product_2, email: @purchase.email) @purchase_3 = create(:failed_purchase, seller: @seller, link: product_2, email: @purchase.email) end it "does not queue update_by_query job" do expect(ElasticsearchIndexerWorker).not_to have_enqueued_sidekiq_job(*update_related_purchases_job_params(@purchase_2)) expect(ElasticsearchIndexerWorker).not_to have_enqueued_sidekiq_job(*update_related_purchases_job_params(@purchase_3)) end end context "when transitioning purchase to successful" do before do @product_2 = create(:product, user: @seller) @purchase_2 = create(:purchase_in_progress, seller: @seller, link: @product_2, email: @purchase.email) @purchase_2.mark_successful! end it "queues update_by_query for related purchases documents" do expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job(*update_related_purchases_job_params(@purchase_2)) end it "updates related purchases documents", :sidekiq_inline, :elasticsearch_wait_for_refresh do purchase_1_doc = get_document_attributes(@purchase) expect(purchase_1_doc["product_ids_from_same_seller_purchased_by_purchaser"]).to eq([@product.id, @product_2.id]) expect(purchase_1_doc["variant_ids_from_same_seller_purchased_by_purchaser"]).to eq([@variant_1.id]) end end context "when updating an irrelevant attribute" do before do @purchase.update!(can_contact: false) end it "does not queue update_by_query job" do expect(ElasticsearchIndexerWorker).not_to have_enqueued_sidekiq_job(*update_related_purchases_job_params(@purchase)) end end context "when creating a subscription purchase" do it "queues an update to related purchase's documents" do subscription = create(:subscription) @purchase.subscription = subscription @purchase.is_original_subscription_purchase = true @purchase.save! ElasticsearchIndexerWorker.jobs.clear create(:purchase, seller: @seller, link: @product, email: @purchase.email, subscription:) expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("update", "record_id" => @purchase.id, "class_name" => "Purchase", "fields" => ["latest_charge_date"]) end end context "with a subscription's new purchase" do before do subscription = create(:subscription) @purchase.subscription = subscription @purchase.is_original_subscription_purchase = true @purchase.save! @purchase_2 = create(:purchase, seller: @seller, link: @product, email: @purchase.email, subscription:, purchase_state: "in_progress") ElasticsearchIndexerWorker.jobs.clear end context "when updating purchase_state" do before do @purchase_2.update!(purchase_state: "successful") end it "queues an update to related purchases' documents" do expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job("update", "record_id" => @purchase.id, "class_name" => "Purchase", "fields" => ["latest_charge_date"]) end end context "when updating an irrelevant attribute" do before do @purchase_2.update!(can_contact: false) end it "does not queue an update to related purchases' documents" do expect(ElasticsearchIndexerWorker).not_to have_enqueued_sidekiq_job("update", "record_id" => @purchase.id, "class_name" => "Purchase", "fields" => ["latest_charge_date"]) end end context "when updating an irrelevant attribute on a successful purchase" do before do @purchase_2.update!(purchase_state: "successful") ElasticsearchIndexerWorker.jobs.clear @purchase_2.update!(can_contact: false) end it "does not queue an update to related purchases' documents" do expect(ElasticsearchIndexerWorker).not_to have_enqueued_sidekiq_job("update", "record_id" => @purchase.id, "class_name" => "Purchase", "fields" => ["latest_charge_date"]) end end end end describe "VariantAttribute Callbacks" do describe ".variants_changed" do before do product = create(:product) category = create(:variant_category, link: product) @variant_1, @variant_2 = create_list(:variant, 2, variant_category: category) @purchase_1, @purchase_2 = create_list(:purchase, 2, link: product, email: "joe@gmail.com", variant_attributes: [@variant_1] ) Purchase::VariantUpdaterService.new( purchase: @purchase_2, variant_id: @variant_2.external_id, quantity: @purchase_2.quantity, ).perform end it "queues udpate for purchase, and related purchases" do expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job( "update", "record_id" => @purchase_2.id, "class_name" => "Purchase", "fields" => ["variant_ids", "variant_ids_from_same_seller_purchased_by_purchaser"] ) expect(ElasticsearchIndexerWorker).to have_enqueued_sidekiq_job( "update_by_query", "source_record_id" => @purchase_2.id, "class_name" => "Purchase", "fields" => ["variant_ids_from_same_seller_purchased_by_purchaser"], "query" => PurchaseSearchService.new( seller: @purchase_2.seller, email: @purchase_2.email, exclude_purchase: @purchase_2.id ).body[:query] ) end it "updates related purchases documents", :sidekiq_inline, :elasticsearch_wait_for_refresh do purchase_1_doc = get_document_attributes(@purchase_1) expect(purchase_1_doc["variant_ids"]).to eq([@variant_1.id]) expect(purchase_1_doc["variant_ids_from_same_seller_purchased_by_purchaser"]).to eq([@variant_1.id, @variant_2.id]) purchase_2_doc = get_document_attributes(@purchase_2) expect(purchase_2_doc["variant_ids"]).to eq([@variant_2.id]) expect(purchase_2_doc["variant_ids_from_same_seller_purchased_by_purchaser"]).to eq([@variant_1.id, @variant_2.id]) end end end describe "AffiliateCredit Callbacks" do before do @purchase = create(:purchase) ElasticsearchIndexerWorker.jobs.clear end context "when affiliate_credit is created" do it "updates purchase document" do create(:affiliate_credit, purchase: @purchase, amount_cents: 123, fee_cents: 15) expect(ElasticsearchIndexerWorker.jobs.size).to eq(1) expect(ElasticsearchIndexerWorker).to \ have_enqueued_sidekiq_job("update", "record_id" => @purchase.id, "class_name" => "Purchase", "fields" => %w[ affiliate_credit_id affiliate_credit_amount_cents affiliate_credit_affiliate_user_id affiliate_credit_fee_cents ]) end end context "when affiliate_credit is updated" do before do @affiliate_credit = create(:affiliate_credit, purchase: @purchase, amount_cents: 123, fee_cents: 15) @balances = create_list(:balance, 3) ElasticsearchIndexerWorker.jobs.clear end it "updates purchase document" do @affiliate_credit.update!(amount_cents: 55, fee_cents: 10) expect(ElasticsearchIndexerWorker.jobs.size).to eq(1) expect(ElasticsearchIndexerWorker).to \ have_enqueued_sidekiq_job("update", "record_id" => @purchase.id, "class_name" => "Purchase", "fields" => %w[affiliate_credit_amount_cents affiliate_credit_fee_cents]) end end end describe "Product Callbacks" do it "enqueues update_by_query job when taxonomy is updated" do product = create(:product) purchase = create(:purchase, link: product) product.update!(taxonomy: create(:taxonomy)) expect(ElasticsearchIndexerWorker).to \ have_enqueued_sidekiq_job("update_by_query", "source_record_id" => purchase.id, "class_name" => "Purchase", "fields" => %w[taxonomy_id], "query" => PurchaseSearchService.new(product:).body[:query]) end it "does not enqueue update_by_query job when product has no sales" do product = create(:product) ElasticsearchIndexerWorker.jobs.clear product.update!(taxonomy: create(:taxonomy)) expect(ElasticsearchIndexerWorker.jobs.size).to eq(0) end it "updates the sales' Elasticsearch documents when the taxonomy is changed", :sidekiq_inline, :elasticsearch_wait_for_refresh do taxonomies = create_list(:taxonomy, 2) product = create(:product, taxonomy: taxonomies.first) purchases = create_list(:purchase, 2, link: product) expect(get_document_attributes(purchases.first)["taxonomy_id"]).to eq(taxonomies.first.id) expect(get_document_attributes(purchases.last)["taxonomy_id"]).to eq(taxonomies.first.id) product.update!(taxonomy: taxonomies.last) expect(get_document_attributes(purchases.first)["taxonomy_id"]).to eq(taxonomies.last.id) expect(get_document_attributes(purchases.last)["taxonomy_id"]).to eq(taxonomies.last.id) end end context "updating a purchase", :sidekiq_inline, :elasticsearch_wait_for_refresh do it "sets the subscription id" do subscription = create(:subscription) purchase = create(:purchase) subscription.purchases << purchase expect(get_document_attributes(purchase)["subscription_id"]).to eq(subscription.id) end end def get_document_attributes(record) EsClient.get(index: Purchase.index_name, id: record.id, ignore: 404)["_source"] end def update_related_purchases_job_params(purchase) [ "update_by_query", { "source_record_id" => purchase.id, "class_name" => "Purchase", "fields" => ["product_ids_from_same_seller_purchased_by_purchaser", "variant_ids_from_same_seller_purchased_by_purchaser"], "query" => PurchaseSearchService.new( seller: purchase.seller, email: purchase.email, exclude_purchase: purchase.id ).body[:query] } ] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/purchase/receipt_spec.rb
spec/models/concerns/purchase/receipt_spec.rb
# frozen_string_literal: true require "spec_helper" describe Purchase::Receipt do let(:purchase) { create(:purchase) } describe "#receipt_email_info" do let(:charge) { create(:charge, purchases: [purchase]) } let(:order) { charge.order } context "without email info records" do it "returns nil" do expect(purchase.receipt_email_info).to be_nil end end context "when the purchase does not use charge receipt" do let!(:email_info_from_purchase) do create( :customer_email_info, purchase_id: purchase.id, email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD, ) end it "returns email_info from purchase" do expect(purchase.receipt_email_info).to eq(email_info_from_purchase) end end context "when the purchase uses charge receipt" do let!(:email_info_from_charge) do create( :customer_email_info, purchase_id: nil, email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD, email_info_charge_attributes: { charge_id: charge.id } ) end it "returns the email info" do expect(purchase.receipt_email_info).to eq(email_info_from_charge) end end end describe "#has_invoice?" do it "returns true" do expect(purchase.has_invoice?).to be(true) end context "when is a free trial" do let(:purchase) { create(:free_trial_membership_purchase) } it "returns false" do expect(purchase.has_invoice?).to be(false) end end context "when is a free purchase" do let(:purchase) { create(:free_purchase) } it "returns false" do expect(purchase.has_invoice?).to be(false) end end end describe "#send_receipt" do it "enqueues the receipt job" do purchase.send_receipt expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(purchase.id).on("critical") end context "when the purchase uses a charge receipt" do before do allow_any_instance_of(Purchase).to receive(:uses_charge_receipt?).and_return(true) end it "doesn't enqueue the receipt job" do purchase.send_receipt expect(SendPurchaseReceiptJob).to_not have_enqueued_sidekiq_job(purchase.id) end end end describe "#resend_receipt" do let(:product) { create(:product_with_pdf_file) } let(:gift) { create(:gift, link: product) } let(:purchase) { create(:purchase, link: product, is_gift_sender_purchase: true, gift_given: gift) } let!(:url_redirect) { create(:url_redirect, purchase:, link: product) } let(:giftee_purchase) { create(:purchase, link: product, gift_received: gift) } let!(:giftee_url_redirect) { create(:url_redirect, purchase: giftee_purchase, link: product) } context "when product has no stampable files" do it "enqueues SendPurchaseReceiptJob using the critical queue" do purchase.resend_receipt expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(purchase.id).on("critical") expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(giftee_purchase.id).on("critical") end end context "when product has stampable files" do before do product.product_files.pdf.first.update!(pdf_stamp_enabled: true) end it "enqueues SendPurchaseReceiptJob using the default queue" do purchase.resend_receipt expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(purchase.id).on("default") expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(giftee_purchase.id).on("default") 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/concerns/purchase/paypal_spec.rb
spec/models/concerns/purchase/paypal_spec.rb
# frozen_string_literal: true require "spec_helper" describe Purchase::Paypal do let(:charge_processor_id) { nil } let(:card_visual) { "user@example.com" } let(:purchase) { build(:purchase, charge_processor_id:, card_visual:) } describe "#paypal_email" do context "when charge_processor_id is PayPal" do let(:charge_processor_id) { PaypalChargeProcessor.charge_processor_id } it "returns card_visual when purchase is PayPal" do expect(purchase.paypal_email).to eq(card_visual) end end context "when charge_processor_id is not PayPal" do let(:charge_processor_id) { StripeChargeProcessor.charge_processor_id } it "returns nil" do expect(purchase.paypal_email).to be_nil end end context "when card_visual is blank" do let(:charge_processor_id) { PaypalChargeProcessor.charge_processor_id } let(:card_visual) { nil } it "returns nil" do expect(purchase.paypal_email).to be_nil end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/purchase/creator_analytics_callbacks_spec.rb
spec/models/concerns/purchase/creator_analytics_callbacks_spec.rb
# frozen_string_literal: true require "spec_helper" describe Purchase::CreatorAnalyticsCallbacks do context "when the purchase happened today" do it "does not queue job after update" do purchase = create(:purchase_in_progress) purchase.mark_successful! expect(RegenerateCreatorAnalyticsCacheWorker.jobs.size).to eq(0) end it "does not queue job after refunding" do purchase = create(:purchase) purchase.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, purchase.total_transaction_cents), purchase.seller) expect(RegenerateCreatorAnalyticsCacheWorker.jobs.size).to eq(0) end end context "when the purchase happened before today" do before do travel_to(Time.utc(2020, 1, 10)) end it "queues job after update" do purchase = create(:purchase_in_progress, created_at: 2.days.ago) purchase.mark_successful! expect(RegenerateCreatorAnalyticsCacheWorker).to have_enqueued_sidekiq_job(purchase.seller_id, "2020-01-07") end it "queues the job after refunding" do purchase = create(:purchase, created_at: 2.days.ago) purchase.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, purchase.total_transaction_cents), purchase.seller) expect(RegenerateCreatorAnalyticsCacheWorker).to have_enqueued_sidekiq_job(purchase.seller_id, "2020-01-07") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/purchase/blockable_spec.rb
spec/models/concerns/purchase/blockable_spec.rb
# frozen_string_literal: true require "spec_helper" describe Purchase::Blockable do let(:product) { create(:product) } let(:buyer) { create(:user) } let(:purchase) { create(:purchase, link: product, email: "gumbot@gumroad.com", purchaser: buyer) } describe "#buyer_blocked?" do it "returns false when buyer is not blocked" do expect(purchase.buyer_blocked?).to eq(false) end context "when the purchase's browser is blocked" do before do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:browser_guid], purchase.browser_guid, nil) end it "returns true" do expect(purchase.buyer_blocked?).to eq(true) end end context "when the purchase's email is blocked" do before do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], purchase.email, nil) end it "returns true" do expect(purchase.buyer_blocked?).to eq(true) end end context "when the purchase's paypal email is blocked" do let(:purchase) { create(:purchase, link: product, email: "gumbot@gumroad.com", purchaser: buyer, charge_processor_id: PaypalChargeProcessor.charge_processor_id) } before do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], purchase.paypal_email, nil) end it "returns true" do expect(purchase.buyer_blocked?).to eq(true) end end context "when the buyer's email address is blocked" do before do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], buyer.email, nil) end it "returns true" do expect(purchase.buyer_blocked?).to eq(true) end end context "when the purchase's ip address is blocked" do before do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], purchase.ip_address, nil, expires_in: 1.hour) end it "returns true" do expect(purchase.buyer_blocked?).to eq(true) end end context "when the purchase's payment method is blocked" do before do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:charge_processor_fingerprint], purchase.stripe_fingerprint, nil) end it "returns true" do expect(purchase.buyer_blocked?).to eq(true) end end end describe "email blocking on fraud" do context "for a fraudulent transaction" do it "blocks the email" do purchase = build(:purchase_in_progress, email: "foo@example.com", error_code: PurchaseErrorCode::FRAUD_RELATED_ERROR_CODES.sample) purchase.mark_failed! expect(purchase.blocked_by_email?).to be true expect(purchase.blocked_by_email_object&.object_value).to eq("foo@example.com") end end context "for a non-fraudulent transaction" do it "does not block the email" do purchase = build(:purchase_in_progress, email: "foo@example.com", error_code: "non_fraud_code") purchase.mark_failed! expect(purchase.blocked_by_email?).to be false end end end describe "ip address blocking" do context "when purchase's ip address is not blocked" do it "returns false for blocked check" do expect(purchase.blocked_by_ip_address?).to be false end end context "when purchase's ip address is blocked" do before do BlockedObject.block!(BLOCKED_OBJECT_TYPES[:ip_address], purchase.ip_address, nil, expires_in: 1.hour) end it "returns true for blocked check" do expect(purchase.blocked_by_ip_address?).to be true expect(purchase.blocked_by_ip_address_object&.object_value).to eq(purchase.ip_address) end end end describe "#block_buyer!" do context "when the purchase is made through Stripe" do it "blocks buyer's email, browser_guid, ip_address and stripe_fingerprint" do purchase.block_buyer! [buyer.email, purchase.email, purchase.browser_guid, purchase.ip_address, purchase.stripe_fingerprint].each do |blocked_value| expect(BlockedObject.find_active_object(blocked_value).blocked?).to eq(true) end end end context "when the purchase is made through PayPal" do let(:paypal_chargeable) { build(:native_paypal_chargeable) } let(:purchase) { create(:purchase, card_visual: paypal_chargeable.visual, purchaser: buyer, chargeable: paypal_chargeable) } it "blocks buyer's email, browser_guid, ip_address and card_visual" do purchase.block_buyer! [buyer.email, purchase.email, purchase.browser_guid, purchase.ip_address, purchase.card_visual].each do |blocked_value| expect(BlockedObject.find_active_object(blocked_value).blocked?).to eq(true) end end end context "when blocking user is provided" do let(:admin_user) { create(:admin_user) } it "blocks buyer and references the blocker" do purchase.block_buyer!(blocking_user_id: admin_user.id) [buyer.email, purchase.email, purchase.browser_guid, purchase.ip_address, purchase.stripe_fingerprint].each do |blocked_value| BlockedObject.find_active_object(blocked_value).tap do |blocked_object| expect(blocked_object.blocked?).to eq(true) expect(blocked_object.blocked_by).to eq(admin_user.id) end end end it "sets `is_buyer_blocked_by_admin` to true" do expect(purchase.is_buyer_blocked_by_admin?).to eq(false) purchase.block_buyer!(blocking_user_id: admin_user.id) expect(purchase.is_buyer_blocked_by_admin?).to eq(true) end end describe "comments" do let(:admin_user) { create(:admin_user) } context "when comment content is provided" do it "adds buyer blocked comments with the provided content" do comment_content = "Blocked by Helper webhook" expect do purchase.block_buyer!(blocking_user_id: admin_user.id, comment_content:) end.to change { purchase.comments.where(content: comment_content, comment_type: "note", author_id: admin_user.id).count }.by(1) .and change { purchase.purchaser.comments.where(content: comment_content, comment_type: "note", author_id: admin_user.id, purchase:).count }.by(1) end end context "when comment content is not provided" do context "when the blocking user is an admin" do it "adds buyer blocked comments with the default content" do comment_content = "Buyer blocked by Admin (#{admin_user.email})" expect do purchase.block_buyer!(blocking_user_id: admin_user.id) end.to change { purchase.comments.where(content: comment_content, comment_type: "note", author_id: admin_user.id).count }.by(1) .and change { purchase.purchaser.comments.where(content: comment_content, comment_type: "note", author_id: admin_user.id, purchase:).count }.by(1) end end context "when the blocking user is not an admin" do it "adds buyer blocked comments with the default content" do user = create(:user) comment_content = "Buyer blocked by #{user.email}" expect do purchase.block_buyer!(blocking_user_id: user.id) end.to change { purchase.comments.where(content: comment_content, comment_type: "note", author_id: user.id).count }.by(1) .and change { purchase.purchaser.comments.where(content: comment_content, comment_type: "note", author_id: user.id, purchase:).count }.by(1) end end context "when the blocking user is not provided" do it "adds buyer blocked comments with the default content and GUMROAD_ADMIN as author" do comment_content = "Buyer blocked" expect do purchase.block_buyer! end.to change { purchase.comments.where(content: comment_content, comment_type: "note", author_id: GUMROAD_ADMIN_ID).count }.by(1) .and change { purchase.purchaser.comments.where(content: comment_content, comment_type: "note", author_id: GUMROAD_ADMIN_ID, purchase:).count }.by(1) end end end end end describe "#unblock_buyer!" do context "when buyer is not blocked" do it "does not call #unblock! on any blocked objects" do expect_any_instance_of(BlockedObject).to_not receive(:unblock!) purchase.unblock_buyer! end end context "when the purchase is made through Stripe" do it "unblocks the buyer's email, browser, IP address and stripe_fingerprint" do # Block purchase first to create the blocked objects purchase.block_buyer! purchase.unblock_buyer! [buyer.email, purchase.email, purchase.browser_guid, purchase.ip_address, purchase.stripe_fingerprint].each do |blocked_value| expect(BlockedObject.find_by(object_value: blocked_value).blocked?).to eq(false) end end end context "when the stripe_fingerprint is nil" do it "unblocks the buyer's stripe_fingerprint from a recent purchase" do purchase.block_buyer! purchase.update_attribute :stripe_fingerprint, nil recent_purchase = create(:purchase, purchaser: buyer, email: "gumbot@gumroad.com") expect do purchase.unblock_buyer! end.to change { BlockedObject.find_by(object_value: recent_purchase.stripe_fingerprint).blocked? }.from(true).to(false) end end context "when the purchase is made through PayPal" do let(:paypal_chargeable) { build(:native_paypal_chargeable) } let(:purchase) { create(:purchase, card_visual: paypal_chargeable.visual, purchaser: buyer, chargeable: paypal_chargeable) } it "unblocks the buyer's email, browser, IP address and card_visual" do # Block purchase first to create the blocked objects purchase.block_buyer! purchase.unblock_buyer! [buyer.email, purchase.email, purchase.browser_guid, purchase.ip_address, purchase.card_visual].each do |blocked_value| expect(BlockedObject.find_by(object_value: blocked_value).blocked?).to eq(false) end end end it "sets `is_buyer_blocked_by_admin` to false" do purchase.block_buyer! purchase.update!(is_buyer_blocked_by_admin: true) purchase.unblock_buyer! expect(purchase.is_buyer_blocked_by_admin).to eq(false) end end describe "#mark_failed" do context "when the purchase fails due to a fraud related reason" do let(:purchaser) { create(:user, email: "purchaser@example.com") } let(:purchase) { create(:purchase, purchaser:, email: "another-email@example.com", purchase_state: "in_progress", stripe_error_code: "card_declined_lost_card", charge_processor_id: StripeChargeProcessor.charge_processor_id) } let(:expected_blocked_objects) do [ ["email", "purchaser@example.com"], ["browser_guid", purchase.browser_guid], ["email", "another-email@example.com"], ["ip_address", purchase.ip_address], ["charge_processor_fingerprint", purchase.stripe_fingerprint] ] end it "blocks buyer's email, browser_guid, ip_address and stripe_fingerprint" do expect do purchase.mark_failed end.to change { BlockedObject.count }.from(0).to(5) expect(BlockedObject.pluck(:object_type, :object_value)).to match_array(expected_blocked_objects) end end context "when the purchase fails due to a non-fraud related reason" do let(:purchase) { create(:purchase, purchase_state: "in_progress", stripe_error_code: "card_declined_expired_card", charge_processor_id: StripeChargeProcessor.charge_processor_id) } it "doesn't block buyer" do expect do purchase.mark_failed end.to_not change { BlockedObject.count } end end describe "ban card testers" do before do @purchaser = create(:user, email: "purchaser@example.com") Feature.activate(:ban_card_testers) end context "when previous failed purchases exist with same email or browser_guid but with different cards" do context "when previous failed purchases were made within the week" do before do 3.times do |n| create(:failed_purchase, purchaser: @purchaser, email: @purchaser.email, stripe_fingerprint: SecureRandom.hex, created_at: n.days.ago) end @purchase = create(:purchase, purchaser: @purchaser, email: @purchaser.email, purchase_state: "in_progress", stripe_fingerprint: "hij", charge_processor_id: StripeChargeProcessor.charge_processor_id) @expected_blocked_objects = [ ["email", @purchaser.email], ["browser_guid", @purchase.browser_guid], ["ip_address", @purchase.ip_address], ["charge_processor_fingerprint", @purchase.stripe_fingerprint] ] end it "blocks the buyer" do expect do @purchase.mark_failed! end.to change { BlockedObject.count }.from(0).to(4) expect(BlockedObject.pluck(:object_type, :object_value)).to match_array(@expected_blocked_objects) end end context "when previous failed purchases weren't made within the week" do before do 3.times do |n| create(:failed_purchase, purchaser: @purchaser, email: @purchaser.email, stripe_fingerprint: SecureRandom.hex, created_at: (n + 7).days.ago) end @purchase = create(:purchase, purchaser: @purchaser, email: @purchaser.email, purchase_state: "in_progress", stripe_fingerprint: "hij", charge_processor_id: StripeChargeProcessor.charge_processor_id) end it "doesn't block buyer" do expect do @purchase.mark_failed! end.to_not change { BlockedObject.count } end end end context "when purchases with different cards fail from the same IP address" do context "when failures happen within a day" do before do 3.times do |n| create(:failed_purchase, purchaser: @purchaser, ip_address: "192.168.1.1", stripe_fingerprint: SecureRandom.hex, created_at: n.hours.ago) end @purchase = create(:purchase, purchaser: @purchaser, ip_address: "192.168.1.1", purchase_state: "in_progress", stripe_fingerprint: "hij", charge_processor_id: StripeChargeProcessor.charge_processor_id) end context "when the ip_address is not already blocked" do it "blocks the IP address" do travel_to(Time.current) do expect do @purchase.mark_failed! end.to change { BlockedObject.count }.from(0).to(1) expect(BlockedObject.pluck(:object_type, :object_value)).to eq [["ip_address", @purchase.ip_address]] expect(BlockedObject.ip_address.find_active_object(@purchase.ip_address).expires_at.to_i).to eq 7.days.from_now.to_i end end end context "when the ip_address is already blocked" do before do @expires_in = BlockedObject::IP_ADDRESS_BLOCKING_DURATION_IN_MONTHS.months BlockedObject.block!( BLOCKED_OBJECT_TYPES[:ip_address], @purchase.ip_address, nil, expires_in: @expires_in ) end it "doesn't overwrite the previous ip_address block" do travel_to(Time.current) do expect do @purchase.mark_failed! end.not_to change { BlockedObject.count } expect(BlockedObject.ip_address.find_active_object(@purchase.ip_address).expires_at.to_i).to eq @expires_in.from_now.to_i end end end end context "when failures doesn't happen in a day" do before do 3.times do |n| create(:failed_purchase, purchaser: @purchaser, ip_address: "192.168.1.1", stripe_fingerprint: SecureRandom.hex, created_at: n.days.ago) end @purchase = create(:purchase, purchaser: @purchaser, ip_address: "192.168.1.1", purchase_state: "in_progress", stripe_fingerprint: "hij", charge_processor_id: StripeChargeProcessor.charge_processor_id) end it "doesn't block buyer" do expect do @purchase.mark_failed! end.to_not change { BlockedObject.count } end end end end describe "block purchases on product" do before do Feature.activate(:block_purchases_on_product) $redis.set(RedisKey.card_testing_product_watch_minutes, 5) $redis.set(RedisKey.card_testing_product_max_failed_purchases_count, 10) $redis.set(RedisKey.card_testing_product_block_hours, 1) @product = create(:product) end context "when number of failed purchases exceeds the threshold" do before do 9.times do |n| create(:failed_purchase, link: @product) end @purchase = create(:purchase, link: @product, purchase_state: "in_progress") end context "when price is not zero" do it "blocks purchases on product" do travel_to(Time.current) do expect do @purchase.mark_failed! end.to change { BlockedObject.count }.from(0).to(1) expect(BlockedObject.pluck(:object_type, :object_value)).to eq [["product", @product.id.to_s]] expect(BlockedObject.product.find_active_object(@product.id).expires_at.to_i).to eq 1.hour.from_now.to_i end end end context "when price is zero" do before do @purchase = create(:purchase, price_cents: 0, link: @product, purchase_state: "in_progress") end it "doesn't block purchases on product" do travel_to(Time.current) do expect do @purchase.mark_failed! end.not_to change { BlockedObject.count } end end end context "when the error code belongs to IGNORED_ERROR_CODES list" do before do @purchase = create(:purchase, link: @product, purchase_state: "in_progress") end it "doesn't block purchases on product" do travel_to(Time.current) do expect do @purchase.error_code = PurchaseErrorCode::PERCEIVED_PRICE_CENTS_NOT_MATCHING @purchase.mark_failed! end.not_to change { BlockedObject.count } end end end end context "when number of failed purchases doesn't exceed the threshold" do before do create(:failed_purchase, link: @product) @purchase = create(:purchase, link: @product, purchase_state: "in_progress") end it "doesn't block purchases on product" do travel_to(Time.current) do expect do @purchase.mark_failed! end.not_to change { BlockedObject.count } end end end context "when multiple purchases fail in a row" do before do $redis.set(RedisKey.card_testing_max_number_of_failed_purchases_in_a_row, 3) end context "when all recent purchases were failed" do before do 2.times do |n| create(:purchase, link: @product, purchase_state: "in_progress").mark_failed! end @purchase = create(:purchase, link: @product, purchase_state: "in_progress") end it "blocks purchases on product" do travel_to(Time.current) do expect do @purchase.mark_failed! end.to change { BlockedObject.count }.from(0).to(1) expect(BlockedObject.pluck(:object_type, :object_value)).to eq [["product", @product.id.to_s]] expect(BlockedObject.product.find_active_object(@product.id).expires_at.to_i).to eq 1.hour.from_now.to_i end end end context "when recent purchases fail with an error code from IGNORED_ERROR_CODES list" do before do 2.times do |n| create(:purchase, link: @product, purchase_state: "in_progress", error_code: PurchaseErrorCode::PERCEIVED_PRICE_CENTS_NOT_MATCHING).mark_failed! end @purchase = create(:purchase, link: @product, purchase_state: "in_progress") end it "doesn't block purchases on product" do travel_to(Time.current) do expect do @purchase.mark_failed! end.not_to change { BlockedObject.count } end end end context "when a successful purchase exists in the recent purchases" do before do create(:purchase, link: @product, purchase_state: "in_progress").mark_failed! create(:purchase, link: @product, purchase_state: "in_progress").mark_failed! create(:purchase, link: @product, purchase_state: "in_progress").mark_successful! @purchase = create(:purchase, link: @product, purchase_state: "in_progress") end it "doesn't block purchases on product" do travel_to(Time.current) do expect do @purchase.mark_failed! end.not_to change { BlockedObject.count } end end end context "when a not_charged purchase exists in the recent purchases" do before do create(:purchase, link: @product, purchase_state: "in_progress").mark_failed! create(:purchase, link: @product, purchase_state: "in_progress").mark_failed! create(:purchase, link: @product, purchase_state: "in_progress").mark_not_charged! @purchase = create(:purchase, link: @product, purchase_state: "in_progress") end it "doesn't block purchases on product" do freeze_time do expect do @purchase.mark_failed! end.not_to change { BlockedObject.count } end end end end end describe "pause payouts for seller internally based on recent failures" do let(:seller) { create(:user) } let(:product) { create(:product, user: seller) } let!(:purchase) { create(:purchase, link: product, purchase_state: "in_progress") } before do Feature.activate(:block_seller_based_on_recent_failures) $redis.set(RedisKey.failed_seller_purchases_watch_minutes, 60) $redis.set(RedisKey.max_seller_failed_purchases_price_cents, 1000) # $10 end context "when feature is inactive" do before { Feature.deactivate(:block_seller_based_on_recent_failures) } it "does not pause payouts for the seller" do create_list(:failed_purchase, 5, link: product, price_cents: 250) purchase.mark_failed! expect(seller.reload.payouts_paused_internally).to be(false) expect(seller.payouts_paused_by_source).to be nil end end context "when error code is ignored" do it "does not pause payouts for the seller" do create_list(:failed_purchase, 5, link: product, price_cents: 250) purchase.update!(error_code: PurchaseErrorCode::PERCEIVED_PRICE_CENTS_NOT_MATCHING) purchase.mark_failed! expect(seller.reload.payouts_paused_internally).to be(false) expect(seller.payouts_paused_by_source).to be nil end end context "when seller account is older than 2 years" do let(:old_seller) { create(:user, created_at: 3.years.ago) } let(:old_product) { create(:product, user: old_seller) } let!(:old_purchase) { create(:purchase, link: old_product, purchase_state: "in_progress") } it "does not pause payouts for the seller even with high failed amounts" do create_list(:failed_purchase, 10, link: old_product, price_cents: 500) old_purchase.mark_failed! expect(old_seller.reload.payouts_paused_internally).to be(false) expect(old_seller.payouts_paused_by_source).to be nil end it "does not create a comment" do create_list(:failed_purchase, 10, link: old_product, price_cents: 500) old_purchase.mark_failed! expect(old_seller.comments.count).to eq(0) end end context "when seller account is slightly newer than 2 years" do let(:newer_seller) { create(:user, created_at: 23.months.ago) } let(:newer_product) { create(:product, user: newer_seller) } let!(:newer_purchase) { create(:purchase, link: newer_product, purchase_state: "in_progress") } it "pauses payouts for the seller when threshold is exceeded" do create_list(:failed_purchase, 5, link: newer_product, price_cents: 250) newer_purchase.mark_failed! expect(newer_seller.reload.payouts_paused_internally).to be(true) expect(newer_seller.payouts_paused_by_source).to eq(User::PAYOUT_PAUSE_SOURCE_SYSTEM) end end context "when total failed amount is below threshold" do it "does not pause payouts for the seller" do create_list(:failed_purchase, 3, link: product, price_cents: 250) purchase.mark_failed! expect(seller.reload.payouts_paused_internally).to be(false) expect(seller.payouts_paused_by_source).to be nil end end context "when total failed amount is above threshold" do it "pauses payouts internally" do create_list(:failed_purchase, 5, link: product, price_cents: 250) purchase.mark_failed! expect(seller.reload.payouts_paused_internally).to be(true) expect(seller.payouts_paused_by_source).to eq(User::PAYOUT_PAUSE_SOURCE_SYSTEM) end it "creates a comment with the failed amount" do create_list(:failed_purchase, 5, link: product, price_cents: 250) purchase.mark_failed! comment = seller.comments.last expect(comment.content).to eq("Payouts paused due to high volume of failed purchases ($13.50 USD in 60 minutes).") expect(comment.comment_type).to eq(Comment::COMMENT_TYPE_ON_PROBATION) expect(comment.author_name).to eq("pause_payouts_for_seller_based_on_recent_failures") end context "when some purchases are outside the watch window" do it "does not pause payouts internally" do travel_to Time.current do create_list(:failed_purchase, 2, link: product, price_cents: 250) create_list(:failed_purchase, 3, link: product, price_cents: 250, created_at: 61.minutes.ago) purchase.mark_failed! expect(seller.reload.payouts_paused_internally).to be(false) expect(seller.payouts_paused_by_source).to be nil end end end end context "when redis keys are not set" do before do $redis.del(RedisKey.failed_seller_purchases_watch_minutes) $redis.del(RedisKey.max_seller_failed_purchases_price_cents) end context "when total failed amount is below default threshold" do it "does not pause payouts internally" do # default max amount is $2000 create_list(:failed_purchase, 5, link: product, price_cents: 200_00) purchase.mark_failed! expect(seller.reload.payouts_paused_internally).to be(false) expect(seller.payouts_paused_by_source).to be nil end end context "when total failed amount is above default threshold" do it "pauses payouts internally" do # default max amount is $2000 create_list(:failed_purchase, 11, link: product, price_cents: 200_00) purchase.mark_failed! expect(seller.reload.payouts_paused_internally).to be(true) expect(seller.payouts_paused_by_source).to eq(User::PAYOUT_PAUSE_SOURCE_SYSTEM) end end end end end describe "#charge_processor_fingerprint" do context "when charge_processor_id is 'stripe'" do let(:purchase) { build(:purchase) } it "returns stripe fingerprint" do expect(purchase.charge_processor_fingerprint).to eq(purchase.stripe_fingerprint) end end context "when charge_processor_id is not 'stripe'" do let(:purchase) { build(:purchase, charge_processor_id: PaypalChargeProcessor.charge_processor_id, card_visual: "paypal-email@example.com") } it "returns card visual" do expect(purchase.charge_processor_fingerprint).to eq("paypal-email@example.com") end end end describe "#block_fraudulent_free_purchases!" do before do @product = create(:product, price_cents: 0) create_list(:purchase, 2, link: @product, ip_address: "127.0.0.1") end context "when number of free purchases of the same product from same IP address exceeds the threshold" do context "when the purchase happens within the configured time limit" do it "blocks the ip_address" do freeze_time do expect do purchase = create(:purchase, link: @product, ip_address: "127.0.0.1", purchase_state: "in_progress") purchase.mark_successful! end.to change { BlockedObject.count }.from(0).to(1) expect(BlockedObject.pluck(:object_type, :object_value)).to eq [["ip_address", "127.0.0.1"]] expect(BlockedObject.ip_address.find_active_object("127.0.0.1").expires_at.to_i).to eq 24.hours.from_now.to_i end end end context "when the purchase happens outside the configured time limit" do it "doesn't block the ip_address" do travel_to(5.hours.from_now) do expect do purchase = create(:purchase, link: @product, ip_address: "127.0.0.1", purchase_state: "in_progress") purchase.mark_successful! end.not_to change { BlockedObject.count } end end end end context "when the purchase is created for another product" do it "doesn't block the ip_address" do expect do purchase = create(:purchase, ip_address: "127.0.0.1", purchase_state: "in_progress") purchase.mark_successful! end.not_to change { BlockedObject.count } end end context "when the purchase is created from another ip_address" do it "doesn't block the ip_address" do expect do purchase = create(:purchase, link: @product, ip_address: "127.0.0.2", purchase_state: "in_progress") purchase.mark_successful! end.not_to change { BlockedObject.count } end end context "when purchase is not free" do it "doesn't block the ip_address" do expect do purchase = create(:purchase, price_cents: 100, link: @product, ip_address: "127.0.0.1", purchase_state: "in_progress") purchase.mark_successful! end.not_to change { BlockedObject.count } end end end describe "#suspend_buyer_on_fraudulent_card_decline!" do before do Feature.activate(:suspend_fraudulent_buyers) @buyer = create(:user) @purchase = build(:purchase_in_progress, email: "sam@example.com", error_code: PurchaseErrorCode::CARD_DECLINED_FRAUDULENT, purchaser: @buyer) end context "when the error code is not CARD_DECLINED_FRAUDULENT" do it "doesn't suspend the buyer" do @purchase.error_code = PurchaseErrorCode::STRIPE_INSUFFICIENT_FUNDS expect { @purchase.mark_failed! }.not_to change { @buyer.reload.suspended? } end end context "when the buyer account was created more than 6 hours ago" do it "doesn't suspend the buyer" do @buyer.update!(created_at: 7.hours.ago) expect { @purchase.mark_failed! }.not_to change { @buyer.reload.suspended? } end end context "when the error code is CARD_DECLINED_FRAUDULENT" do context "when buyer account was created less than 6 hours ago" do it "suspends the buyer" do expect do
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/concerns/workflow/abandoned_cart_products_spec.rb
spec/models/concerns/workflow/abandoned_cart_products_spec.rb
# frozen_string_literal: true require "spec_helper" describe Workflow::AbandonedCartProducts do include Rails.application.routes.url_helpers describe "#abandoned_cart_products" do let(:seller) { create(:user) } let!(:product1) { create(:product, user: seller, name: "Product 1") } let!(:product2) { create(:product, user: seller, name: "Product 2") } let(:variant_category) { create(:variant_category, link: product2) } let!(:variant1) { create(:variant, variant_category:, name: "Product 2 - Version 1") } let!(:variant2) { create(:variant, variant_category:, name: "Product 2- Version 2") } let!(:archived_product) { create(:product, user: seller, archived: true, name: "Archived product") } context "when it is not an abandoned cart workflow" do it "returns an empty array" do workflow = create(:seller_workflow, seller:) expect(workflow.abandoned_cart_products).to be_empty expect(workflow.abandoned_cart_products(only_product_and_variant_ids: true)).to be_empty end end context "when it is an abandoned cart workflow" do context "when 'bought_products', 'bought_variants', 'not_bought_products', and 'not_bought_variants' are not provided" do it "returns all products and variants that are not archived" do workflow = create(:abandoned_cart_workflow, seller:) expect(workflow.abandoned_cart_products).to match_array([{ unique_permalink: product1.unique_permalink, external_id: product1.external_id, name: product1.name, thumbnail_url: product1.for_email_thumbnail_url, url: product1.long_url, variants: [], seller: { name: seller.display_name, avatar_url: seller.avatar_url, profile_url: seller.profile_url, } }, { unique_permalink: product2.unique_permalink, external_id: product2.external_id, name: product2.name, thumbnail_url: product2.for_email_thumbnail_url, url: product2.long_url, variants: [ { external_id: variant1.external_id, name: variant1.name }, { external_id: variant2.external_id, name: variant2.name } ], seller: { name: seller.display_name, avatar_url: seller.avatar_url, profile_url: seller.profile_url, } }]) expect(workflow.abandoned_cart_products(only_product_and_variant_ids: true)).to match_array([[product1.id, []], [product2.id, [variant1.id, variant2.id]]]) end it "includes the product if at least one of its variant is selected" do workflow = create(:abandoned_cart_workflow, seller:, bought_variants: [variant1.external_id]) expect(workflow.abandoned_cart_products).to match_array([{ unique_permalink: product2.unique_permalink, external_id: product2.external_id, name: product2.name, thumbnail_url: product2.for_email_thumbnail_url, url: product2.long_url, variants: [{ external_id: variant1.external_id, name: variant1.name }], seller: { name: seller.display_name, avatar_url: seller.avatar_url, profile_url: seller.profile_url, } }]) expect(workflow.abandoned_cart_products(only_product_and_variant_ids: true)).to match_array([[product2.id, [variant1.id]]]) end it "includes the product along with all its variants if it is selected and one of its variant is selected" do workflow = create(:abandoned_cart_workflow, seller:, bought_products: [product2.unique_permalink], bought_variants: [variant2.external_id]) expect(workflow.abandoned_cart_products).to match_array([{ unique_permalink: product2.unique_permalink, external_id: product2.external_id, name: product2.name, thumbnail_url: product2.for_email_thumbnail_url, url: product2.long_url, variants: [ { external_id: variant1.external_id, name: variant1.name }, { external_id: variant2.external_id, name: variant2.name } ], seller: { name: seller.display_name, avatar_url: seller.avatar_url, profile_url: seller.profile_url, } }]) expect(workflow.abandoned_cart_products(only_product_and_variant_ids: true)).to match_array([[product2.id, [variant1.id, variant2.id]]]) end it "does not include the product if 'not_bought_products' filter includes it even though one of its variants is selected" do workflow = create(:abandoned_cart_workflow, seller:, not_bought_products: [product2.unique_permalink], bought_variants: [variant1.external_id]) expect(workflow.abandoned_cart_products).to be_empty expect(workflow.abandoned_cart_products(only_product_and_variant_ids: true)).to be_empty end it "does not include a product's variant if 'not_bought_variants' filter includes it" do workflow = create(:abandoned_cart_workflow, seller:, bought_products: [product2.unique_permalink], not_bought_variants: [variant2.external_id]) expect(workflow.abandoned_cart_products).to match_array([{ unique_permalink: product2.unique_permalink, external_id: product2.external_id, name: product2.name, thumbnail_url: product2.for_email_thumbnail_url, url: product2.long_url, variants: [{ external_id: variant1.external_id, name: variant1.name }], seller: { name: seller.display_name, avatar_url: seller.avatar_url, profile_url: seller.profile_url, } }]) expect(workflow.abandoned_cart_products(only_product_and_variant_ids: true)).to match_array([[product2.id, [variant1.id]]]) end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/models/installment/installment_json_spec.rb
spec/models/installment/installment_json_spec.rb
# frozen_string_literal: true require "spec_helper" describe "InstallmentJson" do before do @creator = create(:named_user, :with_avatar) @installment = create(:installment, call_to_action_text: "CTA", call_to_action_url: "https://www.example.com", seller: @creator) end describe "#installment_mobile_json_data" do before do @product_file_1 = create(:product_file, installment: @installment, link: @installment.link) @product_file_2 = create(:product_file, installment: @installment, link: @installment.link, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4") @installment.update!(published_at: 1.week.ago) end context "for a digital product purchase" do before do @purchase = create(:purchase, link: @installment.link) @url_redirect = @installment.generate_url_redirect_for_purchase(@purchase) @files_data = [@product_file_1, @product_file_2].map do |product_file| @url_redirect.mobile_product_file_json_data(product_file) end end it "returns the correct json data" do expected_installment_json_data = { files_data: @files_data, message: @installment.message, name: @installment.name, call_to_action_text: @installment.call_to_action_text, call_to_action_url: @installment.call_to_action_url, installment_type: @installment.installment_type, published_at: @installment.published_at, external_id: @installment.external_id, url_redirect_external_id: @url_redirect.external_id, creator_name: @creator.name_or_username, creator_profile_picture_url: @creator.avatar_url, creator_profile_url: @creator.profile_url } expect(@installment.installment_mobile_json_data(purchase: @purchase).to_json).to eq expected_installment_json_data.to_json end context "when the installment has been sent to the user" do it "returns the time sent as the published_at time" do sent_at = 1.day.ago create(:creator_contacting_customers_email_info, installment: @installment, purchase: @purchase, sent_at:) expect(@installment.installment_mobile_json_data(purchase: @purchase)[:published_at].to_json).to eq sent_at.to_json end end context "for an installment without files" do it "returns no files" do installment = create(:installment, link: @installment.link, call_to_action_text: "CTA", call_to_action_url: "https://www.example.com", seller: @creator) installment.update!(published_at: 1.week.ago) url_redirect = installment.generate_url_redirect_for_purchase(@purchase) expected_installment_json_data = { files_data: [], message: installment.message, name: installment.name, call_to_action_text: installment.call_to_action_text, call_to_action_url: installment.call_to_action_url, installment_type: installment.installment_type, published_at: installment.published_at, external_id: installment.external_id, url_redirect_external_id: url_redirect.external_id, creator_name: @creator.name_or_username, creator_profile_picture_url: @creator.avatar_url, creator_profile_url: @creator.profile_url } expect(installment.installment_mobile_json_data(purchase: @purchase).to_json).to eq expected_installment_json_data.to_json end end end context "for a subscription purchase" do before do @installment.link.update!(is_recurring_billing: true) @purchase = create(:membership_purchase, link: @installment.link) @subscription = @purchase.subscription @url_redirect = @installment.generate_url_redirect_for_subscription(@subscription) @files_data = [@product_file_1, @product_file_2].map do |product_file| @url_redirect.mobile_product_file_json_data(product_file) end end it "returns the correct json data" do expected_installment_json_data = { files_data: @files_data, message: @installment.message, name: @installment.name, call_to_action_text: @installment.call_to_action_text, call_to_action_url: @installment.call_to_action_url, installment_type: @installment.installment_type, published_at: @installment.published_at, external_id: @installment.external_id, url_redirect_external_id: @url_redirect.external_id, creator_name: @creator.name_or_username, creator_profile_picture_url: @creator.avatar_url, creator_profile_url: @creator.profile_url } expect(@installment.installment_mobile_json_data(purchase: @purchase, subscription: @subscription).to_json).to eq expected_installment_json_data.to_json end context "when the installment has been sent to the user" do it "returns the time sent as the published_at time" do sent_at = 1.day.ago create(:creator_contacting_customers_email_info, installment: @installment, purchase: @purchase, sent_at:) expect(@installment.installment_mobile_json_data(purchase: @purchase)[:published_at].to_json).to eq sent_at.to_json 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/installment/installment_class_methods_spec.rb
spec/models/installment/installment_class_methods_spec.rb
# frozen_string_literal: true require "spec_helper" describe "InstallmentClassMethods" do before do @creator = create(:named_user, :with_avatar) @installment = create(:installment, call_to_action_text: "CTA", call_to_action_url: "https://www.example.com", seller: @creator) end describe ".product_or_variant_with_sent_emails_for_purchases" do it "returns live product or variant installments that have been emailed to those purchasers" do product = create(:product) variant = create(:variant, variant_category: create(:variant_category, link: product)) product_post = create(:installment, link: product, published_at: 1.day.ago) variant_post = create(:variant_installment, link: product, base_variant: variant, published_at: 1.day.ago) create(:seller_installment, seller: product.user) create(:installment, link: product, published_at: 1.day.ago, deleted_at: 1.day.ago) create(:variant_installment, link: product, base_variant: variant, published_at: nil) purchase = create(:purchase, link: product, variant_attributes: [variant]) expect(Installment.product_or_variant_with_sent_emails_for_purchases([purchase.id])).to be_empty create(:creator_contacting_customers_email_info, installment: product_post, purchase:) expect(Installment.product_or_variant_with_sent_emails_for_purchases([purchase.id])).to match_array [product_post] create(:creator_contacting_customers_email_info, installment: variant_post, purchase:) expect(Installment.product_or_variant_with_sent_emails_for_purchases([purchase.id])).to match_array [product_post, variant_post] expect(Installment.product_or_variant_with_sent_emails_for_purchases([create(:purchase).id])).to be_empty end end describe ".seller_with_sent_emails_for_purchases" do it "returns live seller installments that have been emailed to those purchasers" do product = create(:product) purchase = create(:purchase, link: product) seller_post = create(:seller_installment, seller: product.user, published_at: 1.day.ago) create(:seller_installment, seller: product.user, published_at: 1.day.ago, deleted_at: 1.day.ago) create(:seller_installment, seller: product.user, published_at: nil) create(:installment, link: product, published_at: 1.day.ago) expect(Installment.seller_with_sent_emails_for_purchases([purchase.id])).to be_empty create(:creator_contacting_customers_email_info, installment: seller_post, purchase:) expect(Installment.seller_with_sent_emails_for_purchases([purchase.id])).to match_array [seller_post] end end describe ".profile_only_for_products" do it "returns live profile-only product posts for the given product IDs" do product1 = create(:product) product2 = create(:product) product1_post = create(:installment, link: product1, published_at: 1.day.ago, send_emails: false, shown_on_profile: true) product2_post = create(:installment, link: product2, published_at: 1.day.ago, send_emails: false, shown_on_profile: true) create(:installment, link: product1, send_emails: false, shown_on_profile: true) create(:installment, link: product2, published_at: nil, send_emails: false, shown_on_profile: true) create(:installment, link: product2, published_at: 1.day.ago, deleted_at: 1.day.ago, send_emails: false, shown_on_profile: true) create(:installment, link: product1, published_at: 1.day.ago, shown_on_profile: true) create(:installment, link: product2, published_at: 1.day.ago) create(:installment, published_at: 1.day.ago, send_emails: false, shown_on_profile: true) expect(Installment.profile_only_for_products([product1.id, product2.id])).to match_array [product1_post, product2_post] end end describe ".profile_only_for_variant_ids" do it "returns live profile-only variant posts for the given variant IDs" do product = create(:product) variant1 = create(:variant, variant_category: create(:variant_category, link: product)) variant2 = create(:variant, variant_category: create(:variant_category, link: product)) variant1_post = create(:variant_installment, link: product, base_variant: variant1, published_at: 1.day.ago, send_emails: false, shown_on_profile: true) variant2_post = create(:variant_installment, link: product, base_variant: variant2, published_at: 1.day.ago, send_emails: false, shown_on_profile: true) create(:variant_installment, link: product, base_variant: variant1, published_at: nil, send_emails: false, shown_on_profile: true) create(:variant_installment, link: product, base_variant: variant1, published_at: 1.day.ago, deleted_at: 1.day.ago, send_emails: false, shown_on_profile: true) create(:variant_installment, link: product, base_variant: variant2, published_at: 1.day.ago, shown_on_profile: true) create(:variant_installment, link: product, base_variant: variant2, published_at: 1.day.ago) create(:installment, link: product, published_at: 1.day.ago, send_emails: false, shown_on_profile: true) expect(Installment.profile_only_for_variants([variant1.id, variant2.id])).to match_array [variant1_post, variant2_post] end end describe ".profile_only_for_sellers" do it "returns live profile-only seller posts for the given seller IDs" do seller1 = create(:user) seller2 = create(:user) seller1_post = create(:seller_installment, seller: seller1, published_at: 1.day.ago, send_emails: false, shown_on_profile: true) seller2_post = create(:seller_installment, seller: seller2, published_at: 1.day.ago, send_emails: false, shown_on_profile: true) create(:seller_installment, seller: seller1, published_at: nil, send_emails: false, shown_on_profile: true) create(:seller_installment, seller: seller2, published_at: 1.day.ago, deleted_at: 1.day.ago, send_emails: false, shown_on_profile: true) create(:seller_installment, seller: seller1, published_at: 1.day.ago, shown_on_profile: true) create(:seller_installment, seller: seller2, published_at: 1.day.ago) create(:seller_installment, published_at: 1.day.ago, send_emails: false, shown_on_profile: true) create(:installment, seller: seller1, published_at: 1.day.ago) expect(Installment.profile_only_for_sellers([seller1.id, seller2.id])).to match_array [seller1_post, seller2_post] end end describe ".for_products" do it "returns live, non-workflow product-posts for the given products" do product1 = create(:product) product2 = create(:product) product_ids = [product1.id, product2.id] posts = [ create(:product_installment, :published, link: product1), create(:product_installment, :published, link: product2), ] create(:product_installment, link: product1) create(:product_installment, :published, link: product2, deleted_at: 1.day.ago) create(:product_installment, :published) create(:seller_installment, :published, seller: product1.user) create(:workflow_installment, :published, link: product1) expect(Installment.for_products(product_ids:)).to match_array posts end end describe ".for_variants" do it "returns live, non-workflow variant-posts for the given variants" do variant1 = create(:variant) variant2 = create(:variant) variant_ids = [variant1.id, variant2.id] posts = [ create(:variant_installment, :published, base_variant: variant1), create(:variant_installment, :published, base_variant: variant2), ] create(:variant_installment, base_variant: variant1) create(:variant_installment, :published, base_variant: variant2, deleted_at: 1.day.ago) create(:variant_installment, :published) create(:seller_installment, :published, seller: variant1.user) create(:workflow_installment, :published, base_variant: variant1) expect(Installment.for_variants(variant_ids:)).to match_array posts end end describe ".for_sellers" do it "returns live, non-workflow seller-posts for the given sellers" do seller1 = create(:user) seller2 = create(:user) seller_ids = [seller1.id, seller2.id] posts = [ create(:seller_installment, :published, seller: seller1), create(:seller_installment, :published, seller: seller2), ] create(:seller_installment, seller: seller1) create(:seller_installment, :published, seller: seller2, deleted_at: 1.day.ago) create(:seller_installment, :published) create(:product_installment, :published, seller: seller1) create(:variant_installment, :published, seller: seller1) create(:workflow_installment, :published, seller: seller1) expect(Installment.for_sellers(seller_ids:)).to match_array posts end end describe ".past_posts_to_show_for_products" do before do @enabled_product = create(:product, should_show_all_posts: true) @disabled_product = create(:product, should_show_all_posts: false) @enabled_product_post1 = create(:installment, link: @enabled_product, published_at: 1.day.ago) @enabled_product_post2 = create(:installment, link: @enabled_product, published_at: 1.day.ago) create(:installment, link: @enabled_product, published_at: nil) create(:installment, link: @disabled_product, published_at: 1.day.ago) workflow = create(:workflow, link: @enabled_product, workflow_type: Workflow::PRODUCT_TYPE) create(:installment, workflow:, link: @enabled_product, published_at: 1.day.ago) end it "returns live product posts for products with should_show_all_posts enabled" do expect(Installment.past_posts_to_show_for_products(product_ids: [@enabled_product.id, @disabled_product.id])).to match_array [@enabled_product_post1, @enabled_product_post2] end it "excludes certain post IDs, if provided" do expect(Installment.past_posts_to_show_for_products(product_ids: [@enabled_product.id, @disabled_product.id], excluded_post_ids: [@enabled_product_post1.id])).to match_array [@enabled_product_post2] end end describe ".past_posts_to_show_for_variants" do before do enabled_product = create(:product, should_show_all_posts: true) @enabled_variant = create(:variant, variant_category: create(:variant_category, link: enabled_product)) @disabled_variant = create(:variant) @enabled_variant_post1 = create(:variant_installment, link: enabled_product, base_variant: @enabled_variant, published_at: 1.day.ago) @enabled_variant_post2 = create(:variant_installment, link: enabled_product, base_variant: @enabled_variant, published_at: 1.day.ago) create(:variant_installment, link: enabled_product, base_variant: @enabled_variant, published_at: nil) create(:variant_installment, link: @disabled_variant.link, base_variant: @disabled_variant, published_at: 1.day.ago) end it "returns live variant posts for variants whose products have should_show_all_posts enabled" do expect(Installment.past_posts_to_show_for_variants(variant_ids: [@enabled_variant.id, @disabled_variant.id])).to match_array [@enabled_variant_post1, @enabled_variant_post2] end it "excludes certain post IDs, if provided" do expect(Installment.past_posts_to_show_for_variants(variant_ids: [@enabled_variant.id, @disabled_variant.id], excluded_post_ids: [@enabled_variant_post1.id])).to match_array [@enabled_variant_post2] end end describe ".seller_posts_for_sellers" do before do @seller = create(:user) @seller_post1 = create(:seller_installment, seller: @seller, published_at: 1.day.ago) @seller_post2 = create(:seller_installment, seller: @seller, published_at: 1.day.ago) create(:seller_installment, seller: @seller, published_at: nil) create(:seller_installment, published_at: 1.day.ago) end it "returns live seller posts for the given seller IDs" do expect(Installment.seller_posts_for_sellers(seller_ids: [@seller.id])).to match_array [@seller_post1, @seller_post2] end it "excludes certain post IDs, if provided" do expect(Installment.seller_posts_for_sellers(seller_ids: [@seller.id], excluded_post_ids: [@seller_post1.id])).to match_array [@seller_post2] end end describe ".emailable_posts_for_purchase" do it "returns the product-, variant-, and seller-type posts for the purchase where send_emails is true" do product = create(:product) variant = create(:variant, variant_category: create(:variant_category, link: product)) purchase = create(:purchase, link: product, variant_attributes: [variant]) posts = [ create(:product_installment, :published, link: product), create(:product_installment, :published, link: product), create(:variant_installment, :published, base_variant: variant), create(:seller_installment, :published, seller: product.user), ] create(:product_installment, :published, link: product, send_emails: false, shown_on_profile: true) create(:product_installment, link: product) create(:variant_installment, :published, base_variant: variant, deleted_at: 1.day.ago) create(:workflow_installment, link: product, seller: product.user) expect(Installment.emailable_posts_for_purchase(purchase:)).to match_array posts end end describe ".filter_by_product_id_if_present" do before do @creator = create(:named_user) @product = create(:product, name: "product name", user: @creator) @product_post = create(:installment, link: @product, name: "product update", message: "content for update post 1", published_at: Time.current, shown_on_profile: true, seller: @creator) @audience_post = create(:audience_installment, name: "audience update", message: "content for update post 1", seller: @creator, published_at: Time.current, shown_on_profile: true) another_product = create(:product, name: "product name", user: @creator) @another_product_post = create(:installment, link: another_product, name: "product update", message: "content for update post 1", published_at: Time.current, shown_on_profile: true, seller: @creator) end it "returns the proper product updates if filtered by product ID" do product_filtered_posts = Installment.filter_by_product_id_if_present(@product.id) expect(product_filtered_posts.length).to eq 1 expect(product_filtered_posts).to include(@product_post) expect(product_filtered_posts).to_not include(@audience_post) expect(product_filtered_posts).to_not include(@another_product_post) end it "does not apply any scope if no product_id present" do product_filtered_posts = Installment.filter_by_product_id_if_present(nil) expect(product_filtered_posts.length).to eq 4 end end describe ".missed_for_purchase" do before do @creator = create(:user) @product = create(:product, user: @creator) @purchase = create(:purchase, link: @product) end it "returns only the posts sent by seller in case there are posts belonging to other user" do sent_installment = create(:installment, link: @product, seller: @creator, published_at: Time.current) create(:creator_contacting_customers_email_info, installment: sent_installment, purchase: @purchase) sellers_post = create(:installment, link: @product, published_at: Time.current) create(:installment, link: @product, seller: create(:user), published_at: Time.current) product_filtered_posts = Installment.missed_for_purchase(@purchase) expect(product_filtered_posts).to eq [sellers_post] end it "includes posts sent to customers of multiple products if it includes the bought product" do post_to_multiple_products = create(:seller_installment, seller: @creator, bought_products: [@product.unique_permalink, create(:product, user: @creator).unique_permalink], published_at: 2.days.ago) already_received_post = create(:seller_installment, seller: @creator, bought_products: [@product.unique_permalink, create(:product, user: @creator).unique_permalink], published_at: 1.day.ago) create(:creator_contacting_customers_email_info, installment: already_received_post, purchase: @purchase) missed_posts = Installment.missed_for_purchase(@purchase) expect(missed_posts).to eq [post_to_multiple_products] end it "includes posts sent to all customers" do seller_post = create(:seller_installment, seller: @creator, published_at: 2.days.ago) missed_posts = Installment.missed_for_purchase(@purchase) expect(missed_posts).to eq [seller_post] end it "includes posts sent to audience" do seller_post = create(:audience_installment, seller: @creator, published_at: 2.days.ago) missed_posts = Installment.missed_for_purchase(@purchase) expect(missed_posts).to eq [seller_post] end it "does not include post sent to customers of multiple products if it is already sent to the purchase email" do product_1 = create(:product, user: @creator) product_2 = create(:product, user: @creator) purchase_1 = create(:purchase, link: product_1, email: "bot@gum.co") purchase_2 = create(:purchase, link: product_2, email: "bot@gum.co") post = create(:seller_installment, seller: @creator, published_at: 2.days.ago, bought_products: [product_1.unique_permalink, product_2.unique_permalink]) create(:creator_contacting_customers_email_info, installment: post, purchase: purchase_1) missed_posts = Installment.missed_for_purchase(purchase_2) expect(missed_posts).to eq [] end it "does not include profile-only posts" do product_post = create(:installment, link: @product, seller: @creator, published_at: 3.days.ago) product_post.send_emails = false product_post.shown_on_profile = true product_post.save! seller_post = create(:seller_installment, seller: @creator, bought_products: [@product.unique_permalink, create(:product, user: @creator).unique_permalink], published_at: 2.days.ago) seller_post.send_emails = false seller_post.shown_on_profile = true seller_post.save! missed_posts = Installment.missed_for_purchase(@purchase) expect(missed_posts).to eq [] 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/installment_scopes_spec.rb
spec/models/installment/installment_scopes_spec.rb
# frozen_string_literal: true require "spec_helper" describe "InstallmentScopes" do before do @creator = create(:named_user, :with_avatar) @installment = create(:installment, call_to_action_text: "CTA", call_to_action_url: "https://www.example.com", seller: @creator) end describe ".shown_on_profile" do before do @installment1 = create(:installment, shown_on_profile: true, send_emails: false) @installment2 = create(:installment, shown_on_profile: true, send_emails: true) create(:installment) end it "returns installments shown on profile" do Installment.shown_on_profile.tap do |installments| expect(installments.count).to eq(2) expect(installments).to contain_exactly(@installment1, @installment2) end end end describe ".profile_only" do before do @installment = create(:installment, shown_on_profile: true, send_emails: false) create(:installment, shown_on_profile: false, send_emails: true) end it "returns installments shown only on profile" do Installment.profile_only.tap do |installments| expect(installments.count).to eq(1) expect(installments).to contain_exactly(@installment) end end end describe ".published" do let!(:published_installement) { create(:published_installment) } let!(:not_published_installement) { create(:installment) } it "returns published installments" do result = Installment.published expect(result).to include(published_installement) expect(result).to_not include(not_published_installement) end end describe ".not_published" do let!(:published_installement) { create(:published_installment) } let!(:not_published_installement) { create(:installment) } it "returns unpublished installments" do result = Installment.not_published expect(result).to include(not_published_installement) expect(result).to_not include(published_installement) end end describe ".scheduled" do let!(:published_installment) { create(:published_installment) } let!(:scheduled_installment) { create(:scheduled_installment) } let!(:drafts_installment) { create(:installment) } it "returns scheduled installments" do result = Installment.scheduled expect(result).to include(scheduled_installment) expect(result).to_not include(published_installment, drafts_installment) end end describe ".draft" do let!(:published_installment) { create(:published_installment) } let!(:scheduled_installment) { create(:scheduled_installment) } let!(:drafts_installment) { create(:installment) } it "returns draft installments" do result = Installment.draft expect(result).to include(drafts_installment) expect(result).to_not include(published_installment, scheduled_installment) 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/installment_validations_spec.rb
spec/models/installment/installment_validations_spec.rb
# frozen_string_literal: true require "spec_helper" describe "InstallmentValidations" do describe "#validate_sending_limit_for_sellers" do before do stub_const("Installment::SENDING_LIMIT", 2) @seller = create(:user) @installment = build(:installment, seller: @seller) end context "when seller is sending less than 100 emails" do it "returns true" do expect(@installment.valid?).to eq true expect(@installment.errors.full_messages).to eq [] end end context "when seller has less than $100 revenue" do it "allows to delete the post that was sent to more than 100 email addresses" do @installment.save! allow(@installment).to receive(:audience_members_count).and_return(Installment::SENDING_LIMIT + 1) expect do @installment.mark_deleted! end.to change { Installment.alive.count }.by(-1) end end context "when seller is sending more than 100 emails" do context "when seller has less than $100 sales" do it "returns minimum sales error" do allow(@installment).to receive(:audience_members_count).and_return(Installment::SENDING_LIMIT + 1) expect(@installment.valid?).to eq false expect(@installment.errors.full_messages.to_sentence).to eq("<a href='/help/article/269-balance-page' target='_blank' rel='noreferrer'>Sorry, you cannot send out more than 2 emails until you have $100 in total earnings.</a>") end context "for an abandoned cart workflow installment" do it "returns true with no errors" do @installment.installment_type = Installment::ABANDONED_CART_TYPE allow(@installment).to receive(:audience_members_count).and_return(Installment::SENDING_LIMIT + 1) expect(@installment).to be_valid expect(@installment.errors.size).to eq(0) end end end context "when seller has $100 sales" do it "returns true with no errors" do allow(@seller).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE) allow(@installment).to receive(:audience_members_count).and_return(Installment::SENDING_LIMIT + 1) expect(@installment.valid?).to eq true expect(@installment.errors.full_messages).to eq [] end end end end describe "field validations" do it "when name is longer than 255 characters" do installment = build(:installment, name: "a" * 256) expect(installment.valid?).to eq false expect(installment.errors.messages).to eq( name: ["is too long (maximum is 255 characters)"] ) end it "disallows records with no message" do installment = build(:installment, name: "installment1", message: nil, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/myfile.jpeg", link: create(:product)) expect(installment).to_not be_valid end it "disallows records with empty HTML-only message content" do installment = build( :installment, name: "installment1", message: "<p><br></p>", link: create(:product), send_emails: true ) expect(installment).not_to be_valid expect(installment.errors.full_messages).to include("Please include a message as part of the update.") end end describe "#shown_on_profile_only_for_confirmed_users" do it "allows creating, updating, and deleting non-profile posts belonging to unconfirmed users" do product = create(:product, user: create(:unconfirmed_user)) post = create(:installment, link: product) expect(post).to be_valid post = create(:installment, shown_on_profile: true) post.seller.update!(confirmed_at: nil) post.update!(shown_on_profile: false) expect(post).to be_valid expect { post.destroy! }.not_to(raise_error) end it "disallows creating profile posts by unconfirmed users" do product = create(:product, user: create(:unconfirmed_user)) post = build(:installment, link: product, shown_on_profile: true) expect(post).not_to be_valid expect(post.errors.full_messages).to include "Please confirm your email before creating a public post." end it "disallows updating a post to be a profile post belonging to an unconfirmed user" do product = create(:product, user: create(:unconfirmed_user)) post = create(:installment, link: product) expect(post).to be_valid post.update(shown_on_profile: true) expect(post).not_to be_valid expect(post.errors.full_messages).to include "Please confirm your email before creating a public post." end it "allows soft-deleting a profile post belonging to an unconfirmed user" do post = create(:installment, shown_on_profile: true) post.seller.update!(confirmed_at: nil) expect { post.mark_deleted! }.not_to(raise_error) end it "allows deleting a profile post belonging to an unconfirmed user" do post = create(:installment, shown_on_profile: true) post.seller.update!(confirmed_at: nil) expect { post.destroy! }.not_to(raise_error) end it "allows creating, updating, and deleting profile posts belonging to confirmed users" do post = create(:installment, shown_on_profile: true) expect(post).to be_valid post = create(:installment) post.update!(shown_on_profile: true) expect(post).to be_valid expect { post.destroy! }.not_to(raise_error) end end describe "#published_at_cannot_be_in_the_future" do before do @post = build(:installment, name: "sample name", message: "sample message") end it "allows published_at to be nil" do expect(@post.published_at).to be_nil expect(@post).to be_valid end it "allows published_at to be in the past" do @post.published_at = Time.current expect(@post).to be_valid end it "disallows published_at to be in the future" do @post.published_at = 1.minute.from_now expect(@post).not_to be_valid expect(@post.errors.full_messages).to include("Please enter a publish date in the past.") 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/installment_filters_spec.rb
spec/models/installment/installment_filters_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/with_filtering_support" describe "InstallmentFilters" do before do @creator = create(:named_user, :with_avatar) @installment = create(:installment, call_to_action_text: "CTA", call_to_action_url: "https://www.example.com", seller: @creator) end describe "#add_and_validate_filters" do let(:user) { create(:user) } let!(:product) { create(:product, user:) } subject(:add_and_validate_filters) { filterable_object.add_and_validate_filters(params, user) } it_behaves_like "common customer recipient filter validation behavior", audience_type: "product" do let(:filterable_object) { create(:product_installment, seller: user, link: product) } end it_behaves_like "common customer recipient filter validation behavior", audience_type: "variant" do let(:filterable_object) { create(:variant_installment, seller: user, link: product) } end it_behaves_like "common customer recipient filter validation behavior", audience_type: "seller" do let(:filterable_object) { create(:seller_installment, seller: user, link: product) } end it_behaves_like "common non-customer recipient filter validation behavior", audience_type: "audience" do let(:filterable_object) { create(:audience_installment, seller: user, link: product) } end it_behaves_like "common non-customer recipient filter validation behavior", audience_type: "follower" do let(:filterable_object) { create(:follower_installment, seller: user, link: product) } end it_behaves_like "common non-customer recipient filter validation behavior", audience_type: "affiliate" do let(:filterable_object) { create(:affiliate_installment, seller: user, link: 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/installment/installment_send_installment_spec.rb
spec/models/installment/installment_send_installment_spec.rb
# frozen_string_literal: true require "spec_helper" describe "InstallmentSendInstallment" do before do @creator = create(:named_user, :with_avatar) @installment = create(:installment, call_to_action_text: "CTA", call_to_action_url: "https://www.example.com", seller: @creator) end describe "publish" do it "sets published_at" do travel_to(Time.current) do expect { @installment.publish! }.to change { @installment.published_at.to_s }.to(Time.current.to_s) end end context "video transcoding" do 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, installment: @installment, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4") video_file_2 = create(:product_file, installment: @installment, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter3.mp4") video_file_3 = create(:product_file, installment: @installment, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter4.mp4") video_file_3.delete! @installment.publish! expect(TranscodeVideoForStreamingWorker).to_not have_enqueued_sidekiq_job(video_file_1.id, video_file_1.class.name) expect(TranscodeVideoForStreamingWorker).to_not have_enqueued_sidekiq_job(video_file_2.id, video_file_2.class.name) expect(TranscodeVideoForStreamingWorker).to_not have_enqueued_sidekiq_job(video_file_3.id, video_file_3.class.name) @installment.unpublish! allow_any_instance_of(ProductFile).to receive(:queue_for_transcoding?).and_return(true) @installment.publish! expect(TranscodeVideoForStreamingWorker).to have_enqueued_sidekiq_job(video_file_1.id, video_file_1.class.name) expect(TranscodeVideoForStreamingWorker).to have_enqueued_sidekiq_job(video_file_2.id, video_file_2.class.name) expect(TranscodeVideoForStreamingWorker).to_not have_enqueued_sidekiq_job(video_file_3.id, video_file_3.class.name) end describe "published installments" do before do allow(FFMPEG::Movie).to receive(:new) do double.tap do |movie_double| allow(movie_double).to receive(:duration).and_return(13) allow(movie_double).to receive(:frame_rate).and_return(60) allow(movie_double).to receive(:height).and_return(240) allow(movie_double).to receive(:width).and_return(320) allow(movie_double).to receive(:bitrate).and_return(125_779) end end @s3_double = double allow(@s3_double).to receive(:content_length).and_return(10_000) allow(@s3_double).to receive(:get).and_return("") create(:product_file, installment: @installment, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png") @installment.publish! end it "transcodes video when the link is already published" do video_file = create(:product_file, installment: @installment, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4") allow(video_file).to receive(:s3_object).and_return(@s3_double) allow(video_file).to receive(:confirm_s3_key!) video_file.analyze expect(TranscodeVideoForStreamingWorker).to have_enqueued_sidekiq_job(video_file.id, video_file.class.name) end it "doesn't transcode when the link is unpublished" do @installment.link.unpublish! @installment.unpublish! @installment.reload video_file = create(:product_file, link: @installment.link, installment: @installment, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4") allow(video_file).to receive(:s3_object).and_return(@s3_double) allow(video_file).to receive(:confirm_s3_key!) video_file.analyze expect(TranscodeVideoForStreamingWorker).not_to have_enqueued_sidekiq_job(video_file.id, video_file.class.name) end end end end describe "send_installment_from_workflow_for_purchase" do before do @seller = create(:user) @product = create(:product, user: @seller) vc = create(:variant_category, link: @product) @variant1 = create(:variant, variant_category: vc) @variant2 = create(:variant, variant_category: vc) @workflow = create(:workflow, seller: @seller, link: @product) @installment = create(:installment, link: @product, workflow: @workflow) @purchase1 = create(:purchase, link: @product, created_at: 1.week.ago, price_cents: 100) @purchase2 = create(:purchase, link: @product, email: "tuhinA@gumroad.com", created_at: 2.weeks.ago, price_cents: 100) end it "sends a purchase_installment email for the purchase" do expect(PostSendgridApi).to receive(:process).with( post: @installment, recipients: [{ email: @purchase1.email, purchase: @purchase1 }], cache: {} ) expect(PostSendgridApi).to receive(:process).with( post: @installment, recipients: [{ email: @purchase2.email, purchase: @purchase2 }], cache: anything ) @installment.send_installment_from_workflow_for_purchase(@purchase1.id) @installment.send_installment_from_workflow_for_purchase(@purchase2.id) end it "respects can_contact for purchase installments" do @purchase2.can_contact = false @purchase2.save! expect(PostSendgridApi).to receive(:process).with( post: @installment, recipients: [{ email: @purchase1.email, purchase: @purchase1 }], cache: {} ) @installment.send_installment_from_workflow_for_purchase(@purchase1.id) @installment.send_installment_from_workflow_for_purchase(@purchase2.id) end it "does not send a purchase_installment if buyer got the installment from another purchase" do link2 = create(:product, user: @seller) purchase3 = create(:purchase, link: link2, email: "tuhinA@gumroad.com", created_at: 2.weeks.ago, price_cents: 100) create(:creator_contacting_customers_email_info, installment: @installment, purchase: purchase3) expect(PostSendgridApi).to receive(:process).with( post: @installment, recipients: [{ email: @purchase1.email, purchase: @purchase1 }], cache: {} ) @installment.send_installment_from_workflow_for_purchase(@purchase1.id) @installment.send_installment_from_workflow_for_purchase(@purchase2.id) end it "sends a purchase_installment if buyer got the installment from another purchase but it has since been refunded" do link2 = create(:product, user: @seller) purchase3 = create(:purchase, link: link2, email: "tuhinA@gumroad.com", created_at: 2.weeks.ago, price_cents: 100) create(:creator_contacting_customers_email_info, installment: @installment, purchase: purchase3) @installment.send_installment_from_workflow_for_purchase(@purchase2.id) expect(PostSendgridApi).to receive(:process).with( post: @installment, recipients: [{ email: @purchase2.email, purchase: @purchase2 }], cache: {} ) purchase3.update!(stripe_refunded: true) @installment.send_installment_from_workflow_for_purchase(@purchase2.id) end describe "variant workflows" do before do @variant1_workflow = create(:variant_workflow, link: @product, base_variant: @variant1) @variant1_installment = create(:installment, link: @product, workflow: @variant1_workflow) @variant2_workflow = create(:variant_workflow, link: @product, base_variant: @variant2) @variant2_installment = create(:installment, link: @product, workflow: @variant2_workflow) @purchase1.update!(variant_attributes: [@variant1]) end it "sends a purchase_installment email for a purchase of a variant with a workflow" do expect(PostSendgridApi).to receive(:process).with( post: @variant1_installment, recipients: [{ email: @purchase1.email, purchase: @purchase1 }], cache: {} ) @variant1_installment.send_installment_from_workflow_for_purchase(@purchase1.id) end it "does not send a purchase_installment email for a variant that was not purchased" do expect(PostSendgridApi).not_to receive(:process) @variant2_installment.send_installment_from_workflow_for_purchase(@purchase1.id) @variant1_installment.send_installment_from_workflow_for_purchase(@purchase2.id) end end describe "multi-product or variant workflows" do before do @other_product = create(:product, user: @seller) @other_variant = create(:variant, variant_category: create(:variant_category, link: @other_product)) @purchase1.update!(variant_attributes: [@variant1]) end it "sends a purchase_installment email if the purchase is for the targeted product" do multi_product_workflow = create(:seller_workflow, seller: @seller, bought_products: [@product.unique_permalink, @other_product.unique_permalink]) multi_product_installment = create(:installment, workflow: multi_product_workflow) multi_product_and_variant_workflow = create(:seller_workflow, seller: @seller, bought_products: [@product.unique_permalink], bought_variants: [@other_variant.external_id]) multi_product_and_variant_installment = create(:installment, workflow: multi_product_and_variant_workflow) expect(PostSendgridApi).to receive(:process).with( post: multi_product_installment, recipients: [{ email: @purchase1.email, purchase: @purchase1 }], cache: {} ) expect(PostSendgridApi).to receive(:process).with( post: multi_product_and_variant_installment, recipients: [{ email: @purchase1.email, purchase: @purchase1 }], cache: {} ) multi_product_installment.send_installment_from_workflow_for_purchase(@purchase1.id) multi_product_and_variant_installment.send_installment_from_workflow_for_purchase(@purchase1.id) end it "sends a purchase_installment email if the purchase is for the targeted variant" do multi_variant_workflow = create(:seller_workflow, seller: @seller, bought_variants: [@variant1.external_id, @other_variant.external_id]) multi_variant_installment = create(:installment, workflow: multi_variant_workflow) multi_product_and_variant_workflow = create(:seller_workflow, seller: @seller, bought_products: [@other_product.unique_permalink], bought_variants: [@variant1.external_id]) multi_product_and_variant_installment = create(:installment, workflow: multi_product_and_variant_workflow) expect(PostSendgridApi).to receive(:process).with( post: multi_variant_installment, recipients: [{ email: @purchase1.email, purchase: @purchase1 }], cache: {} ) expect(PostSendgridApi).to receive(:process).with( post: multi_product_and_variant_installment, recipients: [{ email: @purchase1.email, purchase: @purchase1 }], cache: {} ) multi_variant_installment.send_installment_from_workflow_for_purchase(@purchase1.id) multi_product_and_variant_installment.send_installment_from_workflow_for_purchase(@purchase1.id) end it "does not send a purchase_installment email if the purchase is not for the targeted product" do multi_product_workflow = create(:seller_workflow, seller: @seller, bought_products: [@other_product.unique_permalink]) multi_product_installment = create(:installment, workflow: multi_product_workflow) expect(PostSendgridApi).not_to receive(:process) multi_product_installment.send_installment_from_workflow_for_purchase(@purchase1.id) end it "does not send a purchase_installment email if the purchase is not for the targeted variant" do multi_variant_workflow = create(:seller_workflow, seller: @seller, bought_variants: [@other_variant.external_id]) multi_variant_installment = create(:installment, workflow: multi_variant_workflow) expect(PostSendgridApi).not_to receive(:process) multi_variant_installment.send_installment_from_workflow_for_purchase(@purchase1.id) end end describe "subscriptions" do before do @product = create(:membership_product, user: @seller) @purchase = create(:membership_purchase, link: @product, variant_attributes: [@product.default_tier]) @sub = @purchase.subscription @workflow = create(:workflow, seller: @seller, link: @product) @installment = create(:installment, link: @product, workflow: @workflow) end it "does not do anything if purchase is recurring payment" do @purchase.update_attribute(:is_original_subscription_purchase, false) expect(PostSendgridApi).not_to receive(:process) @installment.send_installment_from_workflow_for_purchase(@purchase.id) end it "does not do anything if subscription is cancelled" do @sub.unsubscribe_and_fail! expect(PostSendgridApi).not_to receive(:process) @installment.send_installment_from_workflow_for_purchase(@purchase.id) end it "queues installment for original subscription purchase and alive subscription" do expect(PostSendgridApi).to receive(:process).with( post: @installment, recipients: [{ email: @purchase.email, purchase: @purchase }], cache: {} ) @installment.send_installment_from_workflow_for_purchase(@purchase.id) end context "when subscription plan has changed" do before do @updated_original_purchase = create(:membership_purchase, subscription_id: @sub.id, link: @product, purchase_state: "not_charged") @purchase.update!(is_archived_original_subscription_purchase: true) end it "queues installment for the current original purchase" do expect(PostSendgridApi).to receive(:process).with( post: @installment, recipients: [{ email: @updated_original_purchase.email, purchase: @updated_original_purchase }], cache: {} ) @installment.send_installment_from_workflow_for_purchase(@purchase.id) end context "and tier has changed" do it "does not queue installment for a workflow belonging to the old tier" do other_tier = create(:variant, variant_category: @product.tier_category) @updated_original_purchase.update!(variant_attributes: [other_tier]) variant_workflow = create(:variant_workflow, seller: @seller, link: @product, base_variant: @product.default_tier) variant_installment = create(:installment, link: @product, base_variant: @product.default_tier, workflow: variant_workflow) expect(PostSendgridApi).not_to receive(:process) variant_installment.send_installment_from_workflow_for_purchase(@purchase.id) end end end it "sends a purchase_installment if buyer got the installment from another subscription but it has since been deactivated" do purchase3 = create(:purchase, link: @purchase.link, email: @purchase.email, created_at: 2.weeks.ago, price_cents: 100) create(:creator_contacting_customers_email_info, installment: @installment, purchase: @purchase) allow(PostSendgridApi).to receive(:process).once @installment.send_installment_from_workflow_for_purchase(purchase3.id) expect(PostSendgridApi).to receive(:process).with( post: @installment, recipients: [{ email: purchase3.email, purchase: purchase3 }], cache: {} ) @sub.update!(deactivated_at: 1.day.ago) @installment.send_installment_from_workflow_for_purchase(purchase3.id) end context "when subscription was reactivated" do before do @purchase.update!(created_at: 1.week.ago) @sub.subscription_events.create!(event_type: :deactivated, occurred_at: 6.days.ago) @sub.subscription_events.create!(event_type: :restarted, occurred_at: 1.day.ago) @installment.update!(published_at: 1.day.ago) create(:installment_rule, installment: @installment, delayed_delivery_time: 1.day) @installment_2 = create(:published_installment, link: @product, workflow: @workflow) create(:installment_rule, installment: @installment_2, delayed_delivery_time: 3.days) end context "when it is too early to send the workflow post" do before do # PostSendgridApi creates this, but is mocked in specs create(:creator_contacting_customers_email_info_sent, purchase: @purchase, installment: @installment, email_name: "purchase_installment") end it "does not send an email" do expect(PostSendgridApi).not_to receive(:process) @installment_2.send_installment_from_workflow_for_purchase(@purchase.id) end it "schedules it to be sent in the future" do @installment_2.send_installment_from_workflow_for_purchase(@purchase.id) expect(SendWorkflowInstallmentWorker).to have_enqueued_sidekiq_job(@installment_2.id, 1, @purchase.id, nil) end end it "sends the next workflow post email when the previous one was deleted" do @installment.update!(deleted_at: Time.current) expect(PostSendgridApi).to receive(:process).with( post: @installment_2, recipients: [{ email: @purchase.email, purchase: @purchase }], cache: {} ) travel_to(2.days.from_now) do @installment_2.send_installment_from_workflow_for_purchase(@purchase.id) end end it "sends the next workflow post email when the previous one was sent on time" do expect(PostSendgridApi).to receive(:process).with( post: @installment, recipients: [{ email: @purchase.email, purchase: @purchase }], cache: anything ) # Enqueue first workflow post @installment.send_installment_from_workflow_for_purchase(@purchase.id) # PostSendgridApi creates this, but is mocked in specs create(:creator_contacting_customers_email_info_sent, purchase: @purchase, installment: @installment, email_name: "purchase_installment") expect(PostSendgridApi).to receive(:process).with( post: @installment_2, recipients: [{ email: @purchase.email, purchase: @purchase }], cache: {} ) # Let's wait 2 days and attempt to send the next workflow post email travel_to(2.days.from_now) do @installment_2.send_installment_from_workflow_for_purchase(@purchase.id) end end end end describe "preorders" do before do @preorder_link = create(:product, is_in_preorder_state: true) @preorder_workflow = create(:workflow, seller: @preorder_link.user, link: @preorder_link) @preorder_purchase = create(:purchase, link: @preorder_link, purchase_state: "preorder_concluded_successfully") @preorder_post = create(:installment, link: @preorder_link, workflow: @preorder_workflow) end it "does not send purchase_installment to chargedback purchases" do @preorder_purchase.update_attribute(:chargeback_date, Time.current) expect(PostSendgridApi).not_to receive(:process) @preorder_post.send_installment_from_workflow_for_purchase(@preorder_purchase.id) end end describe "gifts" do before do @gift_link = create(:product) @gift_workflow = create(:workflow, seller: @gift_link.user, link: @gift_link) @gifter_purchase = create(:purchase, link: @gift_link, is_gift_sender_purchase: true, purchase_state: "successful") @giftee_purchase = create(:purchase, link: @gift_link, purchase_state: "gift_receiver_purchase_successful") @gift_post = create(:installment, link: @gift_link, installment_type: "product") end it "sends a message to the giftee" do expect(PostSendgridApi).to receive(:process).with( post: @gift_post, recipients: [{ email: @giftee_purchase.email, purchase: @giftee_purchase }], cache: {} ) @gift_post.send_installment_from_workflow_for_purchase(@giftee_purchase.id) end end end describe "send_installment_from_workflow_for_follower" do before do @followed = create(:user) @workflow = create(:workflow, seller: @followed, link: nil, workflow_type: Workflow::FOLLOWER_TYPE) @installment = create(:follower_installment, seller: @followed, workflow: @workflow) @follower = create(:active_follower, followed_id: @followed.id, email: "some@email.com") end it "sends a follower_installment email for the purchase" do allow(PostSendgridApi).to receive(:process) @installment.send_installment_from_workflow_for_follower(@follower.id) expect(PostSendgridApi).to have_received(:process).with( post: @installment, recipients: [{ email: @follower.email, follower: @follower, url_redirect: UrlRedirect.last! }], cache: {} ) end it "doesn't send email if following was deleted" do @follower.mark_deleted! expect(PostSendgridApi).not_to receive(:process) @installment.send_installment_from_workflow_for_follower(@follower.id) end it "does not send email if follower has not confirmed" do @follower.update_column(:confirmed_at, nil) expect(PostSendgridApi).not_to receive(:process) @installment.send_installment_from_workflow_for_follower(@follower.id) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false