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/presenters/profile_presenter_spec.rb
spec/presenters/profile_presenter_spec.rb
# frozen_string_literal: true describe ProfilePresenter do include Rails.application.routes.url_helpers let(:seller) { create(:named_seller, bio: "Bio") } let(:logged_in_user) { create(:user) } let(:pundit_user) { SellerContext.new(user: logged_in_user, seller:) } let!(:post) do create( :published_installment, installment_type: Installment::AUDIENCE_TYPE, seller:, shown_on_profile: true ) end let!(:tag1) { create(:tag) } let!(:tag2) { create(:tag) } let!(:membership_product) { create(:membership_product, user: seller, name: "Product", tags: [tag1, tag2]) } let!(:simple_product) { create(:product, user: seller) } let!(:featured_product) { create(:product, user: seller, name: "Featured Product", archived: true, deleted_at: Time.current) } let(:presenter) { described_class.new(pundit_user:, seller: seller.reload) } let(:request) { ActionDispatch::TestRequest.create } let!(:section) { create(:seller_profile_products_section, header: "Section 1", hide_header: true, seller:, shown_products: [membership_product.id, simple_product.id]) } let!(:section2) { create(:seller_profile_posts_section, header: "Section 2", seller:, shown_posts: [post.id]) } let!(:section3) { create(:seller_profile_featured_product_section, header: "Section 3", seller:, featured_product_id: featured_product.id) } let(:tabs) { [{ name: "Tab 1", sections: [section.id, section2.id] }, { name: "Tab2", sections: [] }] } before do seller.seller_profile.json_data[:tabs] = tabs seller.seller_profile.save! create(:team_membership, user: logged_in_user, seller:, role: TeamMembership::ROLE_ADMIN) end describe "#creator_profile" do it "returns profile data object" do expect(presenter.creator_profile).to eq( { avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), external_id: seller.external_id, name: seller.name, twitter_handle: nil, subdomain: seller.subdomain, } ) end end describe "#profile_props" do it "returns the props for the profile products tab" do Link.import(force: true, refresh: true) pundit_user = SellerContext.new(user: logged_in_user, seller: create(:user)) sections_presenter = ProfileSectionsPresenter.new(seller:, query: seller.seller_profile_sections.on_profile) expect(ProfileSectionsPresenter).to receive(:new).with(seller:, query: seller.seller_profile_sections.on_profile).and_call_original props = described_class.new(pundit_user:, seller: seller.reload).profile_props(request:, seller_custom_domain_url: nil) expect(props).to match( { **sections_presenter.props(request:, pundit_user:, seller_custom_domain_url: nil), bio: "Bio", tabs: tabs.map { | tab| { **tab, sections: tab[:sections].map { ObfuscateIds.encrypt(_1) } } } } ) end it "includes data for the edit view when logged in as the seller" do props = presenter.profile_props(seller_custom_domain_url: nil, request:) expect(props).to match a_hash_including(ProfileSectionsPresenter.new(seller:, query: seller.seller_profile_sections.on_profile).props(request:, pundit_user:, seller_custom_domain_url: nil)) end end describe "#profile_settings_props" do it "returns profile settings props object" do Link.import(force: true, refresh: true) expect(presenter.profile_settings_props(request:)).to match( { profile_settings: { name: seller.name, username: seller.username, bio: seller.bio, background_color: "#ffffff", highlight_color: "#ff90e8", font: "ABC Favorit", profile_picture_blob_id: nil, }, memberships: [ProductPresenter.card_for_web(product: membership_product, show_seller: false)], **described_class.new(pundit_user: SellerContext.logged_out, seller:).profile_props(request:, seller_custom_domain_url: nil), } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/product_presenter_spec.rb
spec/presenters/product_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe ProductPresenter do include Rails.application.routes.url_helpers include PreorderHelper include ProductsHelper describe ".new_page_props" do let(:new_seller) { create(:named_seller) } let(:existing_seller) { create(:user) } before do create(:product, user: existing_seller) end it "returns well-formed props with show_orientation_text true for new users with no products" do props = described_class.new_page_props(current_seller: new_seller) release_at_date = displayable_release_at_date(1.month.from_now, new_seller.timezone) expect(props).to match( { current_seller_currency_code: "usd", native_product_types: ["digital", "course", "ebook", "membership", "bundle"], service_product_types: ["call", "coffee"], release_at_date:, show_orientation_text: true, eligible_for_service_products: false, ai_generation_enabled: false, ai_promo_dismissed: false, } ) end it "returns well-formed props with show_orientation_text false for existing users with products" do props = described_class.new_page_props(current_seller: existing_seller) release_at_date = displayable_release_at_date(1.month.from_now, existing_seller.timezone) expect(props).to match( { current_seller_currency_code: "usd", native_product_types: ["digital", "course", "ebook", "membership", "bundle"], service_product_types: ["call", "coffee"], release_at_date:, show_orientation_text: false, eligible_for_service_products: false, ai_generation_enabled: false, ai_promo_dismissed: false, } ) end context "commissions are enabled" do before { Feature.activate_user(:commissions, existing_seller) } it "includes commission in the native product types" do expect(described_class.new_page_props(current_seller: existing_seller)[:service_product_types]).to include("commission") end end context "physical products are enabled" do before { existing_seller.update!(can_create_physical_products: true) } it "includes physical in the native product types" do expect(described_class.new_page_props(current_seller: existing_seller)[:native_product_types]).to include("physical") end end context "user is eligible for service products" do let(:existing_seller) { create(:user, :eligible_for_service_products) } it "sets eligible_for_service_products to true" do expect(described_class.new_page_props(current_seller: existing_seller)[:eligible_for_service_products]).to eq(true) end end end describe "#product_props" do let(:request) { instance_double(ActionDispatch::Request, host: "test.gumroad.com", host_with_port: "test.gumroad.com:31337", protocol: "http", cookie_jar: {}, remote_ip: "0.0.0.0") } let(:buyer) { create(:user) } let(:pundit_user) { SellerContext.new(user: buyer, seller: buyer) } let(:product) { create(:product) } let!(:purchase) { create(:purchase, link: product, purchaser: buyer) } it "returns properties from the page presenter" do expect(ProductPresenter::ProductProps).to receive(:new).with(product:).and_call_original expect(described_class.new(product:, request:, pundit_user:).product_props(recommended_by: "discover", seller_custom_domain_url: nil)).to eq( { product: { id: product.external_id, price_cents: 100, **ProductPresenter::InstallmentPlanProps.new(product:).props, covers: [], currency_code: Currency::USD, custom_view_content_button_text: nil, custom_button_text_option: nil, description_html: "This is a collection of works spanning 1984 — 1994, while I spent time in a shack in the Andes.", pwyw: nil, is_sales_limited: false, is_tiered_membership: false, is_legacy_subscription: false, long_url: short_link_url(product.unique_permalink, host: product.user.subdomain_with_protocol), main_cover_id: nil, name: product.name, permalink: product.unique_permalink, preorder: nil, duration_in_months: nil, quantity_remaining: nil, ratings: { count: 0, average: 0, percentages: [0, 0, 0, 0, 0], }, seller: { avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), id: product.user.external_id, name: product.user.username, profile_url: product.user.profile_url(recommended_by: "discover"), }, collaborating_user: nil, is_compliance_blocked: false, is_published: true, is_physical: false, attributes: [], free_trial: nil, is_quantity_enabled: false, is_multiseat_license: false, hide_sold_out_variants: false, native_type: "digital", is_stream_only: false, streamable: false, options: [], rental: nil, recurrences: nil, rental_price_cents: nil, sales_count: nil, summary: nil, thumbnail_url: nil, analytics: product.analytics_data, has_third_party_analytics: false, ppp_details: nil, can_edit: false, refund_policy: { title: "30-day money back guarantee", fine_print: nil, updated_at: buyer.refund_policy.updated_at.to_date, }, bundle_products: [], public_files: [], audio_previews_enabled: false, }, discount_code: nil, purchase: { content_url: nil, id: purchase.external_id, email_digest: purchase.email_digest, created_at: purchase.created_at, membership: nil, review: nil, should_show_receipt: true, is_gift_receiver_purchase: false, show_view_content_button_on_product_page: false, subscription_has_lapsed: false, total_price_including_tax_and_shipping: "$1" }, wishlists: [], } ) end end describe "#product_page_props" do let(:request) { ActionDispatch::TestRequest.create } let(:pundit_user) { SellerContext.new(user: @user, seller: @user) } let(:seller) { create(:user) } let(:product) { create(:product, user: seller, main_section_index: 1) } let(:sections) { create_list(:seller_profile_products_section, 2, seller: seller, product:) } it "returns the properties for the product page" do product.update!(sections: sections.map(&:id).reverse) presenter = described_class.new(product:, request:, pundit_user:) sections_props = ProfileSectionsPresenter.new(seller:, query: product.seller_profile_sections).props(request:, pundit_user:, seller_custom_domain_url: nil) expect(ProfileSectionsPresenter).to receive(:new).with(seller:, query: product.seller_profile_sections).and_call_original expect(presenter.product_page_props(seller_custom_domain_url: nil)).to eq({ **presenter.product_props(seller_custom_domain_url: nil), **sections_props, sections: sections_props[:sections].reverse, main_section_index: 1, }) end end describe "#edit_props" do let(:request) { instance_double(ActionDispatch::Request, host: "test.gumroad.com", host_with_port: "test.gumroad.com:1234", protocol: "http") } let(:circle_integration) { create(:circle_integration) } let(:discord_integration) { create(:discord_integration) } let(:product) do create( :product_with_pdf_file, name: "Product", description: "I am a product!", custom_permalink: "custom", customizable_price: true, suggested_price_cents: 200, max_purchase_count: 50, quantity_enabled: true, should_show_sales_count: true, active_integrations: [ circle_integration, discord_integration ], tag: "hi", taxonomy_id: 1, discover_fee_per_thousand: 300, is_adult: true, native_type: "ebook", ) end let(:presenter) { described_class.new(product:, request:) } let!(:asset_previews) { create_list(:asset_preview, 2, link: product) } let!(:thumbnail) { create(:thumbnail, product:) } let!(:refund_policy) { create(:product_refund_policy, product:, seller: product.user) } let!(:other_refund_policy) { create(:product_refund_policy, product: create(:product, user: product.user, name: "Other product"), max_refund_period_in_days: 0, fine_print: "This is another refund policy") } let!(:variant_category) { create(:variant_category, link: product, title: "Version") } let!(:version1) { create(:variant, variant_category:, name: "Version 1", description: "I am version 1") } let!(:version2) { create(:variant, variant_category:, name: "Version 2", price_difference_cents: 100, max_purchase_count: 100) } let!(:profile_section) { create(:seller_profile_products_section, seller: product.user, shown_products: [product.id]) } let!(:custom_domain) { create(:custom_domain, :with_product, product:) } let(:product_files) do product_file = product.product_files.first [{ attached_product_name: "Product", extension: "PDF", file_name: "Display Name", display_name: "Display Name", description: "Description", file_size: 50, id: product_file.external_id, is_pdf: true, pdf_stamp_enabled: false, is_streamable: false, stream_only: false, is_transcoding_in_progress: false, isbn: nil, pagelength: 3, duration: nil, subtitle_files: [], url: product_file.url, thumbnail: nil, status: { type: "saved" } }] end let(:available_countries) { ShippingDestination::Destinations.shipping_countries.map { { code: _1[0], name: _1[1] } } } before do product.save_custom_button_text_option("pay_prompt") product.save_custom_summary("To summarize, I am a product.") product.save_custom_attributes({ "Detail 1" => "Value 1" }) product.custom_view_content_button_text = "Download Files" product.custom_receipt_text = "Thank you for purchasing! Feel free to contact us any time for support." product.save product.user.reload end it "returns the properties for the product edit page" do expect(presenter.edit_props).to eq( { product: { name: "Product", description: "I am a product!", custom_permalink: "custom", price_cents: 100, **ProductPresenter::InstallmentPlanProps.new(product: presenter.product).props, customizable_price: true, suggested_price_cents: 200, custom_button_text_option: "pay_prompt", custom_summary: "To summarize, I am a product.", custom_view_content_button_text: "Download Files", custom_view_content_button_text_max_length: 26, custom_receipt_text: "Thank you for purchasing! Feel free to contact us any time for support.", custom_receipt_text_max_length: 500, custom_attributes: { "Detail 1" => "Value 1" }, file_attributes: [ { name: "Size", value: "50 Bytes" }, { name: "Length", value: "3 pages" } ], max_purchase_count: 50, quantity_enabled: true, can_enable_quantity: true, should_show_sales_count: true, hide_sold_out_variants: false, is_epublication: false, product_refund_policy_enabled: false, section_ids: [profile_section.external_id], taxonomy_id: "1", tags: ["hi"], display_product_reviews: true, is_adult: true, discover_fee_per_thousand: 300, refund_policy: { allowed_refund_periods_in_days: [ { key: 0, value: "No refunds allowed" }, { key: 7, value: "7-day money back guarantee" }, { key: 14, value: "14-day money back guarantee" }, { key: 30, value: "30-day money back guarantee" }, { key: 183, value: "6-month money back guarantee" } ], max_refund_period_in_days: 30, title: "30-day money back guarantee", fine_print: "This is a product-level refund policy", fine_print_enabled: true }, is_published: true, covers: asset_previews.map(&:as_json), integrations: { "circle" => circle_integration.as_json, "discord" => discord_integration.as_json, "zoom" => nil, "google_calendar" => nil, }, variants: [ { id: version1.external_id, name: "Version 1", description: "I am version 1", price_difference_cents: 0, max_purchase_count: nil, integrations: { "circle" => false, "discord" => false, "zoom" => false, "google_calendar" => false, }, rich_content: [], sales_count_for_inventory: 0, active_subscribers_count: 0, }, { id: version2.external_id, name: "Version 2", description: "", price_difference_cents: 100, max_purchase_count: 100, integrations: { "circle" => false, "discord" => false, "zoom" => false, "google_calendar" => false, }, rich_content: [], sales_count_for_inventory: 0, active_subscribers_count: 0, } ], availabilities: [], shipping_destinations: [], custom_domain: custom_domain.domain, free_trial_enabled: false, free_trial_duration_amount: nil, free_trial_duration_unit: nil, should_include_last_post: false, should_show_all_posts: false, block_access_after_membership_cancellation: false, duration_in_months: nil, subscription_duration: nil, collaborating_user: nil, rich_content: [], files: product_files, has_same_rich_content_for_all_variants: false, is_multiseat_license: false, call_limitation_info: nil, native_type: "ebook", require_shipping: false, cancellation_discount: nil, public_files: [], audio_previews_enabled: false, community_chat_enabled: nil, }, id: product.external_id, unique_permalink: product.unique_permalink, currency_type: "usd", thumbnail: thumbnail.as_json, refund_policies: [ { id: other_refund_policy.external_id, title: "No refunds allowed", fine_print: "This is another refund policy", product_name: "Other product", max_refund_period_in_days: 0, } ], is_tiered_membership: false, is_listed_on_discover: false, is_physical: false, earliest_membership_price_change_date: BaseVariant::MINIMUM_DAYS_TIL_EXISTING_MEMBERSHIP_PRICE_CHANGE.days.from_now.in_time_zone(product.user.timezone).iso8601, profile_sections: [ { id: profile_section.external_id, header: "", product_names: ["Product"], default: true, } ], taxonomies: Discover::TaxonomyPresenter.new.taxonomies_for_nav, custom_domain_verification_status: { success: false, message: "Domain verification failed. Please make sure you have correctly configured the DNS record for #{custom_domain.domain}." }, sales_count_for_inventory: 0, successful_sales_count: 0, ratings: { count: 0, average: 0, percentages: [0, 0, 0, 0, 0], }, seller: UserPresenter.new(user: product.user).author_byline_props, existing_files: product_files, s3_url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}", aws_key: AWS_ACCESS_KEY, available_countries:, google_client_id: "524830719781-6h0t2d14kpj9j76utctvs3udl0embkpi.apps.googleusercontent.com", google_calendar_enabled: false, seller_refund_policy_enabled: true, seller_refund_policy: { title: "30-day money back guarantee", fine_print: nil, }, cancellation_discounts_enabled: false, } ) end context "membership" do let(:membership) do create( :membership_product, name: "Membership", native_type: "membership", description: "Join now", active_integrations: [discord_integration], free_trial_enabled: true, free_trial_duration_amount: 1, free_trial_duration_unit: "month", duration_in_months: 6, should_include_last_post: true, should_show_all_posts: true, ) end let(:presenter) { described_class.new(product: membership, request:) } let(:tier) { membership.alive_variants.first } let!(:collaborator) { create(:collaborator, seller: membership.user, products: [membership]) } let!(:cancellation_discount_offer_code) { create(:cancellation_discount_offer_code, user: membership.user, amount_cents: 0, products: [membership]) } before do tier.update!( description: "I am a tier!", max_purchase_count: 10, customizable_price: true, apply_price_changes_to_existing_memberships: true, subscription_price_change_effective_date: 10.days.from_now, subscription_price_change_message: "Price change!", ) tier.prices.first.update!(suggested_price_cents: 200) tier.active_integrations << discord_integration create(:purchase, :with_review, link: membership, variant_attributes: [tier]) membership.save_custom_button_text_option("") Feature.activate_user(:cancellation_discounts, membership.user) end it "returns the properties for the product edit page" do expect(presenter.edit_props).to eq( { product: { name: "Membership", description: "Join now", custom_permalink: nil, price_cents: 0, **ProductPresenter::InstallmentPlanProps.new(product: presenter.product).props, customizable_price: false, suggested_price_cents: nil, custom_button_text_option: nil, custom_summary: nil, custom_view_content_button_text: nil, custom_view_content_button_text_max_length: 26, custom_receipt_text: nil, custom_receipt_text_max_length: 500, custom_attributes: [], file_attributes: [], max_purchase_count: nil, quantity_enabled: false, can_enable_quantity: false, should_show_sales_count: false, hide_sold_out_variants: false, is_epublication: false, product_refund_policy_enabled: false, refund_policy: { allowed_refund_periods_in_days: [ { key: 0, value: "No refunds allowed" }, { key: 7, value: "7-day money back guarantee" }, { key: 14, value: "14-day money back guarantee" }, { key: 30, value: "30-day money back guarantee" }, { key: 183, value: "6-month money back guarantee" } ], max_refund_period_in_days: 30, title: "30-day money back guarantee", fine_print: nil, fine_print_enabled: false, }, is_published: true, covers: [], integrations: { "circle" => nil, "discord" => discord_integration.as_json, "zoom" => nil, "google_calendar" => nil, }, variants: [ { id: tier.external_id, name: "Untitled", description: "I am a tier!", max_purchase_count: 10, customizable_price: true, recurrence_price_values: { "monthly" => { enabled: true, price_cents: 100, price: "1", suggested_price_cents: 200, suggested_price: "2", }, "quarterly" => { enabled: false }, "biannually" => { enabled: false }, "yearly" => { enabled: false }, "every_two_years" => { enabled: false }, }, integrations: { "circle" => false, "discord" => true, "zoom" => false, "google_calendar" => false, }, apply_price_changes_to_existing_memberships: true, subscription_price_change_effective_date: tier.subscription_price_change_effective_date, subscription_price_change_message: "Price change!", rich_content: [], sales_count_for_inventory: 1, active_subscribers_count: 0, }, ], availabilities: [], shipping_destinations: [], section_ids: [], taxonomy_id: nil, tags: [], display_product_reviews: true, is_adult: false, discover_fee_per_thousand: 100, custom_domain: "", free_trial_enabled: true, free_trial_duration_amount: 1, free_trial_duration_unit: "month", should_include_last_post: true, should_show_all_posts: true, block_access_after_membership_cancellation: false, duration_in_months: 6, subscription_duration: "monthly", collaborating_user: { id: collaborator.affiliate_user.external_id, name: collaborator.affiliate_user.username, profile_url: collaborator.affiliate_user.subdomain_with_protocol, avatar_url: collaborator.affiliate_user.avatar_url, }, rich_content: [], files: [], has_same_rich_content_for_all_variants: false, is_multiseat_license: false, call_limitation_info: nil, native_type: "membership", require_shipping: false, cancellation_discount: { discount: { type: "fixed", cents: 0 }, duration_in_billing_cycles: 3 }, public_files: [], audio_previews_enabled: false, community_chat_enabled: nil, }, id: membership.external_id, unique_permalink: membership.unique_permalink, currency_type: "usd", thumbnail: nil, refund_policies: [], is_tiered_membership: true, is_listed_on_discover: false, is_physical: false, earliest_membership_price_change_date: BaseVariant::MINIMUM_DAYS_TIL_EXISTING_MEMBERSHIP_PRICE_CHANGE.days.from_now.in_time_zone(membership.user.timezone).iso8601, profile_sections: [], taxonomies: Discover::TaxonomyPresenter.new.taxonomies_for_nav, custom_domain_verification_status: nil, sales_count_for_inventory: 0, successful_sales_count: 0, ratings: { count: 1, average: 5, percentages: [0, 0, 0, 0, 100], }, seller: UserPresenter.new(user: membership.user).author_byline_props, existing_files: [], s3_url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}", aws_key: AWS_ACCESS_KEY, available_countries:, google_client_id: "524830719781-6h0t2d14kpj9j76utctvs3udl0embkpi.apps.googleusercontent.com", google_calendar_enabled: false, seller_refund_policy_enabled: true, seller_refund_policy: { title: "30-day money back guarantee", fine_print: nil, }, cancellation_discounts_enabled: true, } ) end end context "call product" do let(:call) { create(:call_product, durations: []) } let(:presenter) { described_class.new(product: call, request:) } let(:durations) { call.variant_categories.first } let!(:thirty_minutes) { create(:variant, variant_category: durations, name: "30 minutes", duration_in_minutes: 30, description: "Shorter call") } let!(:sixty_minutes) { create(:variant, variant_category: durations, name: "60 minutes", duration_in_minutes: 60, description: "Longer call") } let!(:availability) { create(:call_availability, call:) } before do call.call_limitation_info.update!(minimum_notice_in_minutes: 30, maximum_calls_per_day: 5) end it "returns properties for the product edit page" do product_props = presenter.edit_props[:product] expect(product_props[:can_enable_quantity]).to eq(false) expect(product_props[:variants]).to eq( [ { id: thirty_minutes.external_id, name: "30 minutes", description: "Shorter call", price_difference_cents: 0, duration_in_minutes: 30, max_purchase_count: nil, integrations: { "circle" => false, "discord" => false, "zoom" => false, "google_calendar" => false, }, rich_content: [], sales_count_for_inventory: 0, active_subscribers_count: 0, }, { id: sixty_minutes.external_id, name: "60 minutes", description: "Longer call", price_difference_cents: 0, duration_in_minutes: 60, max_purchase_count: nil, integrations: { "circle" => false, "discord" => false, "zoom" => false, "google_calendar" => false, }, rich_content: [], sales_count_for_inventory: 0, active_subscribers_count: 0, }, ] ) expect(product_props[:call_limitation_info]).to eq( { minimum_notice_in_minutes: 30, maximum_calls_per_day: 5, } ) end it "returns availabilities" do expect(presenter.edit_props[:product][:availabilities]).to eq( [ { id: availability.external_id, start_time: availability.start_time.iso8601, end_time: availability.end_time.iso8601, } ] ) end end context "new product" do let(:new_product) { create(:product, name: "Product", description: "Boring") } let(:presenter) { described_class.new(product: new_product, request:) } it "returns the properties for the product edit page" do expect(presenter.edit_props).to eq( { product: { name: "Product", description: "Boring", custom_permalink: nil, price_cents: 100, **ProductPresenter::InstallmentPlanProps.new(product: presenter.product).props, customizable_price: false, suggested_price_cents: nil, custom_button_text_option: nil, custom_summary: nil, custom_view_content_button_text: nil, custom_view_content_button_text_max_length: 26, custom_receipt_text: nil, custom_receipt_text_max_length: 500, custom_attributes: [], file_attributes: [], max_purchase_count: nil, quantity_enabled: false, can_enable_quantity: true, should_show_sales_count: false, hide_sold_out_variants: false, is_epublication: false, product_refund_policy_enabled: false, section_ids: [], taxonomy_id: nil, tags: [], display_product_reviews: true, is_adult: false, discover_fee_per_thousand: 100, refund_policy: { allowed_refund_periods_in_days: [ { key: 0, value: "No refunds allowed" }, { key: 7, value: "7-day money back guarantee" }, { key: 14, value: "14-day money back guarantee" }, { key: 30, value: "30-day money back guarantee" }, { key: 183, value: "6-month money back guarantee" } ], max_refund_period_in_days: 30, title: "30-day money back guarantee", fine_print: nil, fine_print_enabled: false, }, is_published: true, covers: [], integrations: { "circle" => nil, "discord" => nil, "zoom" => nil, "google_calendar" => nil, }, variants: [], availabilities: [], shipping_destinations: [], custom_domain: "", free_trial_enabled: false, free_trial_duration_amount: nil, free_trial_duration_unit: nil, should_include_last_post: false, should_show_all_posts: false, block_access_after_membership_cancellation: false, duration_in_months: nil, subscription_duration: nil, collaborating_user: nil, rich_content: [], files: [], has_same_rich_content_for_all_variants: false, is_multiseat_license: false,
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/settings/team_presenter_spec.rb
spec/presenters/settings/team_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe Settings::TeamPresenter do let(:seller_one) { create(:user) } let(:pundit_user) { SellerContext.new(user: seller_one, seller: seller_one) } describe "initialize" do it "assigns the correct instance variables" do presenter = described_class.new(pundit_user:) expect(presenter.pundit_user).to eq(pundit_user) end end describe "#member_infos" do context "without records" do it "returns owner member info only" do member_infos = described_class.new(pundit_user:).member_infos expect(member_infos.count).to eq(1) expect(member_infos.first.class).to eq(Settings::TeamPresenter::MemberInfo::OwnerInfo) end end context "with records" do let(:seller_two) { create(:user) } let(:seller_three) { create(:user) } before do # seller_two belonging to seller_one team @team_membership = create(:team_membership, user: seller_two, seller: seller_one, role: TeamMembership::ROLE_ADMIN) create(:team_membership, user: seller_two, seller: seller_one, role: TeamMembership::ROLE_ADMIN, deleted_at: Time.current) @team_invitation = create(:team_invitation, seller: seller_one, role: TeamMembership::ROLE_ADMIN) create(:team_invitation, seller: seller_one, role: TeamMembership::ROLE_ADMIN, deleted_at: Time.current) # seller_one belonging to seller_three team - not included in member_infos create(:team_membership, user: seller_one, seller: seller_three, role: TeamMembership::ROLE_ADMIN) create(:team_invitation, seller: seller_three, role: TeamMembership::ROLE_ADMIN) end it "returns seller_one member infos" do member_infos = described_class.new(pundit_user:).member_infos expect(member_infos.count).to eq(3) expect(member_infos.first.class).to eq(Settings::TeamPresenter::MemberInfo::OwnerInfo) membership_info = member_infos.second expect(membership_info.class).to eq(Settings::TeamPresenter::MemberInfo::MembershipInfo) expect(membership_info.to_hash[:id]).to eq(@team_membership.external_id) invitation_info = member_infos.third expect(invitation_info.class).to eq(Settings::TeamPresenter::MemberInfo::InvitationInfo) expect(invitation_info.to_hash[:id]).to eq(@team_invitation.external_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/presenters/settings/team_presenter/member_info/invitation_info_spec.rb
spec/presenters/settings/team_presenter/member_info/invitation_info_spec.rb
# frozen_string_literal: true require "spec_helper" describe Settings::TeamPresenter::MemberInfo::InvitationInfo do let(:seller) { create(:named_seller) } let(:user) { create(:user) } let(:email) { "joe@example.com" } let(:pundit_user) { SellerContext.new(user:, seller:) } let!(:team_invitation) { create(:team_invitation, seller:, email:, role: TeamMembership::ROLE_ADMIN, expires_at: 1.minute.ago) } describe ".build_invitation_info" do context "with user signed in as admin for seller" do let!(:team_membership) { create(:team_membership, seller:, user:, role: TeamMembership::ROLE_ADMIN) } it "returns correct info" do info = Settings::TeamPresenter::MemberInfo.build_invitation_info(pundit_user:, team_invitation:) expect(info.to_hash).to eq({ type: "invitation", id: team_invitation.external_id, role: "admin", name: "", email:, avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), is_expired: true, options: [ { id: "accountant", label: "Accountant" }, { id: "admin", label: "Admin" }, { id: "marketing", label: "Marketing" }, { id: "support", label: "Support" }, { id: "resend_invitation", label: "Resend invitation" }, { id: "remove_from_team", label: "Remove from team" } ], leave_team_option: nil }) end context "when invitation has wip role" do before do # TODO: update once marketing role is no longer WIP team_invitation.update_attribute(:role, TeamMembership::ROLE_MARKETING) end it "includes wip role in options" do info = Settings::TeamPresenter::MemberInfo.build_invitation_info(pundit_user:, team_invitation:) expect(info.to_hash).to eq({ type: "invitation", id: team_invitation.external_id, role: "marketing", name: "", email:, avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), is_expired: true, options: [ { id: "accountant", label: "Accountant" }, { id: "admin", label: "Admin" }, { id: "marketing", label: "Marketing" }, { id: "support", label: "Support" }, { id: "resend_invitation", label: "Resend invitation" }, { id: "remove_from_team", label: "Remove from team" } ], leave_team_option: nil }) end end end context "with user signed in as marketing for seller" do let(:user_with_marketing_role) { create(:user) } let!(:team_membership) { create(:team_membership, seller:, user: user_with_marketing_role, role: TeamMembership::ROLE_MARKETING) } let(:pundit_user) { SellerContext.new(user: user_with_marketing_role, seller:) } it "includes only the current role" do info = Settings::TeamPresenter::MemberInfo.build_invitation_info(pundit_user:, team_invitation:) expect(info.to_hash[:options]).to eq( [ { id: "admin", label: "Admin" } ] ) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/settings/team_presenter/member_info/owner_info_spec.rb
spec/presenters/settings/team_presenter/member_info/owner_info_spec.rb
# frozen_string_literal: true require "spec_helper" describe Settings::TeamPresenter::MemberInfo::OwnerInfo do let(:seller) { create(:named_seller) } describe ".build_owner_info" do it "returns correct info" do info = Settings::TeamPresenter::MemberInfo.build_owner_info(seller) expect(info.to_hash).to eq({ type: "owner", id: seller.external_id, role: "owner", name: seller.display_name, email: seller.form_email, avatar_url: seller.avatar_url, is_expired: false, options: [{ id: "owner", label: "Owner" }], leave_team_option: nil }) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/settings/team_presenter/member_info/membership_info_spec.rb
spec/presenters/settings/team_presenter/member_info/membership_info_spec.rb
# frozen_string_literal: true require "spec_helper" describe Settings::TeamPresenter::MemberInfo::MembershipInfo do let(:seller) { create(:named_seller) } let(:user) { create(:user) } let(:pundit_user) { SellerContext.new(user:, seller:) } describe ".build_membership_info" do let!(:team_membership) { create(:team_membership, seller:, user:, role: TeamMembership::ROLE_ADMIN) } context "with user signed in as admin for seller" do it "returns correct info" do info = Settings::TeamPresenter::MemberInfo.build_membership_info(pundit_user:, team_membership:) expect(info.to_hash).to eq({ type: "membership", id: team_membership.external_id, role: TeamMembership::ROLE_ADMIN, name: user.display_name, email: user.form_email, avatar_url: user.avatar_url, is_expired: false, options: [ { id: "accountant", label: "Accountant" }, { id: "admin", label: "Admin" }, { id: "marketing", label: "Marketing" }, { id: "support", label: "Support" }, ], leave_team_option: { id: "leave_team", label: "Leave team" } }) end context "with other team membership" do let(:other_user) { create(:user) } let!(:other_team_membership) { create(:team_membership, seller:, user: other_user, role: TeamMembership::ROLE_ADMIN) } it "returns correct info" do info = Settings::TeamPresenter::MemberInfo.build_membership_info(pundit_user:, team_membership: other_team_membership) expect(info.to_hash).to eq({ type: "membership", id: other_team_membership.external_id, role: TeamMembership::ROLE_ADMIN, name: other_user.display_name, email: other_user.form_email, avatar_url: other_user.avatar_url, is_expired: false, options: [ { id: "accountant", label: "Accountant" }, { id: "admin", label: "Admin" }, { id: "marketing", label: "Marketing" }, { id: "support", label: "Support" }, { id: "remove_from_team", label: "Remove from team" } ], leave_team_option: nil }) end context "when membership has wip role" do before do # TODO: update once marketing role is no longer WIP other_team_membership.update_attribute(:role, TeamMembership::ROLE_MARKETING) end it "includes wip role in options" do info = Settings::TeamPresenter::MemberInfo.build_membership_info(pundit_user:, team_membership: other_team_membership) expect(info.to_hash[:options]).to eq([ { id: "accountant", label: "Accountant" }, { id: "admin", label: "Admin" }, { id: "marketing", label: "Marketing" }, { id: "support", label: "Support" }, { id: "remove_from_team", label: "Remove from team" } ]) end end end end context "with user signed in as marketing for seller" do let(:user_with_marketing_role) { create(:user) } let!(:team_membership) { create(:team_membership, seller:, user: user_with_marketing_role, role: TeamMembership::ROLE_MARKETING) } let(:pundit_user) { SellerContext.new(user: user_with_marketing_role, seller:) } it "includes only current role for options and leave_team_option" do info = Settings::TeamPresenter::MemberInfo.build_membership_info(pundit_user:, team_membership:) expect(info.to_hash).to eq({ type: "membership", id: team_membership.external_id, role: TeamMembership::ROLE_MARKETING, name: user_with_marketing_role.display_name, email: user_with_marketing_role.form_email, avatar_url: user_with_marketing_role.avatar_url, is_expired: false, options: [ { id: "marketing", label: "Marketing" } ], leave_team_option: { id: "leave_team", label: "Leave team" } }) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/admin/payment_presenter_spec.rb
spec/presenters/admin/payment_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe Admin::PaymentPresenter do describe "#props" do let(:payment) { create(:payment, *payment_traits) } let(:payment_traits) { [] } let(:presenter) { described_class.new(payment:) } subject(:props) { presenter.props } describe "basic structure" do it "returns a hash with all expected keys" do expect(props).to include( :id, :displayed_amount, :payout_period_end_date, :created_at, :user, :state, :humanized_failure_reason, :failed, :cancelled, :returned, :processing, :unclaimed, :non_terminal_state, :processor, :is_stripe_processor, :is_paypal_processor, :processor_fee_cents, :stripe_transfer_id, :stripe_transfer_url, :stripe_connected_account_url, :stripe_connect_account_id, :bank_account, :txn_id, :payment_address, :correlation_id, :was_created_in_split_mode, :split_payments_info ) end end describe "fields" do it "returns the correct field values" do expect(props[:id]).to eq(payment.id) expect(props[:displayed_amount]).to eq(payment.displayed_amount) expect(props[:payout_period_end_date]).to eq(payment.payout_period_end_date) expect(props[:created_at]).to eq(payment.created_at) expect(props[:state]).to eq(payment.state) expect(props[:humanized_failure_reason]).to eq(payment.humanized_failure_reason) expect(props[:failed]).to eq(payment.failed?) expect(props[:cancelled]).to eq(payment.cancelled?) expect(props[:returned]).to eq(payment.returned?) expect(props[:processing]).to eq(payment.processing?) expect(props[:unclaimed]).to eq(payment.unclaimed?) expect(props[:processor]).to eq(payment.processor) expect(props[:processor_fee_cents]).to eq(payment.processor_fee_cents) expect(props[:txn_id]).to eq(payment.txn_id) expect(props[:payment_address]).to eq(payment.payment_address) expect(props[:correlation_id]).to eq(payment.correlation_id) expect(props[:stripe_transfer_id]).to eq(payment.stripe_transfer_id) expect(props[:stripe_connect_account_id]).to eq(payment.stripe_connect_account_id) expect(props[:was_created_in_split_mode]).to eq(payment.was_created_in_split_mode) expect(props[:split_payments_info]).to eq(payment.split_payments_info) end end describe "user association" do context "when payment has a user" do let(:user) { create(:user, name: "Test User") } let(:payment) { create(:payment, user:) } it "returns user information" do expect(props[:user]).to eq( id: user.id, name: user.name ) end end context "when payment has no user" do let(:payment) { create(:payment, user: nil) } it "returns nil" do expect(props[:user]).to be_nil end end end describe "state predicates" do context "when payment is in processing state" do let(:payment_traits) { [] } # Default is processing it "returns correct state predicates" do expect(props[:processing]).to be true expect(props[:failed]).to be false expect(props[:cancelled]).to be false expect(props[:returned]).to be false expect(props[:unclaimed]).to be false end it "identifies non-terminal state correctly" do expect(props[:non_terminal_state]).to be true end end context "when payment is failed" do let(:payment) { create(:payment_failed) } it "returns correct state predicates" do expect(props[:failed]).to be true expect(props[:processing]).to be false end it "identifies terminal state correctly" do expect(props[:non_terminal_state]).to be false end end context "when payment is cancelled" do let(:payment) { create(:payment, state: Payment::CANCELLED) } it "returns correct state predicates" do expect(props[:cancelled]).to be true expect(props[:processing]).to be false end end context "when payment is returned" do let(:payment) { create(:payment_returned) } it "returns correct state predicates" do expect(props[:returned]).to be true expect(props[:processing]).to be false end end context "when payment is unclaimed" do let(:payment) { create(:payment_unclaimed) } it "returns correct state predicates" do expect(props[:unclaimed]).to be true expect(props[:processing]).to be false end it "identifies non-terminal state correctly" do expect(props[:non_terminal_state]).to be true end end context "when payment is completed" do let(:payment) { create(:payment_completed) } it "identifies non-terminal state correctly" do expect(props[:non_terminal_state]).to be true end end end describe "processor types" do context "when payment uses PayPal processor" do let(:payment) do create(:payment_completed, processor: PayoutProcessorType::PAYPAL, txn_id: "PAYPAL-TXN-123", payment_address: "seller@example.com", correlation_id: "CORR-123") end it "includes PayPal-specific information" do expect(props[:txn_id]).to eq("PAYPAL-TXN-123") expect(props[:payment_address]).to eq("seller@example.com") expect(props[:correlation_id]).to eq("CORR-123") end it "identifies PayPal processor correctly" do expect(props[:is_paypal_processor]).to be true expect(props[:is_stripe_processor]).to be false expect(props[:processor]).to eq(PayoutProcessorType::PAYPAL) end end context "when payment uses Stripe processor" do let(:payment) do create(:payment, processor: PayoutProcessorType::STRIPE, stripe_transfer_id: "tr_123456", stripe_connect_account_id: "acct_123456") end it "includes Stripe-specific information" do expect(props[:stripe_transfer_id]).to eq("tr_123456") expect(props[:stripe_connect_account_id]).to eq("acct_123456") expect(props[:stripe_transfer_url]).to eq( StripeUrl.transfer_url("tr_123456", account_id: "acct_123456") ) expect(props[:stripe_connected_account_url]).to eq( StripeUrl.connected_account_url("acct_123456") ) end it "identifies Stripe processor correctly" do expect(props[:is_stripe_processor]).to be true expect(props[:is_paypal_processor]).to be false expect(props[:processor]).to eq(PayoutProcessorType::STRIPE) end end end describe "bank account information" do context "when payment has no bank account" do let(:payment) { create(:payment, bank_account: nil) } it "returns nil for bank_account" do expect(props[:bank_account]).to be_nil end end context "when payment has a bank account" do let(:bank_account) { create(:uk_bank_account) } let(:payment) { create(:payment, bank_account:) } it "returns bank account information" do bank_account_data = props[:bank_account] expect(bank_account_data).to be_a(Hash) expect(bank_account_data[:formatted_account]).to eq(bank_account.formatted_account) end context "when bank account has a credit card" do let(:credit_card) { instance_double(CreditCard, visual: "Visa ending in 1234") } before do allow(bank_account).to receive(:credit_card).and_return(credit_card) end it "includes the credit card visual" do expect(props[:bank_account][:credit_card][:visual]).to eq("Visa ending in 1234") end end context "when bank account has no credit card" do it "includes nil for credit card visual" do expect(props[:bank_account][:credit_card][:visual]).to be_nil 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/presenters/admin/purchase_presenter_spec.rb
spec/presenters/admin/purchase_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe Admin::PurchasePresenter do describe "#props" do let(:seller) { create(:user) } let(:product) { create(:product, user: seller) } let(:purchase) { create(:purchase, link: product, seller: seller) } let(:presenter) { described_class.new(purchase) } subject(:props) { presenter.props } describe "database attributes" do describe "fields" do it "returns the correct field values" do expect(props).to match( formatted_display_price: purchase.formatted_display_price, formatted_gumroad_tax_amount: nil, gumroad_responsible_for_tax: purchase.gumroad_responsible_for_tax?, product: { external_id: product.external_id, name: product.name, long_url: product.long_url }, seller: { email: seller.email, support_email: seller.support_email }, email: purchase.email, created_at: purchase.created_at, updated_at: purchase.updated_at, purchase_state: purchase.purchase_state.capitalize, external_id: purchase.external_id, external_id_numeric: purchase.external_id_numeric, quantity: purchase.quantity, successful: purchase.successful?, failed: purchase.failed?, can_contact: purchase.can_contact?, deleted_at: purchase.deleted_at, fee_cents: purchase.fee_cents, tip: nil, gumroad_tax_cents: purchase.gumroad_tax_cents, formatted_seller_tax_amount: nil, formatted_shipping_amount: nil, formatted_affiliate_credit_amount: nil, formatted_total_transaction_amount: purchase.formatted_total_transaction_amount, charge_processor_id: purchase.charge_processor_id&.capitalize, stripe_transaction: { id: purchase.stripe_transaction_id, search_url: ChargeProcessor.transaction_url_for_admin(purchase.charge_processor_id, purchase.stripe_transaction_id, purchase.charged_using_gumroad_merchant_account?), }, merchant_account: { external_id: purchase.merchant_account.external_id, charge_processor_id: purchase.merchant_account.charge_processor_id.capitalize, holder_of_funds: purchase.merchant_account.holder_of_funds.capitalize, }, refund_policy: nil, stripe_refunded: purchase.stripe_refunded?, stripe_partially_refunded: purchase.stripe_partially_refunded?, chargedback: purchase.chargedback?, chargeback_reversed: purchase.chargeback_reversed?, error_code: nil, last_chargebacked_purchase: nil, variants_list: purchase.variants_list, refunds: [], product_purchases: [], card: { type: purchase.card_type.upcase, visual: match(/\A\d+\z/), country: purchase.card_country, fingerprint_search_url: StripeChargeProcessor.fingerprint_search_url(purchase.stripe_fingerprint), }, ip_address: purchase.ip_address, ip_country: purchase.ip_country, is_preorder_authorization: purchase.is_preorder_authorization, subscription: nil, email_info: nil, is_bundle_purchase: purchase.is_bundle_purchase, url_redirect: nil, offer_code: nil, street_address: purchase.street_address, full_name: purchase.full_name, city: purchase.city, state: purchase.state, zip_code: purchase.zip_code, country: purchase.country, is_gift_sender_purchase: purchase.is_gift_sender_purchase, custom_fields: purchase.custom_fields, license: nil, affiliate_email: nil, gift: nil, can_force_update: purchase.can_force_update?, stripe_fingerprint: purchase.stripe_fingerprint, is_free_trial_purchase: purchase.is_free_trial_purchase?, buyer_blocked: purchase.buyer_blocked?, is_deleted_by_buyer: purchase.is_deleted_by_buyer?, comments_count: purchase.comments.count, ) end end context "when purchase has a tip" do let(:tip) { create(:tip, value_usd_cents: 500) } let(:purchase) { create(:purchase, link: product, seller: seller, tip: tip) } it "returns the tip amount in cents" do expect(props[:tip]).to eq(500) 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/presenters/admin/merchant_account_presenter_spec.rb
spec/presenters/admin/merchant_account_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe Admin::MerchantAccountPresenter do describe "#props" do let(:merchant_account) { create(:merchant_account) } let(:presenter) { described_class.new(merchant_account:) } subject(:props) { presenter.props } describe "database attributes" do before do allow(Stripe::Account).to receive(:retrieve).and_return(double(:account, charges_enabled: false, payouts_enabled: false, requirements: double(:requirements, disabled_reason: "rejected.fraud", as_json: {}))) allow_any_instance_of(MerchantAccount).to receive(:paypal_account_details).and_return(nil) end describe "fields" do it "returns the correct field values" do expect(props).to match( charge_processor_id: merchant_account.charge_processor_id, charge_processor_merchant_id: merchant_account.charge_processor_merchant_id, created_at: merchant_account.created_at, external_id: merchant_account.external_id, user_id: merchant_account.user_id, country: merchant_account.country, country_name: "United States", currency: merchant_account.currency, holder_of_funds: merchant_account.holder_of_funds, stripe_account_url: include("dashboard.stripe.com"), charge_processor_alive_at: merchant_account.charge_processor_alive_at, charge_processor_verified_at: merchant_account.charge_processor_verified_at, charge_processor_deleted_at: merchant_account.charge_processor_deleted_at, updated_at: merchant_account.updated_at, deleted_at: merchant_account.deleted_at, live_attributes: include({ label: "Charges enabled", value: false }), ) end end describe "country information" do context "when merchant account has a country" do let(:merchant_account) { create(:merchant_account, country: "US") } it "returns the country name" do expect(props[:country]).to eq("US") expect(props[:country_name]).to eq("United States") end end context "when merchant account has no country" do let(:merchant_account) { create(:merchant_account, country: nil) } it "returns nil for country_name" do expect(props[:country]).to be_nil expect(props[:country_name]).to be_nil end end end describe "stripe account url" do context "when merchant account is for Stripe" do let(:merchant_account) do create(:merchant_account, charge_processor_id: StripeChargeProcessor.charge_processor_id, charge_processor_merchant_id: "acct_test123") end it "returns the Stripe account URL" do expect(props[:stripe_account_url]).to include("acct_test123") end end context "when merchant account is for PayPal" do let(:merchant_account) do create(:merchant_account_paypal, charge_processor_merchant_id: "PAYPAL123") end it "returns nil for stripe_account_url" do expect(props[:stripe_account_url]).to be_nil end end end end describe "live attributes" do context "for Stripe merchant accounts", :vcr do let(:merchant_account) do create(:merchant_account, charge_processor_merchant_id: "acct_19paZxAQqMpdRp2I") end it "returns the correct attribute values" do props[:live_attributes] expect(props[:live_attributes]).to match_array([ { label: "Charges enabled", value: false }, { label: "Payout enabled", value: false }, { label: "Disabled reason", value: "rejected.fraud" }, { label: "Fields needed", value: hash_including("pending_verification" => ["business_profile.url"]) } ]) end end context "for PayPal merchant accounts", :vcr do let(:merchant_account) do create(:merchant_account_paypal, charge_processor_merchant_id: "B66YJBBNCRW6L") end it "returns the email address associated with the PayPal account" do expect(props[:live_attributes]).to eq([ { label: "Email", value: "sb-byx2u2205460@business.example.com" } ]) end end context "when PayPal account details are not available" do let(:merchant_account) do create(:merchant_account_paypal, charge_processor_merchant_id: "INVALID_ID") end before do allow(merchant_account).to receive(:paypal_account_details).and_return(nil) end it "returns an empty array for live_attributes" do expect(props[:live_attributes]).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/presenters/admin/unreviewed_user_presenter_spec.rb
spec/presenters/admin/unreviewed_user_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe Admin::UnreviewedUserPresenter do include Rails.application.routes.url_helpers describe "#props" do let(:user) do create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) end let(:balance) { create(:balance, user:, amount_cents: 5000) } before do balance # Simulate the total_balance_cents attribute that comes from the service query allow(user).to receive(:total_balance_cents).and_return(5000) end it "returns user id" do props = described_class.new(user).props expect(props[:id]).to eq(user.id) end it "returns external_id" do props = described_class.new(user).props expect(props[:external_id]).to eq(user.external_id) end it "returns display name" do props = described_class.new(user).props expect(props[:name]).to eq(user.display_name) end it "returns email" do props = described_class.new(user).props expect(props[:email]).to eq(user.email) end it "returns unpaid_balance_cents" do props = described_class.new(user).props expect(props[:unpaid_balance_cents]).to eq(5000) end it "returns admin_url with external_id" do props = described_class.new(user).props expect(props[:admin_url]).to eq(admin_user_path(user.external_id)) end it "returns created_at in ISO8601 format" do props = described_class.new(user).props expect(props[:created_at]).to eq(user.created_at.iso8601) end it "returns account_age_days" do user.update!(created_at: 30.days.ago) props = described_class.new(user).props expect(props[:account_age_days]).to eq(30) end describe "payout_method" do it "returns nil when no payout method is configured" do user.update!(payment_address: nil) props = described_class.new(user).props expect(props[:payout_method]).to be_nil end it "returns 'Stripe Connect' when user has Stripe Connect account" do allow(user).to receive(:has_stripe_account_connected?).and_return(true) props = described_class.new(user).props expect(props[:payout_method]).to eq("Stripe Connect") end it "returns 'Stripe' when user has active bank account" do create(:ach_account, user:) props = described_class.new(user).props expect(props[:payout_method]).to eq("Stripe") end it "returns 'PayPal Connect' when user has PayPal account connected" do allow(user).to receive(:has_paypal_account_connected?).and_return(true) user.update!(payment_address: nil) props = described_class.new(user).props expect(props[:payout_method]).to eq("PayPal Connect") end it "returns 'PayPal' when user has legacy PayPal email" do user.update!(payment_address: "paypal@example.com") props = described_class.new(user).props expect(props[:payout_method]).to eq("PayPal") end end describe "revenue_sources" do it "returns empty array when no revenue sources exist" do props = described_class.new(user).props expect(props[:revenue_sources]).to eq([]) end it "includes 'sales' when user has sales balance" do product = create(:product, user:) create(:purchase, seller: user, link: product, purchase_success_balance: balance) props = described_class.new(user).props expect(props[:revenue_sources]).to include("sales") end it "includes 'affiliate' when user has affiliate credits" do product = create(:product) direct_affiliate = create(:direct_affiliate, affiliate_user: user, seller: product.user, products: [product]) purchase = create(:purchase, link: product, affiliate: direct_affiliate) create(:affiliate_credit, affiliate_user: user, seller: product.user, purchase:, link: product, affiliate: direct_affiliate, affiliate_credit_success_balance: balance) props = described_class.new(user).props expect(props[:revenue_sources]).to include("affiliate") expect(props[:revenue_sources]).not_to include("collaborator") end it "includes 'collaborator' when user has collaborator credits" do seller = create(:user) product = create(:product, user: seller) collaborator = create(:collaborator, affiliate_user: user, seller: seller, products: [product]) purchase = create(:purchase, link: product, affiliate: collaborator) create(:affiliate_credit, affiliate_user: user, seller: seller, purchase:, link: product, affiliate: collaborator, affiliate_credit_success_balance: balance) props = described_class.new(user).props expect(props[:revenue_sources]).to include("collaborator") expect(props[:revenue_sources]).not_to include("affiliate") end it "includes 'credit' when user has credits" do create(:credit, user:, balance:, amount_cents: 1000) props = described_class.new(user).props expect(props[:revenue_sources]).to include("credit") end it "includes multiple revenue sources when applicable" do # Add sales product = create(:product, user:) create(:purchase, seller: user, link: product, purchase_success_balance: balance) # Add credit create(:credit, user:, balance:, amount_cents: 1000) props = described_class.new(user).props expect(props[:revenue_sources]).to include("sales") expect(props[:revenue_sources]).to include("credit") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/admin/user_presenter/card_spec.rb
spec/presenters/admin/user_presenter/card_spec.rb
# frozen_string_literal: true require "spec_helper" describe Admin::UserPresenter::Card do describe "#props" do let(:admin_user) { create(:user) } let(:user) { create(:named_user, *user_traits) } let(:user_traits) { [] } let(:pundit_user) { SellerContext.new(user: admin_user, seller: admin_user) } let(:presenter) { described_class.new(user:, pundit_user:) } subject(:props) { presenter.props } before do create_list(:comment, 2, commentable: user, comment_type: Comment::COMMENT_TYPE_NOTE) end describe "fields" do it "returns the correct values" do expect(props[:id]).to eq(user.id) expect(props[:name]).to eq(user.name) expect(props[:bio]).to eq(user.bio) expect(props[:avatar_url]).to eq(user.avatar_url) expect(props[:username]).to eq(user.username) expect(props[:email]).to eq(user.form_email) expect(props[:form_email]).to eq(user.form_email) expect(props[:form_email_domain]).to eq(user.form_email_domain) expect(props[:support_email]).to eq(user.support_email) expect(props[:profile_url]).to eq(user.avatar_url) expect(props[:subdomain_with_protocol]).to eq(user.subdomain_with_protocol) expect(props[:custom_fee_per_thousand]).to eq(user.custom_fee_per_thousand) expect(props[:unpaid_balance_cents]).to eq(user.unpaid_balance_cents) expect(props[:disable_paypal_sales]).to eq(user.disable_paypal_sales) expect(props[:verified]).to eq(user.verified?) expect(props[:suspended]).to eq(user.suspended?) expect(props[:flagged_for_fraud]).to eq(user.flagged_for_fraud?) expect(props[:flagged_for_tos_violation]).to eq(user.flagged_for_tos_violation?) expect(props[:on_probation]).to eq(user.on_probation?) expect(props[:all_adult_products]).to eq(user.all_adult_products?) expect(props[:user_risk_state]).to eq(user.user_risk_state.humanize) expect(props[:comments_count]).to eq(2) expect(props[:compliant]).to eq(user.compliant?) expect(props[:created_at]).to eq(user.created_at) expect(props[:updated_at]).to eq(user.updated_at) expect(props[:deleted_at]).to eq(user.deleted_at) end end describe "blocking information" do context "when user is not blocked by form_email" do it "returns nil for blocked_by_form_email_object" do expect(props[:blocked_by_form_email_object]).to be_nil end end context "when user is blocked by form_email" do let(:blocked_at_time) { 2.days.ago } let(:created_at_time) { 5.days.ago } before do blocked_object = double( "BlockedFormEmail", blocked_at: blocked_at_time, created_at: created_at_time ) allow(user).to receive(:blocked_by_form_email_object).and_return(blocked_object) end it "returns the blocking information" do expect(props[:blocked_by_form_email_object]).to eq( blocked_at: blocked_at_time, created_at: created_at_time ) end end context "when user is not blocked by form_email_domain" do it "returns nil for blocked_by_form_email_domain_object" do expect(props[:blocked_by_form_email_domain_object]).to be_nil end end context "when user is blocked by form_email_domain" do let(:blocked_at_time) { 3.days.ago } let(:created_at_time) { 6.days.ago } before do blocked_object = double( "BlockedFormEmailDomain", blocked_at: blocked_at_time, created_at: created_at_time ) allow(user).to receive(:blocked_by_form_email_domain_object).and_return(blocked_object) end it "returns the blocking information" do expect(props[:blocked_by_form_email_domain_object]).to eq( blocked_at: blocked_at_time, created_at: created_at_time ) end end end describe "user memberships" do context "when user has no memberships" do it "returns an empty array" do expect(props[:admin_manageable_user_memberships]).to eq([]) end end context "when user has memberships" do let(:seller) { create(:user) } let!(:membership) do create(:team_membership, user:, seller:, role: TeamMembership::ROLE_ADMIN) end it "returns an array of membership hashes" do memberships = props[:admin_manageable_user_memberships] expect(memberships).to be_an(Array) expect(memberships.size).to eq(1) end it "includes membership attributes" do membership_data = props[:admin_manageable_user_memberships].first expect(membership_data).to include( id: membership.id, role: membership.role, last_accessed_at: membership.last_accessed_at, created_at: membership.created_at, updated_at: membership.updated_at ) end it "includes seller information" do membership_data = props[:admin_manageable_user_memberships].first expect(membership_data[:seller]).to eq( id: seller.id, avatar_url: seller.avatar_url, display_name_or_email: seller.display_name_or_email ) end end end describe "compliance info" do context "when user has no compliance info" do before do allow(user).to receive(:alive_user_compliance_info).and_return(nil) end it "returns nil" do expect(props[:alive_user_compliance_info]).to be_nil end end context "when user has compliance info" do let(:compliance_info) do create(:user_compliance_info, user:) end before do compliance_info end it "returns a hash with compliance information" do info = props[:alive_user_compliance_info] expect(info).to include( :is_business, :first_name, :last_name, :street_address, :city, :state, :state_code, :zip_code, :country, :country_code, :business_name, :business_type, :business_street_address, :business_city, :business_state, :business_state_code, :business_zip_code, :business_country, :business_country_code, :created_at, :has_individual_tax_id, :has_business_tax_id ) end it "returns the correct field values" do info = props[:alive_user_compliance_info] expect(info[:first_name]).to eq(compliance_info.first_name) expect(info[:last_name]).to eq(compliance_info.last_name) expect(info[:is_business]).to eq(compliance_info.is_business) expect(info[:state_code]).to eq(compliance_info.state_code) expect(info[:country_code]).to eq(compliance_info.country_code) expect(info[:business_state_code]).to eq(compliance_info.business_state_code) expect(info[:business_country_code]).to eq(compliance_info.business_country_code) expect(info[:has_individual_tax_id]).to eq(compliance_info.has_individual_tax_id) expect(info[:has_business_tax_id]).to eq(compliance_info.has_business_tax_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/presenters/admin/product_presenter/card_spec.rb
spec/presenters/admin/product_presenter/card_spec.rb
# frozen_string_literal: true require "spec_helper" describe Admin::ProductPresenter::Card do describe "#props" do let(:admin_user) { create(:user) } let(:user) { create(:named_user) } let(:product) { create(:product, user:) } let(:pundit_user) { SellerContext.new(user: admin_user, seller: admin_user) } let(:presenter) { described_class.new(product:, pundit_user:) } subject(:props) { presenter.props } describe "fields" do it "returns the correct values" do expect(props.except(:cover_placeholder_url)).to eq( external_id: product.external_id, name: product.name, long_url: product.long_url, price_cents: product.price_cents, currency_code: product.price_currency_type, unique_permalink: product.unique_permalink, preview_url: product.preview_url, price_formatted: product.price_formatted, created_at: product.created_at, user: { id: product.user_id, name: product.user.name, suspended: false, flagged_for_tos_violation: false }, admins_can_generate_url_redirects: product.admins_can_generate_url_redirects, alive_product_files: [], html_safe_description: product.html_safe_description, alive: product.alive?, is_adult: product.is_adult?, active_integrations: [], admins_can_mark_as_staff_picked: false, admins_can_unmark_as_staff_picked: false, is_tiered_membership: product.is_tiered_membership?, comments_count: product.comments.size, updated_at: product.updated_at, deleted_at: product.deleted_at ) expect(props[:cover_placeholder_url]).to match(/cover_placeholder.*\.png/) end end describe "alive_product_files" do let!(:product_file1) { create(:product_file, link: product, position: 1) } let!(:product_file2) { create(:product_file, link: product, position: 2) } it "returns formatted product files" do expect(props[:alive_product_files].size).to eq(2) expect(props[:alive_product_files].first).to include( external_id: product_file1.external_id, s3_filename: product_file1.s3_filename ) expect(props[:alive_product_files].second).to include( external_id: product_file2.external_id, s3_filename: product_file2.s3_filename ) end it "returns files in the correct order" do expect(props[:alive_product_files].map { |f| f[:external_id] }).to eq([product_file1.external_id, product_file2.external_id]) end context "when product has deleted files" do let!(:deleted_file) { create(:product_file, link: product, position: 3, deleted_at: 1.day.ago) } it "excludes deleted files" do expect(props[:alive_product_files].size).to eq(2) expect(props[:alive_product_files].map { |f| f[:external_id] }).not_to include(deleted_file.external_id) end end end describe "active_integrations" do context "when product has no integrations" do it "returns an empty array" do expect(props[:active_integrations]).to eq([]) end end context "when product has integrations" do let(:product) { create(:product_with_discord_integration, user:) } it "returns formatted integrations" do expect(props[:active_integrations].size).to eq(1) expect(props[:active_integrations].first[:type]).to eq("DiscordIntegration") end end end describe "product states" do context "when product is alive" do it "returns alive as true" do expect(props[:alive]).to be(true) end end context "when product is deleted" do before do product.mark_deleted! end it "returns alive as false" do expect(props[:alive]).to be(false) end it "sets deleted_at" do expect(props[:deleted_at]).not_to be_nil end end context "when product is adult" do before do product.update!(is_adult: true) end it "returns is_adult as true" do expect(props[:is_adult]).to be(true) end end context "when product is tiered membership" do let(:product) { create(:membership_product_with_preset_tiered_pricing) } it "returns is_tiered_membership as true" do expect(props[:is_tiered_membership]).to be(true) end end end describe "description handling" do context "when product has description with links" do let(:product) { create(:product, user:, description: "Check out http://example.com") } it "returns html safe description with proper link attributes" do expect(props[:html_safe_description]).to include('target="_blank"') expect(props[:html_safe_description]).to include('rel="noopener noreferrer nofollow"') end end context "when product has no description" do let(:product) { create(:product, user:, description: nil) } it "returns nil" do expect(props[:html_safe_description]).to be_nil end end end describe "url redirect generation capability" do context "when product has alive product files" do let!(:product_file) { create(:product_file, link: product) } it "returns admins_can_generate_url_redirects as true" do expect(props[:admins_can_generate_url_redirects]).to be(true) end end context "when product has no alive product files" do it "returns admins_can_generate_url_redirects as false" do expect(props[:admins_can_generate_url_redirects]).to be(false) end end end describe "user object" do it "includes all required user fields" do expect(props[:user]).to include( :id, :name, :suspended, :flagged_for_tos_violation ) end it "returns correct user values" do expect(props[:user][:id]).to eq(product.user_id) expect(props[:user][:name]).to eq(product.user.name) expect(props[:user][:suspended]).to eq(false) expect(props[:user][:flagged_for_tos_violation]).to eq(false) end context "when user is suspended" do let(:user) { create(:named_user, :suspended) } it "returns suspended as true" do expect(props[:user][:suspended]).to be(true) end end context "when user is flagged for TOS violation" do let(:user) { create(:named_user, :flagged_for_tos_violation) } it "returns flagged_for_tos_violation as true" do expect(props[:user][:flagged_for_tos_violation]).to be(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/presenters/admin/product_presenter/multiple_matches_spec.rb
spec/presenters/admin/product_presenter/multiple_matches_spec.rb
# frozen_string_literal: true require "spec_helper" describe Admin::ProductPresenter::MultipleMatches do describe "#props" do let(:user) { create(:user, name: "Test User") } let(:product) { create(:product, user:, name: "Test Product") } let(:presenter) { described_class.new(product:) } subject(:props) { presenter.props } describe "basic structure" do it "returns a hash with all expected keys" do expect(props).to include( :external_id, :name, :created_at, :long_url, :price_formatted, :user ) end end describe "fields" do it "returns the correct field values" do expect(props[:external_id]).to eq(product.external_id) expect(props[:name]).to eq(product.name) expect(props[:created_at]).to eq(product.created_at) expect(props[:long_url]).to eq(product.long_url) expect(props[:price_formatted]).to eq(product.price_formatted) end end describe "user association" do it "returns user information" do expect(props[:user]).to eq( id: user.id, name: user.name ) end it "returns the correct user id and name" do expect(props[:user][:id]).to eq(user.id) expect(props[:user][:name]).to eq("Test User") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/invoice_presenter/seller_info_spec.rb
spec/presenters/invoice_presenter/seller_info_spec.rb
# frozen_string_literal: true describe InvoicePresenter::SellerInfo do let(:seller) { create(:named_seller, support_email: "seller-support@example.com") } let(:product) { create(:product, user: seller) } let(:purchase) do create( :purchase, email: "customer@example.com", link: product, seller:, price_cents: 14_99, created_at: DateTime.parse("January 1, 2023"), was_purchase_taxable: true, gumroad_tax_cents: 100, ) end RSpec.shared_examples "chargeable" do describe "#heading" do subject(:presenter) { described_class.new(chargeable) } it "returns the seller heading" do expect(presenter.heading).to eq("Creator") end end describe "#attributes" do subject(:presenter) { described_class.new(chargeable) } it "returns seller attributes" do expect(presenter.attributes).to eq( [ { label: nil, value: seller.display_name, link: seller.subdomain_with_protocol }, { label: "Email", value: seller.support_or_form_email } ] ) end end end describe "for Purchase" do let(:chargeable) { purchase } it_behaves_like "chargeable" end describe "for Charge", :vcr do let(:charge) { create(:charge, seller:, purchases: [purchase]) } let!(:order) { charge.order } let(:chargeable) { charge } before do order.purchases << purchase order.update!(created_at: DateTime.parse("January 1, 2023")) end it_behaves_like "chargeable" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/invoice_presenter/form_info_spec.rb
spec/presenters/invoice_presenter/form_info_spec.rb
# frozen_string_literal: true describe InvoicePresenter::FormInfo do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:purchase) do create( :purchase, link: product, seller:, price_cents: 1_499, created_at: DateTime.parse("January 1, 2023") ) end let!(:purchase_sales_tax_info) do purchase.create_purchase_sales_tax_info!( country_code: Compliance::Countries::USA.alpha2 ) end let(:presenter) { described_class.new(chargeable) } RSpec.shared_examples "chargeable" do describe "#heading" do context "when is not direct to australian customer" do it "returns Generate invoice" do expect(presenter.heading).to eq("Generate invoice") end end context "when is direct to australian customer" do it "returns Generate receipt" do allow(chargeable).to receive(:is_direct_to_australian_customer?).and_return(true) expect(presenter.heading).to eq("Generate receipt") end end end describe "#display_vat_id?" do context "without gumroad tax" do it "returns false" do expect(presenter.display_vat_id?).to eq(false) end end context "with gumroad tax" do before do purchase.update!(gumroad_tax_cents: 100, was_purchase_taxable: true) end context "when business_vat_id has been previously provided" do before do purchase.purchase_sales_tax_info.update!(business_vat_id: "123") end it "returns false" do expect(presenter.display_vat_id?).to eq(false) end end context "when business_vat_id is missing" do it "returns true" do expect(presenter.display_vat_id?).to eq(true) end end end end describe "#vat_id_label" do before do purchase.update!(was_purchase_taxable: true, gumroad_tax_cents: 100) end context "when country is Australia" do before do purchase_sales_tax_info.update!(country_code: Compliance::Countries::AUS.alpha2) end it "returns ABN" do expect(presenter.vat_id_label).to eq("Business ABN ID (Optional)") end end context "when country is Singapore" do before do purchase_sales_tax_info.update!(country_code: Compliance::Countries::SGP.alpha2) end it "returns GST" do expect(presenter.vat_id_label).to eq("Business GST ID (Optional)") end end context "when country is Norway" do before do purchase_sales_tax_info.update!(country_code: Compliance::Countries::NOR.alpha2) end it "returns MVA" do expect(presenter.vat_id_label).to eq("Norway MVA ID (Optional)") end end context "when country is something else" do it "returns VAT" do expect(presenter.vat_id_label).to eq("Business VAT ID (Optional)") end end end describe "#data" do let(:product) { create(:physical_product, user: seller) } let(:address_fields) do { full_name: "Customer Name", street_address: "1234 Main St", city: "City", state: "State", zip_code: "12345", country: "United States" } end let(:purchase) do create( :purchase, link: product, seller:, **address_fields ) end it "returns form data" do form_data = presenter.data address_fields.except(:country).each do |key, value| expect(form_data[key]).to eq(value) end expect(form_data[:country_iso2]).to eq("US") end end end describe "for Purchase" do let(:chargeable) { purchase } it_behaves_like "chargeable" end describe "for Charge", :vcr do let(:charge) { create(:charge, purchases: [purchase]) } let(:chargeable) { charge } it_behaves_like "chargeable" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/invoice_presenter/supplier_info_spec.rb
spec/presenters/invoice_presenter/supplier_info_spec.rb
# frozen_string_literal: true describe InvoicePresenter::SupplierInfo do let(:seller) { create(:named_seller, support_email: "seller-support@example.com") } let(:product) { create(:product, user: seller) } let(:purchase) do create( :purchase, email: "customer@example.com", link: product, seller:, price_cents: 14_99, created_at: DateTime.parse("January 1, 2023"), was_purchase_taxable: true, gumroad_tax_cents: 100, ) end let(:address_fields) do { full_name: "Customer Name", street_address: "1234 Main St", city: "City", state: "State", zip_code: "12345", country: "United States" } end let(:additional_notes) { "Here is the note!\nIt has multiple lines." } let(:business_vat_id) { "VAT12345" } let!(:purchase_sales_tax_info) do purchase.create_purchase_sales_tax_info!( country_code: Compliance::Countries::USA.alpha2 ) end let(:presenter) { described_class.new(chargeable) } RSpec.shared_examples "chargeable" do describe "#heading" do it "returns Supplier" do expect(presenter.heading).to eq("Supplier") end end describe "#attributes" do context "when is not supplied by the seller" do it "returns Gumroad attributes including the Gumroad note attribute" do expect(presenter.attributes).to eq( [ { label: nil, value: "Gumroad, Inc.", }, { label: "Office address", value: "548 Market St\nSan Francisco, CA 94104-5401\nUnited States", }, { label: "Email", value: ApplicationMailer::NOREPLY_EMAIL, }, { label: "Web", value: ROOT_DOMAIN, }, { label: nil, value: "Products supplied by Gumroad.", } ] ) end describe "Gumroad tax information" do context "with physical product purchase" do let(:product) { create(:physical_product, user: seller) } let(:purchase) do create( :purchase, email: "customer@example.com", link: product, seller:, created_at: DateTime.parse("January 1, 2023"), was_purchase_taxable: true, gumroad_tax_cents: 100, **address_fields ) end context "when country is outside of EU and Australia" do before { purchase.update!(country: "United States") } it "returns nil" do expect(presenter.send(:gumroad_tax_attributes)).to be_nil end end context "when country is in EU" do before { purchase.update!(country: "Italy") } it "returns VAT information" do expect(presenter.send(:gumroad_tax_attributes)).to eq([ { label: "VAT Registration Number", value: GUMROAD_VAT_REGISTRATION_NUMBER } ]) end end context "when country is Australia" do before { purchase.update!(country: "Australia") } it "returns ABN information" do expect(presenter.send(:gumroad_tax_attributes)).to eq([ { label: "Australian Business Number", value: GUMROAD_AUSTRALIAN_BUSINESS_NUMBER } ]) end end context "when country is Canada" do before { purchase.update!(country: "Canada") } it "returns GST and QST information" do expect(presenter.send(:gumroad_tax_attributes)).to eq([ { label: "Canada GST Registration Number", value: GUMROAD_CANADA_GST_REGISTRATION_NUMBER }, { label: "QST Registration Number", value: GUMROAD_QST_REGISTRATION_NUMBER } ]) end end context "when country is Norway" do before { purchase.update!(country: "Norway") } it "returns MVA information" do expect(presenter.send(:gumroad_tax_attributes)).to eq([ { label: "Norway VAT Registration", value: GUMROAD_NORWAY_VAT_REGISTRATION } ]) end end end context "when ip_country is in EU" do before { purchase.update!(ip_country: "Italy") } it "returns VAT information" do expect(presenter.send(:gumroad_tax_attributes)).to eq([ { label: "VAT Registration Number", value: GUMROAD_VAT_REGISTRATION_NUMBER } ]) end end context "when ip_country is Australia" do before do purchase.update!( country: nil, ip_country: "Australia" ) end it "returns ABN information" do expect(presenter.send(:gumroad_tax_attributes)).to eq([ { label: "Australian Business Number", value: GUMROAD_AUSTRALIAN_BUSINESS_NUMBER } ]) end end context "when ip_country is one of the countries that collect tax on all products" do before { purchase.update!(country: nil, ip_country: "Iceland") } it "returns VAT Registration Number Information" do expect(presenter.send(:gumroad_tax_attributes)).to eq([ { label: "VAT Registration Number", value: GUMROAD_OTHER_TAX_REGISTRATION } ]) end end context "when ip_country is one of the countries that collect tax on digital products" do before { purchase.update!(country: nil, ip_country: "Chile") } it "returns VAT Registration Number Information" do expect(presenter.send(:gumroad_tax_attributes)).to eq([ { label: "VAT Registration Number", value: GUMROAD_OTHER_TAX_REGISTRATION } ]) end end end end end end describe "for Purchase" do let(:chargeable) { purchase } it_behaves_like "chargeable" end describe "for Charge", :vcr do let(:charge) { create(:charge, seller:, purchases: [purchase]) } let!(:order) { charge.order } let(:chargeable) { charge } before do order.purchases << purchase order.update!(created_at: DateTime.parse("January 1, 2023")) end it_behaves_like "chargeable" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/invoice_presenter/order_info_spec.rb
spec/presenters/invoice_presenter/order_info_spec.rb
# frozen_string_literal: true describe InvoicePresenter::OrderInfo do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:purchase) do create( :purchase, email: "customer@example.com", link: product, seller:, price_cents: 14_99, created_at: DateTime.parse("January 1, 2023") ) end let(:address_fields) do { full_name: "Customer Name", street_address: "1234 Main St", city: "City", state: "State", zip_code: "12345", country: "United States" } end let(:additional_notes) { "Here is the note!\nIt has multiple lines." } let(:business_vat_id) { "VAT12345" } let!(:purchase_sales_tax_info) do purchase.create_purchase_sales_tax_info!( country_code: Compliance::Countries::USA.alpha2 ) end let(:presenter) { described_class.new(chargeable, address_fields:, additional_notes:, business_vat_id:) } RSpec.shared_examples "chargeable" do describe "#heading" do context "when is not direct to australian customer" do it "returns Invoice" do expect(presenter.heading).to eq("Invoice") end end context "when is direct to australian customer" do it "returns Receipt" do allow(chargeable).to receive(:is_direct_to_australian_customer?).and_return(true) expect(presenter.heading).to eq("Receipt") end end end describe "#pdf_attributes" do before do purchase.update!(was_purchase_taxable: true, tax_cents: 100) end it "returns an Array of attributes" do expect(presenter.pdf_attributes).to eq( [ { label: "Date", value: "Jan 1, 2023", }, { label: "Order number", value: purchase.external_id_numeric.to_s, }, { label: "To", value: "Customer Name<br>1234 Main St<br>City, State, 12345<br>United States" }, { label: "Additional notes", value: "<p>Here is the note!\n<br />It has multiple lines.</p>", }, { label: "VAT ID", value: "VAT12345", }, { label: nil, value: "Reverse Charge - You are required to account for the VAT", }, { label: "Email", value: "customer@example.com", }, { label: "Item purchased", value: nil, }, { label: "The Works of Edgar Gumstein", value: "$14.99", }, { label: "Sales tax (included)", value: "$1", }, { label: "Payment Total", value: "$14.99", }, { label: "Payment method", value: "VISA *4062", } ] ) end context "when country is Australia" do before do purchase.update!(gumroad_tax_cents: 100, was_purchase_taxable: true) purchase_sales_tax_info.update!(country_code: Compliance::Countries::AUS.alpha2) end it "returns correct business VAT ID label" do expect(presenter.pdf_attributes).to include( { label: "ABN ID", value: "VAT12345", } ) end end context "when country is Singapore" do before do purchase.update!(gumroad_tax_cents: 100, was_purchase_taxable: true) purchase_sales_tax_info.update!(country_code: Compliance::Countries::SGP.alpha2) end it "returns correct business VAT ID label" do expect(presenter.pdf_attributes).to include( { label: "GST ID", value: "VAT12345", } ) end end end describe "#form_attributes" do # Keyword arguments are not passed for the form page let(:presenter) { described_class.new(chargeable, address_fields: nil, additional_notes: nil, business_vat_id: nil) } it "returns an Array of attributes" do expect(presenter.form_attributes).to eq( [ { label: "Email", value: "customer@example.com", }, { label: "Item purchased", value: nil, }, { label: "The Works of Edgar Gumstein", value: "$14.99", }, { label: "Payment Total", value: "$14.99", }, { label: "Payment method", value: "VISA *4062", } ] ) end context "with business_vat_id already provided" do before do purchase.update!(gumroad_tax_cents: 100, was_purchase_taxable: true) purchase_sales_tax_info.update!(business_vat_id:) end it "includes VAT ID attributes" do expect(presenter.form_attributes).to include( { label: "VAT ID", value: business_vat_id } ) expect(presenter.form_attributes).to include( { label: nil, value: "Reverse Charge - You are required to account for the VAT" } ) end end end end describe "for Purchase" do let(:chargeable) { purchase } it_behaves_like "chargeable" end describe "for Charge" do let(:charge) { create(:charge, purchases: [purchase]) } let!(:order) { charge.order } let(:chargeable) { charge } before do order.purchases << purchase order.update!(created_at: DateTime.parse("January 1, 2023")) end it_behaves_like "chargeable" context "when the charge has a second purchase" do let(:second_purchase) do create( :purchase, email: "customer@example.com", link: create(:product, name: "Second Product", user: seller), seller:, displayed_price_cents: 9_99, was_purchase_taxable: true, tax_cents: 60, created_at: DateTime.parse("January 1, 2023") ) end before do purchase.update!(was_purchase_taxable: true, tax_cents: 100) charge.purchases << second_purchase order.purchases << second_purchase end it "sums the tax" do expect(presenter.pdf_attributes).to include( { label: "Sales tax (included)", value: "$1.60", } ) end it "includes second purchase product" do expect(presenter.pdf_attributes).to include( { label: "Second Product", value: "$9.99", } ) end context "with Gumroad tax", :vcr do let(:zip_tax_rate) { create(:zip_tax_rate, combined_rate: 0.20, is_seller_responsible: false) } let(:valid_bussiness_vat_id) { "51824753556" } let(:purchase) { create(:purchase_in_progress, zip_tax_rate:, chargeable: create(:chargeable)) } let(:second_purchase) { create(:purchase_in_progress, zip_tax_rate:, chargeable: create(:chargeable)) } let(:purchase_sales_tax_info) { PurchaseSalesTaxInfo.new(country_code: Compliance::Countries::AUS.alpha2) } let(:presenter) { described_class.new(chargeable, address_fields:, additional_notes:, business_vat_id: valid_bussiness_vat_id) } before do purchase.process! purchase.mark_successful! purchase.update!( gumroad_tax_cents: 50, purchase_sales_tax_info: ) second_purchase.process! second_purchase.mark_successful! second_purchase.update!( gumroad_tax_cents: 100, purchase_sales_tax_info: ) end context "when the tax was not refunded" do it "includes the tax" do expect(presenter.pdf_attributes).to include( { label: "Sales tax (included)", value: "$1.50", } ) end end context "when the tax was refunded" do before do purchase.refund_gumroad_taxes!(refunding_user_id: 1, business_vat_id: valid_bussiness_vat_id) second_purchase.refund_gumroad_taxes!(refunding_user_id: 1, business_vat_id: valid_bussiness_vat_id) end it "subtracts the refunded amounts" do expect(presenter.pdf_attributes).not_to include(label: "Sales tax (included)") 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/presenters/checkout/discounts_presenter_spec.rb
spec/presenters/checkout/discounts_presenter_spec.rb
# frozen_string_literal: true describe Checkout::DiscountsPresenter do include CurrencyHelper let(:seller) { create(:named_seller) } let(:product1) { create(:product, user: seller, price_cents: 1000, price_currency_type: Currency::EUR) } let(:product2) { create(:product, user: seller, price_cents: 500) } let!(:product3) { create(:membership_product_with_preset_tiered_pricing, user: seller) } let!(:offer_code1) { create(:percentage_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}"), minimum_quantity: 1, duration_in_billing_cycles: 1, minimum_amount_cents: 1000) } 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) } let(:user) { create(:user) } let(:presenter) { described_class.new(pundit_user: SellerContext.new(user:, seller:), offer_codes: [offer_code1, offer_code2, offer_code3], pagination: nil) } describe "#discounts_props" do before do create(:product, user: seller, deleted_at: Time.current) create_list(:purchase, 10, link: product1, offer_code: offer_code1, displayed_price_currency_type: Currency::EUR, price_cents: get_usd_cents(Currency::EUR, product1.price_cents)) create_list(:purchase, 5, 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 the correct props" do create(:team_membership, user:, seller:, role: TeamMembership::ROLE_ADMIN) expect(presenter.discounts_props) .to eq({ pages: ["discounts", "form", "upsells"], pagination: nil, offer_codes: [ { can_update: true, discount: { type: "percent", value: 50 }, code: "code1", currency_type: "usd", id: offer_code1.external_id, name: "Discount 1", valid_at: offer_code1.valid_at, expires_at: offer_code1.expires_at, limit: 12, minimum_quantity: 1, duration_in_billing_cycles: 1, minimum_amount_cents: 1000, products: [ { id: product1.external_id, name: "The Works of Edgar Gumstein", archived: false, currency_type: "eur", url: product1.long_url, is_tiered_membership: false, }, { id: product2.external_id, name: "The Works of Edgar Gumstein", archived: false, currency_type: "usd", url: product2.long_url, is_tiered_membership: false, }, ], }, { can_update: true, discount: { type: "cents", value: 200 }, code: "code2", currency_type: "usd", id: offer_code2.external_id, name: "Discount 2", valid_at: offer_code2.valid_at, expires_at: nil, limit: 20, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, products: [ { id: product2.external_id, name: "The Works of Edgar Gumstein", archived: false, currency_type: "usd", url: product2.long_url, is_tiered_membership: false, }, ], }, { can_update: true, discount: { type: "percent", value: 50 }, code: "code3", currency_type: "usd", id: offer_code3.external_id, name: "Discount 3", valid_at: nil, expires_at: nil, limit: nil, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, products: nil, }, ], products: [ { id: product3.external_id, name: "The Works of Edgar Gumstein", archived: false, currency_type: "usd", url: product3.long_url, is_tiered_membership: true, }, { id: product1.external_id, name: "The Works of Edgar Gumstein", archived: false, currency_type: "eur", url: product1.long_url, is_tiered_membership: false, }, { id: product2.external_id, name: "The Works of Edgar Gumstein", archived: false, currency_type: "usd", url: product2.long_url, is_tiered_membership: false, }, ], show_black_friday_banner: false, black_friday_code: "BLACKFRIDAY2025", black_friday_code_name: "Black Friday 2025", }) end end describe "#offer_code_props" do context "with user as admin for owner" do before do create(:team_membership, user:, seller:, role: TeamMembership::ROLE_ADMIN) end it "returns the correct props" do expect(presenter.offer_code_props(offer_code1)).to eq( { can_update: true, discount: { type: "percent", value: 50 }, code: "code1", currency_type: "usd", id: offer_code1.external_id, name: "Discount 1", valid_at: offer_code1.valid_at, expires_at: offer_code1.expires_at, limit: 12, minimum_quantity: 1, duration_in_billing_cycles: 1, minimum_amount_cents: 1000, products: [ { id: product1.external_id, name: "The Works of Edgar Gumstein", archived: false, currency_type: "eur", url: product1.long_url, is_tiered_membership: false, }, { id: product2.external_id, name: "The Works of Edgar Gumstein", archived: false, currency_type: "usd", url: product2.long_url, is_tiered_membership: false, }, ], } ) end end [TeamMembership::ROLE_ADMIN, TeamMembership::ROLE_MARKETING].each do |role| context "with user as #{role} for owner" do before do create(:team_membership, user:, seller:, role:) end it "returns correct props" do expect(presenter.offer_code_props(offer_code1)[:can_update]).to eq(true) end end end [TeamMembership::ROLE_ACCOUNTANT, TeamMembership::ROLE_SUPPORT].each do |role| context "with user as #{role} for owner" do before do create(:team_membership, user:, seller:, role:) end it "returns correct props" do expect(presenter.offer_code_props(offer_code1)[:can_update]).to eq(false) end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/checkout/upsells_presenter_spec.rb
spec/presenters/checkout/upsells_presenter_spec.rb
# frozen_string_literal: true describe Checkout::UpsellsPresenter do describe "#upsells_props" do let(:seller) { create(:named_seller) } let(:product1) { create(:product_with_digital_versions, user: seller, price_cents: 1000) } let(:product2) { create(:product_with_digital_versions, user: seller, price_cents: 500) } let!(:upsell1) { create(:upsell, product: product1, variant: product1.alive_variants.second, name: "Upsell 1", seller:, cross_sell: true, replace_selected_products: true) } let!(:upsell2) { create(:upsell, product: product2, offer_code: create(:offer_code, products: [product2], user: seller), name: "Upsell 2", seller:) } let!(:upsell2_variant) { create(:upsell_variant, upsell: upsell2, selected_variant: product2.alive_variants.first, offered_variant: product2.alive_variants.second) } let(:presenter) { described_class.new(pundit_user: SellerContext.new(user: seller, seller:), upsells: seller.upsells.order(updated_at: :desc), pagination: nil) } let(:checkout_presenter) { CheckoutPresenter.new(logged_in_user: seller, ip: nil) } before do create(:product, user: seller, deleted_at: Time.current) build_list :product, 5 do |product, i| product.name = "Product #{i}" create_list(:upsell_purchase, 2, upsell: upsell1, selected_product: product) upsell1.selected_products << product end create_list(:upsell_purchase, 20, upsell: upsell2, selected_product: product2, upsell_variant: upsell2_variant) end it "returns the correct props" do expect(presenter.upsells_props) .to eq({ pages: ["discounts", "form", "upsells"], pagination: nil, upsells: [ { description: "This offer will only last for a few weeks.", id: upsell2.external_id, name: "Upsell 2", text: "Take advantage of this excellent offer!", cross_sell: false, replace_selected_products: false, universal: false, paused: false, discount: { cents: 100, product_ids: [product2.external_id], type: "fixed", expires_at: nil, minimum_quantity: nil, duration_in_billing_cycles: nil, minimum_amount_cents: nil, }, product: { id: product2.external_id, currency_type: "usd", name: "The Works of Edgar Gumstein", variant: nil, }, selected_products: [], upsell_variants: [{ id: upsell2_variant.external_id, selected_variant: { id: upsell2_variant.selected_variant.external_id, name: upsell2_variant.selected_variant.name, }, offered_variant: { id: upsell2_variant.offered_variant.external_id, name: upsell2_variant.offered_variant.name }, }], }, { description: "This offer will only last for a few weeks.", id: upsell1.external_id, name: "Upsell 1", text: "Take advantage of this excellent offer!", cross_sell: true, replace_selected_products: true, universal: false, paused: false, discount: nil, product: { id: product1.external_id, currency_type: "usd", name: "The Works of Edgar Gumstein", variant: { id: product1.alive_variants.second.external_id, name: "Untitled 2", }, }, selected_products: [ { id: upsell1.selected_products[0].external_id, name: "Product 0" }, { id: upsell1.selected_products[1].external_id, name: "Product 1" }, { id: upsell1.selected_products[2].external_id, name: "Product 2" }, { id: upsell1.selected_products[3].external_id, name: "Product 3" }, { id: upsell1.selected_products[4].external_id, name: "Product 4" }, ], upsell_variants: [], }, ], products: [ { id: product1.external_id, name: product1.name, has_multiple_versions: true, native_type: product1.native_type }, { id: product2.external_id, name: product2.name, has_multiple_versions: true, native_type: product2.native_type } ] }) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/checkout/form_presenter_spec.rb
spec/presenters/checkout/form_presenter_spec.rb
# frozen_string_literal: true describe Checkout::FormPresenter do describe "#form_props" do let(:seller) { create(:named_seller) } let(:user) { create(:user) } let(:presenter) { described_class.new(pundit_user: SellerContext.new(user:, seller:)) } before do create(:team_membership, user:, seller:, role: TeamMembership::ROLE_ADMIN) end it "returns the correct props" do expect(presenter.form_props) .to eq( { pages: ["discounts", "form", "upsells"], user: { display_offer_code_field: false, recommendation_type: User::RecommendationType::OWN_PRODUCTS, tipping_enabled: false, }, cart_item: nil, card_product: nil, custom_fields: [], products: [], } ) end context "when tipping is enabled for the user" do before do seller.update!(tipping_enabled: true) end it "returns true for tipping_enabled" do expect(presenter.form_props[:user][:tipping_enabled]).to eq(true) end end context "when the seller has the offer code field enabled" do before do seller.update!(display_offer_code_field: true) end it "returns the correct props" do expect(presenter.form_props[:user][:display_offer_code_field]).to eq(true) end end context "when the seller has an alive product" do let!(:product) { create(:product, user: seller) } it "includes it as a cart item, card product, and in the list of products" do props = presenter.form_props expect(props[:cart_item]).to eq(CheckoutPresenter.new(logged_in_user: nil, ip: nil).checkout_product(product, product.cart_item({}), {}).merge({ quantity: 1, url_parameters: {}, referrer: "" })) expect(props[:card_product]).to eq(ProductPresenter.card_for_web(product:)) expect(props[:products]).to eq [{ id: product.external_id, name: product.name, archived: false }] end end context "when the seller has custom fields" do it "returns the correct props" do product = create(:product) field = create(:custom_field, seller:, products: [product]) other_product = create(:product, user: seller, json_data: { custom_fields: [{ type: "text", name: "Field", required: true }] }) other_field = create(:custom_field, seller:, products: [other_product]) create(:custom_field, seller:, is_post_purchase: true) expect(presenter.form_props[:custom_fields]).to eq [ { id: field.external_id, name: field.name, global: false, required: false, collect_per_product: false, type: field.type, products: [product.external_id] }, { id: other_field.external_id, name: other_field.name, global: false, required: false, collect_per_product: false, type: other_field.type, products: [other_product.external_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/presenters/checkout/upsells/product_presenter_spec.rb
spec/presenters/checkout/upsells/product_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe Checkout::Upsells::ProductPresenter do let!(:product) do create( :product, name: "Test Product", price_cents: 1000, native_type: "ebook" ) end let(:presenter) { described_class.new(product) } before do create(:purchase, :with_review, link: product) end describe "#product_props" do it "returns product properties hash" do expect(presenter.product_props).to eq( id: product.external_id, permalink: product.unique_permalink, name: "Test Product", price_cents: 1000, currency_code: "usd", review_count: 1, average_rating: 5.0, native_type: "ebook", options: [] ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/discover/canonical_url_presenter_spec.rb
spec/presenters/discover/canonical_url_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe Discover::CanonicalUrlPresenter do let(:discover_domain_with_protocol) { UrlService.discover_domain_with_protocol } describe "#canonical_url" do it "returns the root url when no valid search parameters are present" do params = ActionController::Parameters.new({}) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/") params = ActionController::Parameters.new({ sort: "hot_and_new" }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/") params = ActionController::Parameters.new({ max_price: 0 }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/") end it "returns the url with parameters" do params = ActionController::Parameters.new({ query: "product" }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/?query=product") params = ActionController::Parameters.new({ taxonomy: "3d/3d-modeling" }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/3d/3d-modeling") params = ActionController::Parameters.new({ taxonomy: "3d/3d-modeling", query: "product" }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/3d/3d-modeling?query=product") params = ActionController::Parameters.new({ tags: ["3d model"] }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/?tags=3d+model") end it "returns the url with sorted parameters and values" do params = ActionController::Parameters.new({ rating: 1, query: "product", sort: "featured" }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/?query=product&rating=1&sort=featured") params = ActionController::Parameters.new({ max_price: 1, tags: ["tagb", "taga"], sort: "hot_and_new" }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/?max_price=1&sort=hot_and_new&tags=taga%2Ctagb") params = ActionController::Parameters.new({ max_price: 1, tags: ["taga", "tagb"], sort: "hot_and_new" }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/?max_price=1&sort=hot_and_new&tags=taga%2Ctagb") end it "ignores empty parameters" do params = ActionController::Parameters.new({ query: "product", max_price: 0, tags: [], sort: "" }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/?max_price=0&query=product") end it "ignores invalid parameters" do params = ActionController::Parameters.new({ query: "product", invalid: "invalid", unknown: "unknown" }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/?query=product") end it "correctly formats array parameters" do params = ActionController::Parameters.new({ tags: ["tag1", "tag2"], filetypes: ["mp3", "zip"] }) expect(described_class.canonical_url(params)).to eq("#{discover_domain_with_protocol}/?filetypes=mp3%2Czip&tags=tag1%2Ctag2") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/discover/autocomplete_presenter_spec.rb
spec/presenters/discover/autocomplete_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe Discover::AutocompletePresenter do let(:user) { create(:user) } let(:browser_guid) { SecureRandom.uuid } let(:query) { "test" } let(:presenter) { described_class.new(query:, user:, browser_guid:) } let!(:product) { create(:product, :recommendable, name: "Test Product") } before do Link.import(force: true, refresh: true) end describe "#props" do context "when query is blank" do let(:query) { "" } let!(:product2) { create(:product, :recommendable, name: "Another Test Product") } let!(:product3) { create(:product, :recommendable, name: "Yet Another Test Product") } before do Link.import(force: true, refresh: true) end it "returns top products and recent searches" do create(:discover_search_suggestion, discover_search: create(:discover_search, user:, browser_guid:, query: "test", created_at: 1.day.ago)) create_list(:discover_search_suggestion, 3, discover_search: create(:discover_search, user:, browser_guid:, query: "recent search")) result = presenter.props expect(result[:products]).to contain_exactly( { name: "Test Product", url: a_string_matching(/\/#{product.unique_permalink}\?autocomplete=true&layout=discover&recommended_by=search/), seller_name: "gumbo", thumbnail_url: nil, }, { name: "Another Test Product", url: a_string_matching(/\/#{product2.unique_permalink}\?autocomplete=true&layout=discover&recommended_by=search/), seller_name: "gumbo", thumbnail_url: nil, }, { name: "Yet Another Test Product", url: a_string_matching(/\/#{product3.unique_permalink}\?autocomplete=true&layout=discover&recommended_by=search/), seller_name: "gumbo", thumbnail_url: nil, }, ) expect(result[:viewed]).to be(false) expect(result[:recent_searches]).to eq(["recent search", "test"]) end context "when the user has viewed products" do before do add_page_view(product, Time.current, user_id: user.id) ProductPageView.__elasticsearch__.refresh_index! end it "returns recently viewed products" do result = presenter.props expect(result[:products]).to contain_exactly( { name: "Test Product", url: a_string_matching(/\/#{product.unique_permalink}\?autocomplete=true&layout=discover&recommended_by=search/), seller_name: "gumbo", thumbnail_url: nil, }, ) expect(result[:viewed]).to be(true) end end context "when not logged in but has viewed products in this browser" do before do add_page_view(product2, Time.current, browser_guid:) ProductPageView.__elasticsearch__.refresh_index! end it "returns recently viewed products" do result = described_class.new(query:, user: nil, browser_guid:).props expect(result[:products]).to contain_exactly( { name: "Another Test Product", url: a_string_matching(/\/#{product2.unique_permalink}\?autocomplete=true&layout=discover&recommended_by=search/), seller_name: "gumbo", thumbnail_url: nil, }, ) expect(result[:viewed]).to be(true) end end end context "when query is present" do let(:query) { "test" } let!(:searches) do [ create(:discover_search_suggestion, discover_search: create(:discover_search, user:, browser_guid:, query: "test query", created_at: 1.day.ago)), create(:discover_search_suggestion, discover_search: create(:discover_search, user:, browser_guid:, query: "another test", created_at: 1.hour.ago)), create(:discover_search_suggestion, discover_search: create(:discover_search, user:, browser_guid:, query: "unrelated", created_at: 1.minute.ago)), ] end it "returns matching products and filtered recent searches" do result = presenter.props expect(result[:products].sole).to match( name: "Test Product", url: a_string_matching(/\/#{product.unique_permalink}\?autocomplete=true&layout=discover&query=test&recommended_by=search/), seller_name: "gumbo", thumbnail_url: nil, ) expect(result[:recent_searches]).to eq(["another test", "test query"]) end end context "when user is nil" do let(:user) { nil } let!(:thumbnail) { create(:thumbnail, product:) } it "returns matching products" do expect(presenter.props[:products].sole).to match( name: "Test Product", url: a_string_matching(/\/#{product.unique_permalink}\?autocomplete=true&layout=discover&query=test&recommended_by=search/), seller_name: "gumbo", thumbnail_url: thumbnail.url, ) end it "does not return recent searches" do create(:discover_search_suggestion, discover_search: create(:discover_search, user: nil, browser_guid:, query: "recent search")) expect(described_class.new(query:, user: nil, browser_guid:).props[:recent_searches]).to eq([]) end end it "finds searches by user when user is present" do create(:discover_search_suggestion, discover_search: create(:discover_search, user:, browser_guid:, query: "user search")) create(:discover_search_suggestion, discover_search: create(:discover_search, user: nil, browser_guid:, query: "browser search")) result = described_class.new(query: "", user:, browser_guid: nil).props expect(result[:recent_searches]).to eq(["user search"]) end it "finds searches by browser_guid when user is nil" do other_guid = SecureRandom.uuid create(:discover_search_suggestion, discover_search: create(:discover_search, user: nil, browser_guid:, query: "browser search")) create(:discover_search_suggestion, discover_search: create(:discover_search, user: nil, browser_guid: other_guid, query: "other search")) result = described_class.new(query: "", user: nil, browser_guid:).props expect(result[:recent_searches]).to eq(["browser search"]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/discover/tag_page_meta_presenter_spec.rb
spec/presenters/discover/tag_page_meta_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe Discover::TagPageMetaPresenter do describe "#title" do context "when one tag with specific title available is provided" do it "returns the specific title" do expect(described_class.new(["3d-models"], 1000).title).to eq("Professional 3D Modeling Assets") end end context "when one tag without specific title available is provided" do it "returns the default title" do expect(described_class.new(["tutorial"], 1000).title).to eq("tutorial") end end context "when multiple tags are provided" do it "returns the default title" do expect(described_class.new(["tag 1", "tag 2"], 1000).title).to eq("tag 1, tag 2") end end end describe "#meta_description" do context "when one tag with specific meta description available is provided" do it "returns the specific meta description" do expect(described_class.new(["3d models"], 1000).meta_description).to eq("Browse over 1,000 3D assets including" \ " 3D models, CG textures, HDRI environments & more for VFX, game development, AR/VR, architecture, and animation.") end end context "when one tag without specific meta description available is provided" do it "returns the default meta description" do expect(described_class.new(["tutorial"], 1000).meta_description).to eq("Browse over 1,000 unique tutorial" \ " products published by independent creators on Gumroad. Discover the best things to read, watch, create & more!") end end context "when multiple tags are provided" do it "returns the default meta description" do expect(described_class.new(["tag 1", "tag 2"], 1000).meta_description).to eq("Browse over 1,000 unique tag 1" \ " and tag 2 products published by independent creators on Gumroad. Discover the best things to read, watch," \ " create & more!") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/discover/taxonomy_presenter_spec.rb
spec/presenters/discover/taxonomy_presenter_spec.rb
# frozen_string_literal: true require "spec_helper" describe Discover::TaxonomyPresenter do subject(:presenter) { Discover::TaxonomyPresenter.new } describe "#taxonomies_for_nav" do it "converts the taxonomy into a list of categories, with keys as strings" do education_taxonomy = Taxonomy.find_by(slug: "education") math_taxonomy = Taxonomy.find_by(slug: "math", parent: education_taxonomy) history_taxonomy = Taxonomy.find_by(slug: "history", parent: education_taxonomy) three_d_taxonomy = Taxonomy.find_by(slug: "3d") assets_taxonomy = Taxonomy.find_by(slug: "3d-assets", parent: three_d_taxonomy) expect(presenter.taxonomies_for_nav).to include( { key: assets_taxonomy.id.to_s, slug: "3d-assets", label: "3D Assets", parent_key: three_d_taxonomy.id.to_s }, { key: three_d_taxonomy.id.to_s, slug: "3d", label: "3D", parent_key: nil }, { key: education_taxonomy.id.to_s, slug: "education", label: "Education", parent_key: nil }, { key: history_taxonomy.id.to_s, slug: "history", label: "History", parent_key: education_taxonomy.id.to_s }, { key: math_taxonomy.id.to_s, slug: "math", label: "Math", parent_key: education_taxonomy.id.to_s }, ) end it "returns 'other' taxonomy last" do expect(presenter.taxonomies_for_nav.last).to eq({ key: Taxonomy.find_by(slug: "other").id.to_s, slug: "other", label: "Other", parent_key: nil }) end context "when logged_in_user is present" do it "sorts taxonomies based on recommended products" do recommended_products = [ create(:product, taxonomy: Taxonomy.find_by_path(["education", "math"])), create(:product, taxonomy: Taxonomy.find_by_path(["3d", "3d-assets"])), create(:product, taxonomy: nil), ] expect(presenter.taxonomies_for_nav(recommended_products:).first(2)).to contain_exactly( { key: Taxonomy.find_by(slug: "3d").id.to_s, slug: "3d", label: "3D", parent_key: nil }, { key: Taxonomy.find_by(slug: "education").id.to_s, slug: "education", label: "Education", parent_key: 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/presenters/product_presenter/product_props_spec.rb
spec/presenters/product_presenter/product_props_spec.rb
# frozen_string_literal: true require "spec_helper" describe ProductPresenter::ProductProps do include Rails.application.routes.url_helpers include Capybara::RSpecMatchers let(:presenter) { described_class.new(product:) } describe "#props", :vcr do let(:seller) { create(:user, name: "Testy", username: "testy", created_at: 60.days.ago) } let(:buyer) { create(:user) } let(:request) { OpenStruct.new(remote_ip: "12.12.128.128", host: "example.com", host_with_port: "example.com") } before do create(:payment_completed, user: seller) create(:custom_domain, user: seller, domain: "www.example.com") allow(request).to receive(:cookie_jar).and_return({}) end context "membership product" do let(:product) { create(:membership_product, unique_permalink: "test", name: "hello", user: seller, price_cents: 200) } let(:offer_code) { create(:offer_code, products: [product], valid_at: 1.day.ago, expires_at: 1.day.from_now, minimum_quantity: 1, duration_in_billing_cycles: 1) } let(:purchase) { create(:membership_purchase, :with_review, link: product, email: buyer.email) } let!(:asset_preview) { create(:asset_preview, link: product) } context "when requested from gumroad domain" do let(:request) { double("request") } before do allow(request).to receive(:remote_ip).and_return("12.12.128.128") allow(request).to receive(:host).and_return("http://testy.test.gumroad.com") allow(request).to receive(:host_with_port).and_return("http://testy.test.gumroad.com:1234") allow(request).to receive(:cookie_jar).and_return({ _gumroad_guid: purchase.browser_guid }) end let(:pundit_user) { SellerContext.new(user: buyer, seller: buyer) } it "returns properties for the product page" do product.save_custom_attributes( [ { "name" => "Attribute 1", "value" => "Value 1" }, { "name" => "Attribute 2", "value" => "Value 2" } ] ) expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:, recommended_by: "discover", discount_code: offer_code.code)).to eq( product: { id: product.external_id, price_cents: 0, **ProductPresenter::InstallmentPlanProps.new(product:).props, covers: [product.asset_previews.first.as_json], currency_code: Currency::USD, custom_view_content_button_text: nil, custom_button_text_option: nil, description_html: "This is a collection of works spanning 1984 — 1994, while I spent time in a shack in the Andes.", pwyw: nil, is_sales_limited: false, is_tiered_membership: true, is_legacy_subscription: false, long_url: short_link_url(product.unique_permalink, host: seller.subdomain_with_protocol), main_cover_id: asset_preview.guid, name: "hello", permalink: "test", preorder: nil, duration_in_months: nil, quantity_remaining: nil, ratings: { count: 1, average: 5, percentages: [0, 0, 0, 0, 100], }, seller: { avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), id: seller.external_id, name: "Testy", profile_url: seller.profile_url(recommended_by: "discover"), }, collaborating_user: nil, is_compliance_blocked: false, is_published: true, is_physical: false, attributes: [ { name: "Attribute 1", value: "Value 1" }, { name: "Attribute 2", value: "Value 2" } ], free_trial: nil, is_quantity_enabled: false, is_multiseat_license: false, hide_sold_out_variants: false, native_type: "membership", is_stream_only: false, streamable: false, options: [{ id: product.variant_categories[0].variants[0].external_id, description: "", name: "hello", is_pwyw: false, price_difference_cents: nil, quantity_left: nil, recurrence_price_values: { "monthly" => { price_cents: 200, suggested_price_cents: nil } }, duration_in_minutes: nil, }], rental: nil, recurrences: { default: "monthly", enabled: [{ id: product.prices.alive.first.external_id, recurrence: "monthly", price_cents: 0 }] }, rental_price_cents: nil, sales_count: nil, summary: nil, thumbnail_url: nil, analytics: product.analytics_data, has_third_party_analytics: false, ppp_details: nil, can_edit: false, refund_policy: { title: "30-day money back guarantee", fine_print: nil, updated_at: product.user.refund_policy.updated_at.to_date }, bundle_products: [], public_files: [], audio_previews_enabled: false, }, discount_code: { valid: true, code: "sxsw", discount: { type: "fixed", cents: 100, product_ids: [product.external_id], expires_at: offer_code.expires_at, minimum_quantity: 1, duration_in_billing_cycles: 1, minimum_amount_cents: nil, }, }, purchase: { content_url: nil, created_at: purchase.created_at, id: purchase.external_id, email_digest: purchase.email_digest, membership: { manage_url: manage_subscription_url(purchase.subscription.external_id, host: DOMAIN), tier_name: "hello", tier_description: nil }, review: ProductReviewPresenter.new(purchase.product_review).review_form_props, should_show_receipt: true, is_gift_receiver_purchase: false, show_view_content_button_on_product_page: false, subscription_has_lapsed: false, total_price_including_tax_and_shipping: "$0 a month" }, wishlists: [], ) end context "when the user has read-only access" do let(:support_for_seller) { create(:user, username: "supportforseller") } let(:pundit_user) { SellerContext.new(user: support_for_seller, seller:) } before do create(:team_membership, user: support_for_seller, seller:, role: TeamMembership::ROLE_SUPPORT) end it "sets can_edit to false" do expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:)[:product][:can_edit]).to eq(false) end end context "when product refund policy setting is enabled" do let!(:product_refund_policy) do create(:product_refund_policy, title: "Refund policy", fine_print: "This is a product-level refund policy", product:, seller:) end before do product.user.update!(refund_policy_enabled: false) product.update!(product_refund_policy_enabled: true) end it "returns the product-level refund policy" do expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:)[:product][:refund_policy]).to eq( { title: product_refund_policy.title, fine_print: "<p>This is a product-level refund policy</p>", updated_at: product_refund_policy.updated_at.to_date } ) end context "when the fine_print is empty" do before do product_refund_policy.update!(fine_print: "") end it "returns the refund policy" do expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:)[:product][:refund_policy]).to eq( { title: product_refund_policy.title, fine_print: nil, updated_at: product_refund_policy.updated_at.to_date } ) end end context "when account-level refund policy setting is enabled" do before do seller.update!(refund_policy_enabled: true) seller.refund_policy.update!(fine_print: "This is a seller-level refund policy") end it "returns the seller-level refund policy" do expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:)[:product][:refund_policy]).to eq( { title: seller.refund_policy.title, fine_print: "<p>This is a seller-level refund policy</p>", updated_at: seller.refund_policy.updated_at.to_date } ) 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 "returns the product-level refund policy" do expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:)[:product][:refund_policy]).to eq( { title: product_refund_policy.title, fine_print: "<p>This is a product-level refund policy</p>", updated_at: product_refund_policy.updated_at.to_date } ) end end end end context "with invalid offer code" do it "returns an error if the offer code is sold out" do offer_code.update!(max_purchase_count: 0) expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:, discount_code: offer_code.code)[:discount_code]).to eq({ valid: false, error_code: :sold_out }) end it "returns an error if the offer code doesn't exist" do expect(described_class.new(product:).props(seller_custom_domain_url: nil, request:, pundit_user: nil, discount_code: "notreal")[:discount_code]).to eq({ valid: false, error_code: :invalid_offer }) end end end end context "digital versioned product" do let(:product) { create(:product_with_digital_versions, native_type: Link::NATIVE_TYPE_COMMISSION, unique_permalink: "test", name: "hello", user: seller, price_cents: 200) } let(:purchase) { create(:membership_purchase, link: product, email: buyer.email) } let!(:review) { create(:product_review, purchase:, rating: 5, message: "This is my review!") } context "when requested from gumroad domain" do let(:request) { double("request") } before do allow(request).to receive(:remote_ip).and_return("12.12.128.128") allow(request).to receive(:host).and_return("http://testy.test.gumroad.com") allow(request).to receive(:host_with_port).and_return("http://testy.test.gumroad.com:1234") allow(request).to receive(:cookie_jar).and_return({ _gumroad_guid: purchase.browser_guid }) end let(:pundit_user) { SellerContext.new(user: buyer, seller: buyer) } it "returns properties for the product page" do expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:, recommended_by: "profile")).to eq( product: { id: product.external_id, price_cents: 200, **ProductPresenter::InstallmentPlanProps.new(product:).props, covers: [], currency_code: Currency::USD, custom_view_content_button_text: nil, custom_button_text_option: nil, description_html: "This is a collection of works spanning 1984 — 1994, while I spent time in a shack in the Andes.", pwyw: nil, is_sales_limited: false, is_tiered_membership: false, is_legacy_subscription: false, long_url: short_link_url(product.unique_permalink, host: seller.subdomain_with_protocol), main_cover_id: nil, name: "hello", permalink: "test", preorder: nil, duration_in_months: nil, quantity_remaining: nil, ratings: { count: 1, average: 5, percentages: [0, 0, 0, 0, 100], }, seller: { avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), id: seller.external_id, name: "Testy", profile_url: seller.profile_url(recommended_by: "profile"), }, collaborating_user: nil, is_compliance_blocked: false, is_published: true, is_physical: false, attributes: [], free_trial: nil, is_quantity_enabled: false, is_multiseat_license: false, hide_sold_out_variants: false, native_type: "commission", is_stream_only: false, streamable: false, options: [ { id: product.variant_categories[0].variants[0].external_id, description: "", name: "Untitled 1", is_pwyw: false, price_difference_cents: 0, quantity_left: nil, recurrence_price_values: nil, duration_in_minutes: nil, }, { id: product.variant_categories[0].variants[1].external_id, description: "", name: "Untitled 2", is_pwyw: false, price_difference_cents: 0, quantity_left: nil, recurrence_price_values: nil, duration_in_minutes: nil, } ], rental: nil, recurrences: nil, rental_price_cents: nil, sales_count: nil, summary: nil, thumbnail_url: nil, analytics: product.analytics_data, has_third_party_analytics: false, ppp_details: nil, can_edit: false, refund_policy: { title: product.user.refund_policy.title, fine_print: product.user.refund_policy.fine_print, updated_at: product.user.refund_policy.updated_at.to_date }, bundle_products: [], public_files: [], audio_previews_enabled: false, }, discount_code: nil, purchase: { content_url: nil, id: purchase.external_id, email_digest: purchase.email_digest, created_at: purchase.created_at, membership: nil, review: ProductReviewPresenter.new(purchase.product_review).review_form_props, should_show_receipt: true, is_gift_receiver_purchase: false, show_view_content_button_on_product_page: false, subscription_has_lapsed: false, total_price_including_tax_and_shipping: "$2" }, wishlists: [], ) end it "handles users without a username set" do seller.update!(username: nil) expect(described_class.new(product:).props(seller_custom_domain_url: nil, request:, pundit_user: nil)[:seller]).to be_nil end end end context "bundle product" do let(:bundle) { create(:product, user: seller, is_bundle: true) } before do create(:bundle_product, bundle:, product: create(:product, user: seller), quantity: 2, position: 1) versioned_product = create(:product_with_digital_versions, user: seller) versioned_product.alive_variants.second.update(price_difference_cents: 200) create(:bundle_product, bundle:, product: versioned_product, variant: versioned_product.alive_variants.second, position: 0) bundle.reload end it "sets bundle_products correctly" do expect(described_class.new(product: bundle).props(seller_custom_domain_url: nil, request:, pundit_user: nil)[:product][:bundle_products]).to eq( [ { currency_code: Currency::USD, id: bundle.bundle_products.second.product.external_id, name: "The Works of Edgar Gumstein", native_type: "digital", price: 300, quantity: 1, ratings: { average: 0, count: 0 }, thumbnail_url: nil, url: short_link_url(bundle.bundle_products.second.product.unique_permalink, host: request[:host]), variant: "Untitled 2", }, { currency_code: Currency::USD, id: bundle.bundle_products.first.product.external_id, name: "The Works of Edgar Gumstein", native_type: "digital", price: 200, quantity: 2, ratings: { average: 0, count: 0 }, thumbnail_url: nil, url: short_link_url(bundle.bundle_products.first.product.unique_permalink, host: request[:host]), variant: nil, }, ] ) end end describe "collaborators" do let(:product) { create(:product, user: seller, is_collab: true) } let(:pundit_user) { SellerContext.new(user: product.user, seller: product.user) } let!(:collaborator) { create(:collaborator, seller:) } let!(:product_affiliate) { create(:product_affiliate, affiliate: collaborator, product:, dont_show_as_co_creator: false) } context "apply_to_all_products is true" do context "collaborator dont_show_as_co_creator is false" do it "includes the collaborating user" do expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:)[:product][:collaborating_user]).to eq( { avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), id: collaborator.affiliate_user.external_id, name: collaborator.affiliate_user.username, profile_url: collaborator.affiliate_user.profile_url, } ) end end context "collaborator dont_show_as_co_creator is true" do before { collaborator.update!(dont_show_as_co_creator: true) } it "does not include the collaborating user" do expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:)[:product][:collaborating_user]).to be_nil end end end context "apply_to_all_products is false" do before { collaborator.update!(apply_to_all_products: false) } context "product affiliate dont_show_as_co_creator is false" do it "includes the collaborating user" do expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:)[:product][:collaborating_user]).to eq( { avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), id: collaborator.affiliate_user.external_id, name: collaborator.affiliate_user.username, profile_url: collaborator.affiliate_user.profile_url, } ) end end context "product affiliate dont_show_as_co_creator is true" do before { product_affiliate.update!(dont_show_as_co_creator: true) } it "does not include the collaborating user" do expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:)[:product][:collaborating_user]).to be_nil end end end end it "caches sales_count and tracks cache hits/misses", :sidekiq_inline, :elasticsearch_wait_for_refresh do product = create(:product, user: seller) presenter = described_class.new(product:) metrics_key = described_class::SALES_COUNT_CACHE_METRICS_KEY $redis.del(metrics_key) expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user: nil)[:product][:sales_count]).to eq(nil) expect($redis.hgetall(metrics_key)).to eq({}) product.update!(should_show_sales_count: true) expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user: nil)[:product][:sales_count]).to eq(0) expect($redis.hgetall(metrics_key)).to eq("misses" => "1") expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user: nil)[:product][:sales_count]).to eq(0) expect($redis.hgetall(metrics_key)).to eq("misses" => "1", "hits" => "1") create(:purchase, link: product) expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user: nil)[:product][:sales_count]).to eq(1) expect($redis.hgetall(metrics_key)).to eq("misses" => "2", "hits" => "1") expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user: nil)[:product][:sales_count]).to eq(1) expect($redis.hgetall(metrics_key)).to eq("misses" => "2", "hits" => "2") end it "includes free downloads in the sales_count for products with paid variants", :sidekiq_inline, :elasticsearch_wait_for_refresh do product = create(:product, user: seller, should_show_sales_count: true, price_cents: 0) presenter = described_class.new(product:) category = create(:variant_category, link: product) create(:variant, variant_category: category, price_difference_cents: 200) create(:free_purchase, link: product) create_list(:purchase, 2, link: product, price_cents: 200) expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user: nil)[:product][:sales_count]).to eq(3) end context "with current seller" do let(:product) { create(:product) } let(:pundit_user) { SellerContext.new(user: buyer, seller: buyer) } it "includes wishlists" do wishlist = create(:wishlist, user: buyer) presenter = described_class.new(product:) expect(presenter.props(seller_custom_domain_url: nil, request:, pundit_user:)[:wishlists]).to eq([{ id: wishlist.external_id, name: wishlist.name, selections_in_wishlist: [] }]) end end context "when custom domain is specified" do let(:product) { create(:product) } it "uses the custom domain for the seller profile url" do expect( presenter.props(seller_custom_domain_url: "https://example.com", request:, pundit_user: nil, recommended_by: "discover")[:product][:seller][:profile_url] ).to eq "https://example.com?recommended_by=discover" end end context "with public files" do let(:product) { create(:product) } let!(:public_file1) { create(:public_file, :with_audio, resource: product) } let!(:public_file2) { create(:public_file, resource: product) } let!(:public_file3) { create(:public_file, :with_audio, deleted_at: 1.day.ago) } before do Feature.activate_user(:audio_previews, product.user) public_file1.file.analyze end it "includes public files" do props = described_class.new(product:).props(seller_custom_domain_url: nil, request:, pundit_user: nil)[:product] expect(props[:public_files].sole).to eq(PublicFilePresenter.new(public_file: public_file1).props) expect(props[:audio_previews_enabled]).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/presenters/product_presenter/installment_plan_props_spec.rb
spec/presenters/product_presenter/installment_plan_props_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe ProductPresenter::InstallmentPlanProps do let(:product) { create(:product, price_cents: 1000) } let(:presenter) { described_class.new(product: product) } describe "#props" do context "when product has no installment plan" do it "returns correct props" do product.installment_plan&.destroy! expect(presenter.props).to eq( eligible_for_installment_plans: true, allow_installment_plan: false, installment_plan: nil ) end end context "when product has an installment plan" do let!(:installment_plan) do create(:product_installment_plan, link: product, number_of_installments: 2, recurrence: "monthly") end it "returns correct props with installment plan details" do expect(presenter.props).to eq( eligible_for_installment_plans: true, allow_installment_plan: true, installment_plan: { number_of_installments: 2, recurrence: "monthly" } ) end end context "when product is not eligible for installment plans" do let(:product) { create(:membership_product) } it "returns correct props" do expect(presenter.props).to eq( eligible_for_installment_plans: false, allow_installment_plan: false, installment_plan: 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/presenters/product_presenter/card_spec.rb
spec/presenters/product_presenter/card_spec.rb
# frozen_string_literal: true require "spec_helper" describe ProductPresenter::Card do include Rails.application.routes.url_helpers let(:request) { instance_double(ActionDispatch::Request, host: "test.gumroad.com", host_with_port: "test.gumroad.com:1234", protocol: "http") } let(:creator) { create(:user, name: "Testy", username: "testy") } let(:product) { create(:product, unique_permalink: "test", name: "hello", user: creator) } describe "#for_web" do context "digital product" do it "returns the necessary properties for a product card" do data = described_class.new(product:).for_web(request:, recommended_by: "discover") expect(data).to eq( { id: product.external_id, permalink: "test", name: "hello", seller: { id: creator.external_id, name: "Testy", profile_url: creator.profile_url(recommended_by: "discover"), avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png") }, description: product.plaintext_description.truncate(100), ratings: { count: 0, average: 0 }, currency_code: Currency::USD, price_cents: 100, thumbnail_url: nil, native_type: Link::NATIVE_TYPE_DIGITAL, is_pay_what_you_want: false, is_sales_limited: false, duration_in_months: nil, recurrence: nil, url: product.long_url(recommended_by: "discover"), quantity_remaining: nil } ) end it "returns the URL with the offer code" do data = described_class.new(product:).for_web(request:, recommended_by: "discover", offer_code: "BLACKFRIDAY2025") expect(data[:url]).to include("code=BLACKFRIDAY2025") end it "does not return the URL of a deleted thumbnail" do create(:thumbnail, product:) result = described_class.new(product:).for_web expect(result[:thumbnail_url]).to be_present product.thumbnail.mark_deleted! product.reload result = described_class.new(product:).for_web expect(result[:thumbnail_url]).to eq(nil) end it "includes description when compute_description is true by default" do result = described_class.new(product:).for_web expect(result[:description]).to eq(product.plaintext_description.truncate(100)) end it "includes description when compute_description is explicitly true" do result = described_class.new(product:).for_web(compute_description: true) expect(result[:description]).to eq(product.plaintext_description.truncate(100)) end it "excludes description when compute_description is false" do result = described_class.new(product:).for_web(compute_description: false) expect(result).not_to have_key(:description) end end context "membership product" do let(:product) do recurrence_price_values = [ { "monthly" => { enabled: true, price: 10 }, "yearly" => { enabled: true, price: 100 } }, { "monthly" => { enabled: true, price: 2.99 }, "yearly" => { enabled: true, price: 19.99 } } ] create(:membership_product_with_preset_tiered_pricing, user: creator, recurrence_price_values:, subscription_duration: "yearly") end it "includes the lowest tier price for the default subscription duration" do data = described_class.new(product:).for_web expect(data[:price_cents]).to eq 19_99 end end end describe "#for_email" do it "returns the necessary properties for an email product card" do expect(described_class.new(product:).for_email).to eq( { name: product.name, thumbnail_url: ActionController::Base.helpers.asset_url("native_types/thumbnails/digital.png"), url: short_link_url(product.general_permalink, host: "http://#{creator.username}.test.gumroad.com:31337"), seller: { name: creator.name, profile_url: creator.profile_url, avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"), }, } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/receipt_presenter/payment_info_spec.rb
spec/presenters/receipt_presenter/payment_info_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/receipt_presenter_concern" describe ReceiptPresenter::PaymentInfo do include ActionView::Helpers::UrlHelper let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller, name: "Digital product") } let(:purchase) do create( :purchase, link: product, seller:, price_cents: 1_499, created_at: DateTime.parse("January 1, 2023") ) end let(:payment_info) { described_class.new(purchase) } let(:invoice_url) do Rails.application.routes.url_helpers.generate_invoice_by_buyer_url( purchase.external_id, email: purchase.email, host: UrlService.domain_with_protocol ) end describe ".new" do let(:subscription) { create(:subscription) } context "with a Purchase" do it "assigns the purchase to instance variables" do expect(payment_info.send(:chargeable)).to eq(purchase) expect(payment_info.send(:orderable)).to eq(purchase) end end context "with a Charge", :vcr do let(:charge) { create(:charge) } let(:payment_info) { described_class.new(charge) } before do charge.purchases << purchase charge.order.purchases << purchase end it "assigns the charge and order to instance variables" do expect(payment_info.send(:chargeable)).to eq(charge) expect(payment_info.send(:orderable)).to eq(charge.order) end end end describe "#title" do context "when is not a recurring subscription charge" do it "returns correct title" do expect(payment_info.title).to eq("Payment info") end end context "when the purchase is recurring subscription" do include_context "when the purchase is recurring subscription" it "returns correct title" do expect(payment_info.title).to eq("Thank you for your payment!") end end end describe "payment attributes" do let(:today_payment_attributes) { payment_info.today_payment_attributes } let(:upcoming_payment_attributes) { payment_info.upcoming_payment_attributes } RSpec.shared_examples "payment attributes for single purchase" do context "when is gift receiver purchase" do let(:gift) { create(:gift, gift_note: "Hope you like it!", giftee_email: "giftee@example.com") } let(:purchase) { create(:purchase, link: gift.link, gift_received: gift, is_gift_receiver_purchase: true) } it "returns an empty arrays" do expect(today_payment_attributes).to eq([]) expect(upcoming_payment_attributes).to eq([]) end end context "when is gift sender purchase" do let(:gift) { create(:gift, gift_note: "Hope you like it!", giftee_email: "giftee@example.com") } let(:purchase) { create(:purchase, link: gift.link, gift_received: gift, is_gift_sender_purchase: true) } it "returns an empty array for upcoming payment" do expect(upcoming_payment_attributes).to eq([]) end end context "when is a membership purchase" do let(:product) { create(:membership_product, name: "Membership product") } let(:purchase) do create( :membership_purchase, link: product, price_cents: 1_998, created_at: DateTime.parse("January 1, 2023") ) end context "with shipping and tax" do before do purchase.update!( was_purchase_taxable: true, displayed_price_cents: 1_744, tax_cents: 254, shipping_cents: 499, total_transaction_cents: 1_744 + 254 + 499 ) # Skip validation that triggers "Validation failed: We couldn't charge your card. Try again or use a different card." purchase.update_column(:price_cents, 1_744) end it "returns pricing attributes" do expect(today_payment_attributes).to eq( [ { label: "Today's payment", value: nil }, { label: "Membership product", value: "$17.44" }, { label: "Shipping", value: "$4.99" }, { label: "Sales tax (included)", value: "$2.54" }, { label: "Amount paid", value: "$24.97" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end context "when the purchase is in EUR" do before do purchase.link.default_price.update!(currency: Currency::EUR) purchase.link.update!(price_currency_type: Currency::EUR) purchase.update!( displayed_price_currency_type: Currency::EUR, rate_converted_to_usd: 1.07, displayed_price_cents: 1_866 # 17.44 * 1.07 ) purchase.original_purchase.reload end it "returns today's pricing attributes in USD" do expect(today_payment_attributes).to eq( [ { label: "Today's payment", value: nil }, { label: "Membership product", value: "$17.44" }, { label: "Shipping", value: "$4.99" }, { label: "Sales tax (included)", value: "$2.54" }, { label: "Amount paid", value: "$24.97" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end end context "when the purchase is recurring subscription" do include_context "when the purchase is recurring subscription" do let(:purchase_attributes) do { was_purchase_taxable: true, displayed_price_cents: 1_744, tax_cents: 254, shipping_cents: 499, total_transaction_cents: 1_744 + 254 + 499, created_at: DateTime.parse("January 1, 2023"), } end end before do purchase.subscription.original_purchase.update!(purchase_attributes) end it "returns today's pricing attributes in USD" do expect(today_payment_attributes).to eq( [ { label: "Today's payment", value: nil }, { label: "Membership product", value: "$17.44" }, { label: "Shipping", value: "$4.99" }, { label: "Sales tax (included)", value: "$2.54" }, { label: "Amount paid", value: "$24.97" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end end end context "when the purchase is a free trial" do let(:purchase) do create( :free_trial_membership_purchase, price_cents: 3_00, created_at: Date.parse("Jan 1, 2023") ) end before do purchase.link.update!(name: "Membership with trial") purchase.subscription.update!(free_trial_ends_at: Date.parse("Jan 8, 2023")) end it "returns today's payment attributes" do expect(today_payment_attributes).to eq( [ { label: "Today's payment", value: nil }, { label: "Membership with trial", value: "$0" }, ] ) end it "returns upcoming payment attributes" do expect(upcoming_payment_attributes).to eq( [ { label: "Upcoming payment", value: nil }, { label: "Membership with trial", value: "$3 on Jan 8, 2023" }, ] ) end context "when the purchase includes tax" do before do purchase.update!( was_purchase_taxable: true, tax_cents: 120, total_transaction_cents: purchase.total_transaction_cents + 120, displayed_price_cents: purchase.displayed_price_cents + 120 ) end it "return today's payment attributes with product price and tax as zeros" do purchase.subscription.original_purchase.reload expect(today_payment_attributes).to eq( [ { label: "Today's payment", value: nil }, { label: "Membership with trial", value: "$0" }, { label: "Sales tax (included)", value: "$0" }, { label: "Amount paid", value: "$0" }, ] ) end it "returns upcoming payment attributes" do purchase.subscription.original_purchase.reload expect(upcoming_payment_attributes).to eq( [ { label: "Upcoming payment", value: nil }, { label: "Membership with trial", value: "$5.40 on Jan 8, 2023" }, ] ) end end end context "when the purchase has fixed length" do context "when the purchase is a free trial" do let(:purchase) do create( :free_trial_membership_purchase, price_cents: 3_00, created_at: Date.parse("Jan 1, 2023") ) end before do purchase.link.update!(name: "Membership product") purchase.subscription.update!( free_trial_ends_at: Date.parse("Jan 8, 2023"), charge_occurrence_count: 2 ) end it "returns today's payment attributes" do expect(today_payment_attributes).to eq( [ { label: "Today's payment", value: nil }, { label: "Membership product (free trial)", value: "$0" }, ] ) end it "returns upcoming payment attributes" do expect(upcoming_payment_attributes).to eq( [ { label: "Upcoming payment", value: nil }, { label: "Membership product: 1 of 2", value: "$3 on Jan 8, 2023" }, ] ) end end context "when there is at least one more remaining charge" do before do purchase.subscription.update!(charge_occurrence_count: 2) end it "returns today's payment attributes" do purchase.subscription.original_purchase.reload expect(today_payment_attributes).to eq( [ { label: "Today's payment", value: nil }, { label: "Membership product: 1 of 2", value: "$19.98" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end it "returns upcoming payment attributes" do purchase.subscription.original_purchase.reload expect(upcoming_payment_attributes).to eq( [ { label: "Upcoming payment", value: nil }, { label: "Membership product: 2 of 2", value: "$19.98 on Feb 1, 2023" }, ] ) end end context "when there are no more remaining charges" do before do purchase.subscription.update!(charge_occurrence_count: 1) end it "does not includes today's payment header and upcoming payments" do expect(today_payment_attributes).to eq( [ { label: "Membership product: 1 of 1", value: "$19.98 - This is the final payment. You will not be charged for this product again." }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end it "returns empty upcoming payment attributes" do expect(upcoming_payment_attributes).to eq([]) end end end end context "when is not a membership purchase" do context "when the purchase is free" do let(:purchase) { create(:free_purchase) } it "returns an empty arrays for payment attributes" do expect(today_payment_attributes).to eq([]) expect(upcoming_payment_attributes).to eq([]) end end context "when the purchase is for digital product" do context "when there is only 1 qty" do it "returns today's pricing attribute with product price" do expect(today_payment_attributes).to eq( [ { label: "Digital product", value: "$14.99" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end it "returns empty upcoming payment attributes" do expect(upcoming_payment_attributes).to eq([]) end context "when the purchase is in EUR" do before do purchase.link.update!(price_currency_type: Currency::EUR, price_cents: 1499) purchase.update!( displayed_price_currency_type: Currency::EUR, rate_converted_to_usd: 1.07, displayed_price_cents: purchase.price_cents * 1.07 # 14.99 * 1.07 ) purchase.original_purchase.reload end it "returns today's pricing attributes in USD" do expect(today_payment_attributes).to eq( [ { label: "Digital product", value: "$14.98" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end end context "when the purchase is taxable" do before do purchase.update!( was_purchase_taxable: true, tax_cents: 254, displayed_price_cents: 1_744, price_cents: 1_744, total_transaction_cents: 1_744 + 254 ) end it "returns today's pricing attributes with product name and sales tax" do expect(today_payment_attributes).to eq( [ { label: "Digital product", value: "$17.44" }, { label: "Sales tax (included)", value: "$2.54" }, { label: "Amount paid", value: "$19.98" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end it "returns empty upcoming payment attributes" do expect(upcoming_payment_attributes).to eq([]) end end end context "when the quantity is greater than 1" do before do purchase.update!( quantity: 2, displayed_price_cents: purchase.displayed_price_cents * 2, price_cents: purchase.displayed_price_cents * 2, total_transaction_cents: purchase.displayed_price_cents * 2 ) end context "when there is no tax or shipping" do it "returns today's pricing attributes without amount paid" do expect(today_payment_attributes).to eq( [ { label: "Digital product × 2", value: "$29.98" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end it "returns empty upcoming payment attributes" do expect(upcoming_payment_attributes).to eq([]) end end context "when the purchase has a license with quantity" do include_context "when the purchase has a license" it "returns today's pricing attributes with quantity" do expect(today_payment_attributes).to eq( [ { label: "Digital product × 2", value: "$29.98" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end it "returns empty upcoming payment attributes" do expect(upcoming_payment_attributes).to eq([]) end end context "when the purchase is taxable" do before do purchase.update!( was_purchase_taxable: true, tax_cents: 254, displayed_price_cents: 1_744, price_cents: 1_744, total_transaction_cents: 1_744 + 254 ) end it "returns today's pricing attributes with subtotal, quantity, sales tax" do expect(today_payment_attributes).to eq( [ { label: "Digital product × 2", value: "$17.44" }, { label: "Sales tax (included)", value: "$2.54" }, { label: "Amount paid", value: "$19.98" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end it "returns empty upcoming payment attributes" do expect(upcoming_payment_attributes).to eq([]) end end end end context "when the purchase is for a physical product" do include_context "when the purchase is for a physical product" before do purchase.update!( was_purchase_taxable: true, displayed_price_cents: 1_499, price_cents: 1_499, # shipping included tax_cents: 254, shipping_cents: 499, total_transaction_cents: 1_499 + 254 + 499 ) purchase.link.update!(name: "Physical product") end it "returns today's pricing attributes" do expect(today_payment_attributes).to eq( [ { label: "Physical product", value: "$14.99" }, { label: "Shipping", value: "$4.99" }, { label: "Sales tax (included)", value: "$2.54" }, { label: "Amount paid", value: "$22.52" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end it "returns empty upcoming payment attributes" do expect(upcoming_payment_attributes).to eq([]) end end end context "when the purchase is a commission deposit purchase", :vcr do let(:purchase) { create(:commission_deposit_purchase, price_cents: 200) } let(:payment_info) { described_class.new(purchase) } before { purchase.create_artifacts_and_send_receipt! } it "returns correct today payment attributes" do expect(payment_info.today_payment_attributes).to eq( [ { label: "Today's payment", value: nil }, { label: "The Works of Edgar Gumstein", value: "$1" }, { label: nil, value: link_to("Generate invoice", invoice_url) } ] ) end it "returns correct upcoming payment attributes" do expect(payment_info.upcoming_payment_attributes).to eq( [ { label: "Upcoming payment", value: nil }, { label: "The Works of Edgar Gumstein", value: "$1 on completion" } ] ) end end end context "with a Purchase" do it_behaves_like "payment attributes for single purchase" end context "with a Charge", :vcr do let(:charge) { create(:charge) } let(:invoice_url) do purchase = charge.send(:purchase_as_chargeable) Rails.application.routes.url_helpers.generate_invoice_by_buyer_url( purchase.external_id, email: purchase.email, host: UrlService.domain_with_protocol ) end let(:payment_info) { described_class.new(charge) } before do charge.purchases << purchase charge.order.purchases << purchase end it_behaves_like "payment attributes for single purchase" context "with multiple purchases" do let(:purchase_two) do create( :purchase, link: create(:product, name: "Product Two", user: seller), seller:, price_cents: 999 ) end let(:purchase_three) do create( :purchase, link: create(:product, name: "Product Three", user: seller), seller:, price_cents: 499 ) end before do charge.purchases << purchase_two charge.purchases << purchase_three charge.order.purchases << purchase_two charge.order.purchases << purchase_three end it "includes both purchases with amount paid" do expect(today_payment_attributes).to eq( [ { label: "Digital product", value: "$14.99" }, { label: "Product Two", value: "$9.99" }, { label: "Product Three", value: "$4.99" }, { label: "Amount paid", value: "$29.97" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end context "when purchases have shipping and tax" do before do purchase_two.update!( was_purchase_taxable: true, displayed_price_cents: 999, # in product currency, USD tax_cents: 120, shipping_cents: 250, total_transaction_cents: 999 + 120 + 250 ) purchase_three.update!( was_purchase_taxable: true, displayed_price_cents: 499, # in product currency, USD tax_cents: 59, shipping_cents: 150, total_transaction_cents: 499 + 59 + 150 ) end it "sums amounts" do expect(today_payment_attributes).to eq( [ { label: "Digital product", value: "$14.99" }, { label: "Product Two", value: "$9.99" }, { label: "Product Three", value: "$4.99" }, { label: "Shipping", value: "$4" }, # 2.50 + 1.5 { label: "Sales tax (included)", value: "$1.79" }, # 1.2 + 0.59 { label: "Amount paid", value: "$35.76" }, { label: nil, value: link_to("Generate invoice", invoice_url) }, ] ) end end end end end describe "#recurring_subscription_notes" do context "when is not a recurring subscription charge" do it "returns nil" do expect(payment_info.send(:recurring_subscription_notes)).to be_nil end end context "when the purchase is recurring subscription" do include_context "when the purchase is recurring subscription" it "returns note content" do expect(payment_info.send(:recurring_subscription_notes).first).to include( "We have successfully processed the payment for your recurring subscription" ) end end context "when the purchase is an installment payment" do let(:product) { create(:product, :with_installment_plan, user: seller, name: "Installment product") } let(:original_installment_purchase) { create(:installment_plan_purchase, link: product) } let(:purchase) do create( :recurring_installment_plan_purchase, subscription: original_installment_purchase.subscription, link: product ) end it "returns installment-specific note content" do note = payment_info.send(:recurring_subscription_notes).first expect(note).to include("We have successfully processed the installment payment for") expect(note).to include(product.name) end end end describe "#usd_currency_note" do it "returns note content" do expect(payment_info.send(:usd_currency_note)).to eq( "All charges are processed in United States Dollars. " + "Your bank or financial institution may apply their own fees for currency conversion." ) end end describe "#credit_card_note" do RSpec.shared_examples "credit card note" do it "returns note content" do expect(payment_info.send(:credit_card_note)).to eq( "The charge will be listed as GUMRD.COM* on your credit card statement." ) end context "when the card_type is blank" do before { purchase.update!(card_type: nil) } it "returns nil" do expect(payment_info.send(:credit_card_note)).to be_nil end end context "when the card_type is paypal" do before { purchase.update!(card_type: CardType::PAYPAL) } it "returns nil" do purchase.update!(card_type: CardType::PAYPAL) expect(payment_info.send(:credit_card_note)).to be_nil end end end context "with a Purchase" do it_behaves_like "credit card note" end context "with a Charge", :vcr do let(:charge) { create(:charge) } let(:payment_info) { described_class.new(charge) } before do charge.purchases << purchase charge.order.purchases << purchase end it_behaves_like "credit card note" end end describe "#notes" do include_context "when the purchase is recurring subscription" it "returns all notes" do expect(payment_info.notes.size).to eq(3) expect(payment_info.notes[0]).to include( "We have successfully processed the payment for your recurring subscription" ) expect(payment_info.notes[1]).to eq( "All charges are processed in United States Dollars. " + "Your bank or financial institution may apply their own fees for currency conversion." ) expect(payment_info.notes[2]).to eq( "The charge will be listed as GUMRD.COM* on your credit card statement." ) end end describe "#payment_method_attribute" do RSpec.shared_examples "payment method attribute" do it "returns payment method attribute" do expect(payment_info.payment_method_attribute).to eq( { label: "Payment method", value: "VISA *4062" } ) end context "when the purchase is a free trial" do let(:purchase) { create(:free_trial_membership_purchase) } it "returns nil" do expect(payment_info.payment_method_attribute).to be_nil end end context "when the purchase is a free purchase" do let(:purchase) { create(:free_purchase) } it "returns nil" do expect(payment_info.payment_method_attribute).to be_nil end end end describe "#today_membership_paid_until_attribute" do context "when is not a recurring subscription charge" do it "returns nil" do expect(payment_info.send(:today_membership_paid_until_attribute)).to be_nil end end context "when the purchase is recurring subscription" do let(:purchase) { create(:recurring_membership_purchase) } context "when is gift sender purchase" do before do purchase.update!(is_gift_sender_purchase: true) end it "return the paid until date" do expect(payment_info.send(:today_membership_paid_until_attribute)).to eq( { label: "Membership paid for until", value: purchase.subscription.end_time_of_subscription.to_fs(:formatted_date_abbrev_month) } ) end end context "when is not gift sender purchase" do it "returns nil" do expect(payment_info.send(:today_membership_paid_until_attribute)).to be_nil end end context "when the purchase is not a subscription" do before do allow(purchase).to receive(:subscription).and_return(nil) end it "returns nil" do expect(payment_info.send(:today_membership_paid_until_attribute)).to be_nil end end end end context "with a Purchase" do it_behaves_like "payment method attribute" end context "with a Charge", :vcr do let(:charge) { create(:charge) } let(:payment_info) { described_class.new(charge) } before do charge.purchases << purchase charge.order.purchases << purchase end it_behaves_like "payment method attribute" context "with two free purchases" do let(:purchase) { create(:free_purchase) } let(:purchase_two) { create(:free_purchase) } before do charge.purchases << purchase_two charge.order.purchases << purchase_two end it "returns nil" do expect(payment_info.payment_method_attribute).to be_nil end context "when the second purchase is not free" do let(:purchase_two) { create(:purchase) } it "returns payment method attribute" do expect(payment_info.payment_method_attribute).to eq( { label: "Payment method", value: "VISA *4062" } ) 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/presenters/receipt_presenter/item_info_spec.rb
spec/presenters/receipt_presenter/item_info_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/receipt_presenter_concern" describe ReceiptPresenter::ItemInfo do include ActionView::Helpers::UrlHelper let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:purchase) do create( :purchase, link: product, seller:, price_cents: 1_499, created_at: DateTime.parse("January 1, 2023") ) end let(:item_info) { described_class.new(purchase) } describe ".new" do let(:subscription) { create(:subscription) } it "assigns instance variables" do expect(item_info.send(:product)).to eq(product) expect(item_info.send(:purchase)).to eq(purchase) expect(item_info.send(:seller)).to eq(purchase.seller) expect(item_info.send(:subscription)).to eq(purchase.subscription) end end describe "#props" do let(:props) { item_info.props } it "returns a hash with the correct keys" do expect(props.keys).to eq( %i[ notes custom_receipt_note show_download_button license_key gift_attributes general_attributes product manage_subscription_note ] ) end describe "notes" do context "when the purchase is a free trial" do let(:purchase) { create(:free_trial_membership_purchase) } it "returns note" do expect(props[:notes]).to eq(["Your free trial has begun!"]) end end context "when the purchase is for a physical product" do include_context "when the purchase is for a physical product" it "returns physical_product_note" do expect(props[:notes]).to eq(["Your order will ship shortly. The creator will notify you when your package is on its way."]) end context "when is a gift sender purchase" do include_context "when is a gift sender purchase" it "returns an empty array" do expect(props[:notes]).to eq([]) end end context "if is preorder authorization" do include_context "when is a preorder authorization" it "returns notes" do expect(props[:notes]).to eq( [ "The shipment will occur soon after December 1st, 10AM PST.", "You'll get it on December 1st, 10AM PST." ] ) end end end context "when the purchase is a rental" do before do purchase.update!(is_rental: true) end it "return rental note" do expect(props[:notes]).to eq(["Your rental of The Works of Edgar Gumstein will expire in 30 days or 72 hours after you begin viewing it."]) end end it "returns an empty array" do expect(props[:notes]).to eq([]) end end describe "custom_receipt_note" do context "when the product does not have a custom receipt note" do it "returns nil" do expect(props[:custom_receipt_note]).to be_nil end end context "when the product has a custom receipt note" do before do purchase.link.update!(custom_receipt: "Here is a link to https://example.com") end it "returns nil" do expect(props[:custom_receipt_note]).to be_nil end context "when the purchase has a gift note" do let(:gift) { create(:gift, gift_note: "Gift note") } 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 nil" do expect(props[:custom_receipt_note]).to be_nil end end end end describe "show_download_button" do context "when the purchase has url_redirect" do before do purchase.create_url_redirect! end context "when the product has content for url redirects" do it "returns true" do expect(props[:show_download_button]).to eq(true) end context "when is gift sender purchase" do include_context "when is a gift sender purchase" it "returns false" do expect(props[:show_download_button]).to eq(false) end end context "when is a preorder authorization" do include_context "when is a preorder authorization" it "returns false" do expect(props[:show_download_button]).to eq(false) end end context "when is a coffee purchase" do before { purchase.link.update!(native_type: Link::NATIVE_TYPE_COFFEE) } it "returns false" do expect(props[:show_download_button]).to eq(false) end end end end end describe "license_key" do context "when the purchase has a license" do include_context "when the purchase has a license" it "returns license key" do expect(props[:license_key]).to eq(purchase.license_key) end end context "when the purchase does not have a license" do it "returns nil" do expect(props[:license_key]).to be_nil end end end describe "product" do it "calls ProductPresenter#card_for_email" do expect(ProductPresenter).to receive(:card_for_email).with(product:).and_call_original expect(props[:product]).to be_present end end describe "gift_attributes" do context "when is not gift sender purchase" do it "returns an empty array" do expect(props[:gift_attributes]).to eq([]) end end context "when is a gift sender purchase" do include_context "when is a gift sender purchase" it "returns gift attributes" do allow(purchase).to receive(:giftee_name_or_email).and_return("giftee_name_or_email") expect(props[:gift_attributes]).to eq( [ { label: "Gift sent to", value: "giftee_name_or_email" }, { label: "Message", value: "Hope you like it!" } ] ) end context "when the gift note is empty" do before do gift.update!(gift_note: " ") end it "doesn't return gift_message_attribute" do expect(props[:gift_attributes]).to eq( [ { label: "Gift sent to", value: "giftee@example.com" }, ] ) end end end end describe "general_attributes" do context "when the purchase is not for membership" do context "when the purchase doesn't have a variant or quantity" do it "returns product price" do expect(props[:general_attributes]).to eq( [ { label: "Product price", value: "$14.99" }, ] ) end context "when the purchase is in EUR" do before do purchase.update!( displayed_price_currency_type: Currency::EUR, ) purchase.original_purchase.reload end it "returns product price in EUR" do expect(props[:general_attributes]).to eq( [ { label: "Product price", value: "€14.99" } ] ) end end end context "when the purchase is a call purchase" do let!(:purchase) { create(:call_purchase, variant_attributes: [create(:variant, name: "1 hour")]) } it "returns general attributes including product price and duration" do presenter = described_class.new(purchase) expect(presenter.props[:general_attributes]).to eq( [ { label: "Call schedule", value: [purchase.call.formatted_time_range, purchase.call.formatted_date_range] }, { label: "Call link", value: "https://zoom.us/j/gmrd" }, { label: "Duration", value: "1 hour" }, { label: "Product price", value: "$1" }, ] ) end end context "when the purchase has variants and quantity" do let(:sizes_category) { create(:variant_category, title: "sizes", link: product) } let(:small_variant) { create(:variant, name: "small", price_difference_cents: 300, variant_category: sizes_category) } let(:colors_category) { create(:variant_category, title: "colors", link: product) } let(:red_variant) { create(:variant, name: "red", price_difference_cents: 300, variant_category: colors_category) } before do purchase.variant_attributes << small_variant purchase.variant_attributes << red_variant purchase.update!(quantity: 2) end it "returns general attributes with variant, price, and quantity" do expect(props[:general_attributes]).to eq( [ { label: "Variant", value: "small, red" }, { label: "Product price", value: "$7.49" }, { label: "Quantity", value: 2 } ] ) end context "when the purchase is free" do before do expect_any_instance_of(Purchase).to receive(:free_purchase?).and_return(true) end it "returns general attributes with variant and quantity and no product price" do expect(props[:general_attributes]).to eq( [ { label: "Variant", value: "small, red" }, { label: "Quantity", value: 2 } ] ) end end context "when the purchase is a coffee purchase" do before { purchase.link.update!(native_type: Link::NATIVE_TYPE_COFFEE) } it "returns general attributes including donation and excluding variant and quantity" do expect(props[:general_attributes]).to eq( [{ label: "Donation", value: "$7.49" }] ) end end context "when the purchase has a license" do include_context "when the purchase has a license" it "returns general attributes with variant, price, and quantity" do expect(props[:general_attributes]).to eq( [ { label: "Variant", value: "small, red" }, { label: "Product price", value: "$7.49" }, { label: "Quantity", value: 2 } ] ) end context "when the purchase is a multi-seat license" do before do allow_any_instance_of(Purchase).to receive(:is_multiseat_license?).and_return(true) end it "returns quantity as seats" do expect(props[:general_attributes]).to eq( [ { label: "Variant", value: "small, red" }, { label: "Product price", value: "$7.49" }, { label: "Number of seats", value: 2 } ] ) end end context "when the purchase contains only one quantity" do before do purchase.update!(quantity: 1) end it "returns general attributes with variant and product price only" do expect(props[:general_attributes]).to eq( [ { label: "Variant", value: "small, red" }, { label: "Product price", value: "$14.99" }, ] ) end end end end context "when the purchase is bundle" do let(:bundle) { create(:product, user: seller, is_bundle: true, name: "Bundle product") } let(:purchase) { create(:purchase, link: bundle) } let!(:product) { create(:product, user: seller, name: "Product") } let!(:bundle_product) { create(:bundle_product, bundle:, product:) } before do purchase.create_artifacts_and_send_receipt! end it "returns bundle attribute" do presenter = described_class.new(purchase.product_purchases.last) expect(presenter.props[:general_attributes]).to eq( [ { label: "Bundle", value: link_to("Bundle product", bundle.long_url, target: "_blank") }, ] ) end end end context "when the purchase is for a membership" do let(:purchase) do create( :membership_purchase, link: product, price_cents: 1_998, created_at: DateTime.parse("January 1, 2023") ) end it "returns general attributes with variant" do end context "when the purchase has quantity" do before do purchase.update!(quantity: 2) end it "returns general attributes with variant, price and quantity" do expect(props[:general_attributes]).to eq( [ { label: "Product price", value: "$9.99" }, { label: "Quantity", value: 2 } ] ) end end end context "without custom_fields" do it "returns product price only" do expect(props[:general_attributes]).to eq( [ { label: "Product price", value: "$14.99" }, ] ) end end context "with custom fields" do before do purchase.purchase_custom_fields << [ build(:purchase_custom_field, field_type: CustomField::TYPE_TERMS, name: "https://example.com/terms", value: "true"), build(:purchase_custom_field, field_type: CustomField::TYPE_CHECKBOX, name: "Want free swag?", value: "true"), build(:purchase_custom_field, field_type: CustomField::TYPE_CHECKBOX, name: "Sure you want free swag?", value: nil), build(:purchase_custom_field, field_type: CustomField::TYPE_TEXT, name: "Address", value: "123 Main St") ] end it "includes correct custom fields" do expect(props[:general_attributes]).to eq( [ { label: "Product price", value: "$14.99" }, { label: "Terms and Conditions", value: '<a target="_blank" href="https://example.com/terms">https://example.com/terms</a>' }, { label: "Want free swag?", value: "Yes" }, { label: "Sure you want free swag?", value: "No" }, { label: "Address", value: "123 Main St" } ] ) end end context "when the purchase has a tip" do before { purchase.create_tip!(value_cents: 500) } it "includes tip price attribute" do expect(props[:general_attributes]).to include( { label: "Tip", value: "$5" } ) end end end describe "#refund_policy_attribute" do context "when the purchase doesn't have a refund policy" do it "returns product price only" do expect(props[:general_attributes]).to eq( [ { label: "Product price", value: "$14.99" }, ] ) end end context "when the purchase has a refund policy" do before do purchase.create_purchase_refund_policy!( title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30, fine_print: "This is the fine print of the refund policy." ) end it "includes refund policy attribute" do expect(props[:general_attributes]).to eq( [ { label: "Product price", value: "$14.99" }, { label: "30-day money back guarantee", value: "This is the fine print of the refund policy." }, ] ) end end context "when the purchase is a gift receiver purchase" do let(:gift) { create(:gift, gift_note: "Hope you like it!", giftee_email: "giftee@example.com") } 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) } before do gifter_purchase.create_purchase_refund_policy!( title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30, fine_print: "This is the fine print of the refund policy." ) end it "uses gifter_purchase's refund policy" do expect(item_info.send(:purchase)).to eq(gift.giftee_purchase) expect(props[:general_attributes]).to eq( [ { label: "Product price", value: "$1" }, { label: "30-day money back guarantee", value: "This is the fine print of the refund policy." }, ] ) end end context "when the purchase is a bundle product purchase" do let(:bundle) { create(:product, user: seller, is_bundle: true, name: "Bundle product") } let(:purchase) { create(:purchase, link: bundle, seller:) } let!(:product) { create(:product, user: seller, name: "Product") } let!(:bundle_product) { create(:bundle_product, bundle:, product:) } before do purchase.create_purchase_refund_policy!( title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30, fine_print: "Bundle fine print." ) purchase.create_artifacts_and_send_receipt! end it "uses the bundle purchase's refund policy" do presenter = described_class.new(purchase.product_purchases.last) expect(presenter.props[:general_attributes]).to eq( [ { label: "Bundle", value: link_to("Bundle product", bundle.long_url, target: "_blank") }, { label: "30-day money back guarantee", value: "Bundle fine print." }, ] ) end end context "when the purchase is a bundle gift receiver purchase" do let(:bundle) { create(:product, user: seller, is_bundle: true, name: "Bundle product") } let(:gift) { create(:gift, gift_note: "Hope you like it!", giftee_email: "giftee@example.com", link: bundle) } let(:gifter_purchase) { create(:purchase, link: bundle, seller:, gift_given: gift, is_gift_sender_purchase: true) } let(:purchase) { create(:purchase, link: bundle, seller:, gift_received: gift, is_gift_receiver_purchase: true) } let!(:product) { create(:product, user: seller, name: "Product") } let!(:bundle_product) { create(:bundle_product, bundle:, product:) } before do gifter_purchase.create_purchase_refund_policy!( title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30, fine_print: "Bundle gift fine print." ) purchase.create_artifacts_and_send_receipt! end it "uses the gifter bundle purchase's refund policy" do presenter = described_class.new(purchase.product_purchases.last) expect(presenter.props[:general_attributes]).to eq( [ { label: "Bundle", value: link_to("Bundle product", bundle.long_url, target: "_blank") }, { label: "30-day money back guarantee", value: "Bundle gift fine print." }, ] ) end end end describe "#refund_policy_attribute" do context "when the purchase doesn't have a refund policy" do it "returns product price only" do expect(props[:general_attributes]).to eq( [ { label: "Product price", value: "$14.99" }, ] ) end end context "when the purchase has a refund policy" do before do purchase.create_purchase_refund_policy!( title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30, fine_print: "This is the fine print of the refund policy." ) end it "includes refund policy attribute" do expect(props[:general_attributes]).to eq( [ { label: "Product price", value: "$14.99" }, { label: "30-day money back guarantee", value: "This is the fine print of the refund policy." }, ] ) end end context "when the purchase is a gift receiver purchase" do let(:gift) { create(:gift, gift_note: "Hope you like it!", giftee_email: "giftee@example.com") } 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) } before do gifter_purchase.create_purchase_refund_policy!( title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30, fine_print: "This is the fine print of the refund policy." ) end it "uses gifter_purchase's refund policy" do expect(item_info.send(:purchase)).to eq(gift.giftee_purchase) expect(props[:general_attributes]).to eq( [ { label: "Product price", value: "$1" }, { label: "30-day money back guarantee", value: "This is the fine print of the refund policy." }, ] ) end end end describe "manage_subscription_note" do context "when the purchase is not a subscription" do it "returns nil" do expect(props[:manage_subscription_note]).to be_nil end end context "when the purchase is a membership" do let(:product) { create(:membership_product) } let(:purchase) { create(:membership_purchase, link: product, total_transaction_cents: 1_499) } it "returns subscription note" do url = Rails.application.routes.url_helpers.manage_subscription_url( purchase.subscription.external_id, host: UrlService.domain_with_protocol, ) expect(props[:manage_subscription_note]).to eq( "You will be charged once a month. If you would like to manage your membership you can visit " \ "<a target=\"_blank\" href=\"#{url}\">subscription settings</a>." ) end context "when not used in an email" do let(:for_email) { false } it "requires email confirmation in the subscription settings link" do url = Rails.application.routes.url_helpers.manage_subscription_url( purchase.subscription.external_id, host: UrlService.domain_with_protocol, ) expect(props[:manage_subscription_note]).to eq( "You will be charged once a month. If you would like to manage your membership you can visit " \ "<a target=\"_blank\" href=\"#{url}\">subscription settings</a>." ) end end context "when the subscription is a gift" do before do allow(purchase.subscription).to receive(:gift?).and_return(true) allow(purchase).to receive(:giftee_name_or_email).and_return("giftee@gumroad.com") end context "when the purchase is a gift sender purchase" do it "returns gift subscription note" do note = "Note that giftee@gumroad.com’s membership will not automatically renew." expect(props[:manage_subscription_note]).to eq(note) end end context "when the purchase is a gift receiver purchase" do let(:gift) { create(:gift, gift_note: "Gift note") } 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 nil" do expect(props[:manage_subscription_note]).to be_nil end end end end context "when the purchase is an installment plan" do it "returns the installment plan manage note with dates and link" do travel_to(Time.zone.parse("2025-03-14")) product_installment_plan = create( :product_installment_plan, number_of_installments: 5, recurrence: "monthly", ) purchase = create(:installment_plan_purchase, link: product_installment_plan.link) subscription = purchase.subscription props = described_class.new(purchase).props url = Rails.application.routes.url_helpers.manage_subscription_url( subscription.external_id, host: UrlService.domain_with_protocol, ) expect(props[:manage_subscription_note]).to eq( "Installment plan initiated on Mar 14, 2025. " \ "Your final charge will be on Aug 14, 2025. " \ "You can manage your payment settings <a target=\"_blank\" href=\"#{url}\">here</a>." ) end end end describe "commission deposit purchase", :vcr do let(:purchase) { create(:commission_deposit_purchase) } let(:item_info) { described_class.new(purchase) } before do purchase.create_artifacts_and_send_receipt! purchase.reload end it "returns the correct product price" do props = item_info.props expect(props[:general_attributes]).to include( { label: "Product price", value: "$2" } ) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/receipt_presenter/mail_subject_spec.rb
spec/presenters/receipt_presenter/mail_subject_spec.rb
# frozen_string_literal: true require "spec_helper" describe ReceiptPresenter::MailSubject, :vcr do let(:product_one) { create(:product, name: "Product One") } let(:purchase_one) { create(:purchase, link: product_one) } let(:charge) { create(:charge, purchases: [purchase_one]) } let(:mail_subject) { described_class.build(chargeable) } describe ".build" do describe "with one purchase" do RSpec.shared_examples "one purchase mail subject" do it "returns expected subject" do expect(mail_subject).to eq("You bought Product One!") end context "when the purchase is free" do let(:purchase_one) { create(:free_purchase) } it "returns free purchase subject" do expect(mail_subject).to eq("You got The Works of Edgar Gumstein!") end end context "when the purchase is a rental" do before { purchase_one.update!(is_rental: true) } it "returns rental purchase subject" do expect(mail_subject).to eq("You rented Product One!") end end context "when the purchase is for a subscription" do let(:product_one) { create(:membership_product, name: "Product One") } let(:purchase_one) { create(:membership_purchase, link: product_one) } it "returns subscription purchase subject" do expect(mail_subject).to eq("You've subscribed to Product One!") end context "when the purchase subscription is recurring" do before { purchase_one.update!(is_original_subscription_purchase: false) } it "returns recurring subscription purchase subject" do expect(mail_subject).to eq("Recurring charge for Product One.") end end context "when the purchase subscription is an upgrade" do before do purchase_one.update!( is_original_subscription_purchase: false, is_upgrade_purchase: true ) end it "returns upgrade subscription subject" do expect(mail_subject).to eq("You've upgraded your membership for Product One!") end end end context "when the purchase is a gift" do let(:gift) do create( :gift, link: product_one, gifter_email: "gifter@example.com", giftee_email: "giftee@example.com" ) end context "when is gift receiver purchase" do let(:purchase_one) do create( :purchase, link: gift.link, gift_received: gift, is_gift_receiver_purchase: true, ) end it "returns gift receiver purchase subject" do expect(mail_subject).to eq("gifter@example.com bought Product One for you!") end context "when the gifter has provided a name" do before { purchase_one.update!(full_name: "Gifter Name") } it "returns gift receiver purchase subject with gifter name" do expect(mail_subject).to eq("Gifter Name (gifter@example.com) bought Product One for you!") end end end context "when is gift sender purchase" do before do purchase_one.update!(is_gift_sender_purchase: true, gift_given: gift) end it "returns gift sender purchase subject" do expect(mail_subject).to eq("You bought giftee@example.com Product One!") end end context "when the purchase is a commission completion purchase" do before { purchase_one.update!(is_commission_completion_purchase: true) } it "returns commission completion purchase subject" do expect(mail_subject).to eq("Product One is ready for download!") end end end end context "when chargeable is a Purchase" do let(:chargeable) { purchase_one } it_behaves_like "one purchase mail subject" end context "when chargeable is a Charge" do let(:chargeable) { charge } it_behaves_like "one purchase mail subject" end end describe "with two purchases" do let(:product_two) { create(:product, name: "Product Two") } let(:purchase_two) { create(:purchase, link: product_two) } let(:chargeable) { charge } before do charge.purchases << purchase_two end it "returns subject for two purchases" do expect(mail_subject).to eq("You bought Product One and Product Two") end end describe "with more than two purchases" do let(:product_two) { create(:product, name: "Product Two") } let(:purchase_two) { create(:purchase, link: product_two) } let(:product_three) { create(:product, name: "Product Three") } let(:purchase_three) { create(:purchase, link: product_three) } let(:chargeable) { charge } before do charge.purchases << purchase_two charge.purchases << purchase_three end it "returns subject for more than two purchases" do expect(mail_subject).to eq("You bought Product One and 2 more products") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/receipt_presenter/shipping_info_spec.rb
spec/presenters/receipt_presenter/shipping_info_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/receipt_presenter_concern" describe ReceiptPresenter::ShippingInfo do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:purchase) do create( :purchase, link: product, seller:, price_cents: 1_499, created_at: DateTime.parse("January 1, 2023") ) end let(:presenter) { described_class.new(chargeable) } RSpec.shared_examples "for a Chargeable" do describe ".new" do it "assigns instance variable" do expect(presenter.send(:chargeable)).to eq(chargeable) end end it "returns correct title" do expect(presenter.title).to eq("Shipping info") end describe "#attributes" do let(:attributes) { presenter.attributes } context "when the purchase is for a physical product" do include_context "when the purchase is for a physical product" let(:purchase_shipping_attributes) do { full_name: "Edgar Gumstein", street_address: "123 Gum Road", country: "United States", state: "CA", zip_code: "94107", city: "San Francisco", } end before do purchase.link.update!(require_shipping: true) purchase.update!(**purchase_shipping_attributes) end it "includes shipping attributes" do expect(attributes).to eq( [ { label: "Shipping to", value: "Edgar Gumstein" }, { label: "Shipping address", value: "123 Gum Road<br>San Francisco, CA 94107<br>United States" } ] ) end end context "when the purchase is not for a physical product" do it "it returns empty shipping attributes" do expect(attributes).to eq([]) end end end end describe "for a Purchase" do let(:chargeable) { purchase } include_examples "for a Chargeable" end describe "for a Charge", :vcr do let(:charge) { create(:charge, purchases: [purchase]) } let(:chargeable) { charge } include_examples "for a Chargeable" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/receipt_presenter/charge_info_spec.rb
spec/presenters/receipt_presenter/charge_info_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/receipt_presenter_concern" describe ReceiptPresenter::ChargeInfo do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:purchase) do create( :purchase, link: product, seller:, price_cents: 14_99, created_at: DateTime.parse("January 1, 2023") ) end let(:presenter) { described_class.new(chargeable, for_email: true, order_items_count: 1) } RSpec.shared_examples "chargeable" do describe "#formatted_created_at" do it "returns the formatted date" do expect(presenter.formatted_created_at).to eq("Jan 1, 2023") end end describe "#formatted_total_transaction_amount" do before do allow(chargeable).to receive(:charged_amount_cents).and_return(14_99) end context "when the purchase is not a membership" do it "returns formatted amount" do expect(presenter.formatted_total_transaction_amount).to eq("$14.99") end end end describe "#order_id" do it "returns the external_id_for_invoice" do expect(presenter.order_id).to eq(chargeable.external_id_for_invoice) end end describe "#product_questions_note" do it "returns note with reply" do expect(presenter.product_questions_note).to eq( "Questions about your product? Contact Seller by replying to this email." ) end context "when is not for email" do let(:presenter) { described_class.new(purchase, for_email: false, order_items_count: 1) } it "returns text with seller's email, if there is no product-level support email" do product.update!(support_email: nil) expect(presenter.product_questions_note).to eq(<<~HTML.squish) Questions about your product? Contact Seller at <a href="mailto:seller@example.com">seller@example.com</a>. HTML end it "returns text with product support email, when there is a product-level support email" do product.update!(support_email: "support@product.com") expect(presenter.product_questions_note).to eq(<<~HTML.squish) Questions about your product? Contact Seller at <a href="mailto:support@product.com">support@product.com</a>. HTML end end context "when the seller name contains HTML" do let(:seller) { create(:named_seller, name: "<script>alert('xss')</script>") } it "escapes the seller name for email" do expect(presenter.product_questions_note).to include( "Contact &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt; by replying to this email." ) end it "escapes the seller name for non-email" do presenter = described_class.new(chargeable, for_email: false, order_items_count: 1) expect(presenter.product_questions_note).to include( "Contact &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt; at" ) end end context "when is a gift sender purchase" do include_context "when is a gift sender purchase" RSpec.shared_examples "no product questions note for gift sender" do it "returns nil" do expect(presenter.product_questions_note).to be_nil end end describe "for a Purchase" do it_behaves_like "no product questions note for gift sender" end describe "for a Charge" do let(:charge) { create(:charge) } let(:payment_info) { described_class.new(charge) } let(:presenter) { described_class.new(charge, for_email: true, order_items_count: 1) } before do charge.purchases << purchase charge.order.purchases << purchase end it_behaves_like "no product questions note for gift sender" context "with multiple purchases" do let(:second_purchase) { create(:purchase) } before do charge.purchases << second_purchase charge.order.purchases << second_purchase end it_behaves_like "no product questions note for gift sender" end end end end end describe "for Purchase" do let(:chargeable) { purchase } it_behaves_like "chargeable" end describe "for Charge" do let(:charge) { create(:charge, seller:, purchases: [purchase], amount_cents: 14_99) } let!(:order) { charge.order } let(:chargeable) { charge } before do order.purchases << purchase order.update!(created_at: DateTime.parse("January 1, 2023")) end it_behaves_like "chargeable" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/receipt_presenter/footer_info_spec.rb
spec/presenters/receipt_presenter/footer_info_spec.rb
# frozen_string_literal: true require "spec_helper" describe ReceiptPresenter::FooterInfo, :vcr do include ActionView::Helpers::UrlHelper let(:product) { create(:membership_product) } let(:purchase) { create(:membership_purchase, email: "customer@example.com", link: product) } let(:for_email) { true } let(:presenter) { described_class.new(chargeable) } describe "#can_manage_subscription?" do context "when product is a recurring billing" do context "when chargeable is a Purchase" do let(:chargeable) { purchase } it "returns true" do expect(presenter.can_manage_subscription?).to be(true) end context "when is a receipt for gift receiver" do let(:gift) { create(:gift, link: product) } before do purchase.update!(gift_received: gift, is_gift_receiver_purchase: true) end it "returns false" do expect(presenter.can_manage_subscription?).to be(false) end end context "when is a receipt for gift sender" do let(:gift) { create(:gift, link: product) } before do purchase.update!(gift_given: gift, is_gift_sender_purchase: true) end it "returns false" do expect(presenter.can_manage_subscription?).to be(false) end end end context "when chargeable is a Charge" do let(:chargeable) { create(:charge, purchases: [purchase]) } it "returns false" do expect(presenter.can_manage_subscription?).to be(false) end end end end describe "#manage_subscription_note" do let(:chargeable) { purchase } it "returns expected text" do expect(presenter.manage_subscription_note).to eq("You'll be charged once a month.") end end describe "#manage_subscription_link" do let(:chargeable) { purchase } let(:expected_url) do Rails.application.routes.url_helpers.manage_subscription_url( purchase.subscription.external_id, host: UrlService.domain_with_protocol, ) end it "returns the expected link" do expect(presenter.manage_subscription_link).to include("Manage membership") expect(presenter.manage_subscription_link).to include(expected_url) end end describe "#unsubscribe_link" do let(:chargeable) { purchase } it "returns the expected link" do allow_any_instance_of(Purchase).to receive(:secure_external_id).and_return("sample-secure-id") expected_url = Rails.application.routes.url_helpers.unsubscribe_purchase_url( "sample-secure-id", host: UrlService.domain_with_protocol, ) expect(presenter.unsubscribe_link).to include("Unsubscribe") expect(presenter.unsubscribe_link).to include(expected_url) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/receipt_presenter/recommended_products_info_spec.rb
spec/presenters/receipt_presenter/recommended_products_info_spec.rb
# frozen_string_literal: true require "spec_helper" describe ReceiptPresenter::RecommendedProductsInfo do let(:purchaser) { create(:user) } let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller, name: "Digital product") } let(:purchase) do create( :purchase, link: product, seller:, price_cents: 1_499, created_at: DateTime.parse("January 1, 2023") ) end let(:recommended_products_info) { described_class.new(chargeable) } RSpec.shared_examples "chargeable" do it "returns correct title" do expect(recommended_products_info.title).to eq("Customers who bought this item also bought") end describe "#products" do RSpec.shared_examples "doesn't return products" do it "doesn't return products" do expect(RecommendedProductsService).not_to receive(:for_checkout) expect(recommended_products_info.products).to eq([]) expect(recommended_products_info.present?).to eq(false) end end context "when the purchase doesn't have a purchaser" do it_behaves_like "doesn't return products" end context "when the purchase has a purchaser" do before do purchase.update!(purchaser:) end context "when the feature is active" do let(:recommendable_product) { create(:product, :recommendable, name: "Recommended product") } let!(:affiliate) do create( :direct_affiliate, seller: recommendable_product.user, products: [recommendable_product], affiliate_user: create(:user) ) end before do seller.update!(recommendation_type: User::RecommendationType::GUMROAD_AFFILIATES_PRODUCTS) end context "with a regular purchase" do it "calls RecommendedProductsService with correct args" do expect(RecommendedProducts::CheckoutService).to receive(:fetch_for_receipt).with( purchaser: purchase.purchaser, receipt_product_ids: [purchase.link.id], recommender_model_name: "sales", limit: ReceiptPresenter::RecommendedProductsInfo::RECOMMENDED_PRODUCTS_LIMIT, ).and_call_original expect(RecommendedProductsService).to receive(:fetch).with( { model: "sales", ids: [purchase.link.id], exclude_ids: [purchase.link.id], number_of_results: RecommendedProducts::BaseService::NUMBER_OF_RESULTS, user_ids: nil, } ).and_return(Link.where(id: [recommendable_product.id])) expect(recommended_products_info.products.size).to eq(1) expect(recommended_products_info.present?).to eq(true) product_card = recommended_products_info.products.first expect(product_card[:name]).to eq(recommendable_product.name) expect(product_card[:url]).to include("affiliate_id=#{seller.global_affiliate.external_id_numeric}") expect(product_card[:url]).to include("layout=profile") expect(product_card[:url]).to include("recommended_by=receipt") expect(product_card[:url]).to include("recommender_model_name=sales") end end context "with a bundle purchase" do let(:purchase) { create(:purchase, link: create(:product, :bundle)) } before do purchase.create_artifacts_and_send_receipt! end it "calls RecommendedProductsService with correct args" do expect(RecommendedProducts::CheckoutService).to receive(:fetch_for_receipt).with( purchaser: purchase.purchaser, receipt_product_ids: [purchase.link_id] + purchase.link.bundle_products.map(&:product_id), recommender_model_name: "sales", limit: ReceiptPresenter::RecommendedProductsInfo::RECOMMENDED_PRODUCTS_LIMIT, ).and_call_original expect(recommended_products_info.products).to eq([]) expect(recommended_products_info.present?).to eq(false) end end end end end end describe "for Purchase" do let(:chargeable) { purchase } it_behaves_like "chargeable" end describe "for Charge", :vcr do let(:charge) { create(:charge, seller:, purchases: [purchase]) } let!(:order) { charge.order } let(:chargeable) { charge } before do order.purchases << purchase end it_behaves_like "chargeable" context "with multiple purchases" do let(:another_product) { create(:product, user: seller) } let(:another_purchase) { create(:purchase, link: another_product, seller:) } let(:recommendable_product) { create(:product, :recommendable, name: "Recommended product") } let!(:affiliate) do create( :direct_affiliate, seller: recommendable_product.user, products: [recommendable_product], affiliate_user: create(:user) ) end before do purchase.update!(purchaser:) another_purchase.update!(purchaser:) seller.update!(recommendation_type: User::RecommendationType::GUMROAD_AFFILIATES_PRODUCTS) charge.purchases << another_purchase order.purchases << another_purchase end describe "#products" do it "calls RecommendedProductsService with correct args" do expect(RecommendedProducts::CheckoutService).to receive(:fetch_for_receipt).with( purchaser: purchase.purchaser, receipt_product_ids: [purchase.link_id, another_purchase.link_id], recommender_model_name: "sales", limit: ReceiptPresenter::RecommendedProductsInfo::RECOMMENDED_PRODUCTS_LIMIT, ).and_call_original expect(recommended_products_info.products).to eq([]) expect(recommended_products_info.present?).to eq(false) end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/receipt_presenter/giftee_manage_subscription_spec.rb
spec/presenters/receipt_presenter/giftee_manage_subscription_spec.rb
# frozen_string_literal: true require "spec_helper" describe ReceiptPresenter::GifteeManageSubscription do let(:chargeable) { create(:membership_purchase, gift_received: create(:gift), is_gift_receiver_purchase: true) } let(:subscription) { chargeable.subscription } let(:presenter) { described_class.new(chargeable) } describe "#note" do let(:expected_url) do Rails.application.routes.url_helpers.manage_subscription_url( subscription.external_id, host: UrlService.domain_with_protocol, ) end context "when the chargeable is not a purchase" do let(:chargeable) { create(:charge) } it "returns nil" do expect(presenter.note).to be_nil end end context "when the subscription is not a gift" do before do chargeable.update!(is_gift_receiver_purchase: false) end it "returns nil" do expect(presenter.note).to be_nil end end context "when the chargeable is a subscription and gift" do before do chargeable.update!(is_gift_receiver_purchase: true) create(:membership_purchase, gift_given: chargeable.gift_received, is_gift_sender_purchase: true, subscription:) end it "returns the expected note" do expect(presenter.note).to eq( "Your gift includes a 1-month membership. If you wish to continue your membership, you can visit <a target=\"_blank\" href=\"#{expected_url}\">subscription settings</a>." ) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/presenters/post/social_image_spec.rb
spec/presenters/post/social_image_spec.rb
# frozen_string_literal: true describe Post::SocialImage do it "parses the embedded image correctly" do content_with_one_image = <<~HTML <p>First paragraph</p> <figure> <img src="path/to/image.jpg"> <p class="figcaption">Image description</p> </figure> <p>Second paragraph</p> HTML social_image = Post::SocialImage.for(content_with_one_image) expect(social_image.url).to eq("path/to/image.jpg") expect(social_image.caption).to eq("Image description") expect(social_image.blank?).to be_falsey end context "when image is an ActiveStorage upload" do it "sets the full social image URL" do content_with_one_image = <<~HTML <p>First paragraph</p> <figure> <img src="#{AWS_S3_ENDPOINT}/#{PUBLIC_STORAGE_S3_BUCKET}/blobKey"> <p class="figcaption">Image description</p> </figure> <p>Second paragraph</p> HTML social_image = Post::SocialImage.for(content_with_one_image) expect(social_image.url).to eq("#{AWS_S3_ENDPOINT}/#{PUBLIC_STORAGE_S3_BUCKET}/blobKey") end end context "when no embedded image" do it "is blank" do social_image = Post::SocialImage.for("<p>hi!</p>") expect(social_image.url).to be_blank expect(social_image.caption).to be_blank expect(social_image.blank?).to be_truthy end end context "when multiple embedded images" do it "uses the first image" do content_with_one_image = <<~HTML <figure> <img src="path/to/first_image.jpg"> <p class="figcaption">First image description</p> </figure> <figure> <img src="path/to/second_image.jpg"> <p class="figcaption">Second image description</p> </figure> HTML social_image = Post::SocialImage.for(content_with_one_image) expect(social_image.url).to eq("path/to/first_image.jpg") expect(social_image.caption).to eq("First image description") end context "when first image has no caption, but second image has a caption" do it "does not use second image's caption" do content_with_one_image = <<~HTML <figure> <img src="path/to/first_image.jpg"> </figure> <figure> <img src="path/to/second_image.jpg"> <p class="figcaption">Second image description</p> </figure> HTML social_image = Post::SocialImage.for(content_with_one_image) expect(social_image.url).to eq("path/to/first_image.jpg") expect(social_image.caption).to be_blank end end end context "when different media types are embedded" do it "ignores non-image embeds" do content_with_one_image = <<~HTML <figure> <iframe src="embedded_tweet"/> </figure> <figure> <img src="path/to/image.jpg"> <p class="figcaption">Image description</p> </figure> HTML social_image = Post::SocialImage.for(content_with_one_image) expect(social_image.url).to eq("path/to/image.jpg") expect(social_image.caption).to eq("Image description") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/team_memberships_spec.rb
spec/requests/team_memberships_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Team Memberships", type: :system, js: true do describe "Account switch" do context "with logged in user" do let(:user) { create(:user, name: "Gum") } before do create(:user_compliance_info, user:) login_as user end context "with one team memberships" do let(:seller) { create(:user, name: "Joe") } before do create(:user_compliance_info, user: seller, first_name: "Joey") create(:team_membership, user:, seller:) end it "switches account to seller" do visit products_path within "nav[aria-label='Main']" do toggle_disclosure("Gum") choose("Joe") wait_for_ajax expect(page).to have_text(seller.display_name) end expect(page).to have_text("Products") end context "accessing a restricted page" do it "redirects to the dashboard" do visit settings_password_path within "nav[aria-label='Main']" do toggle_disclosure("Gum") choose("Joe") wait_for_ajax expect(page).to have_text(seller.display_name) end expect(page).not_to have_alert(text: "Your current role as Admin cannot perform this action.") expect(page.current_path).to eq(dashboard_path) 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/requests/collaborations_spec.rb
spec/requests/collaborations_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Collaborations", type: :system, js: true do let(:seller_1) { create(:user) } let(:seller_2) { create(:user) } let(:seller_3) { create(:user) } let(:seller_1_product_1) { create(:product, user: seller_1, name: "First product") } let(:seller_1_product_2) { create(:product, user: seller_1, name: "Second product") } let(:seller_2_product_1) { create(:product, user: seller_2, name: "Third product") } let(:seller_2_product_2) { create(:product, user: seller_2, name: "Fourth product") } let(:seller_3_product_1) { create(:product, user: seller_3, name: "Fifth product") } let(:collaborator_1) do create(:collaborator, seller: seller_1, affiliate_user:).tap do |collaborator| collaborator.product_affiliates.create!( product: seller_1_product_1, affiliate_basis_points: 50_00 ) collaborator.product_affiliates.create!( product: seller_1_product_2, affiliate_basis_points: 35_00 ) end end let(:collaborator_2) do create(:collaborator, seller: seller_2, affiliate_user:).tap do |collaborator| collaborator.product_affiliates.create!( product: seller_2_product_1, affiliate_basis_points: 50_00 ) collaborator.product_affiliates.create!( product: seller_2_product_2, affiliate_basis_points: 35_00 ) end end let(:collaborator_3_pending) do create( :collaborator, :with_pending_invitation, seller: seller_3, affiliate_user: ).tap do |collaborator| collaborator.product_affiliates.create!( product: seller_3_product_1, affiliate_basis_points: 20_00 ) end end describe "seller view" do let(:affiliate_user) { create(:user) } before { login_as affiliate_user } context "viewing collaborations" do it "only shows the tabs when there are collaborations" do visit collaborators_path expect(page).to_not have_tab_button("Collaborators") expect(page).to_not have_tab_button("Collaborations") collaborator_1 visit collaborators_path expect(page).to have_tab_button("Collaborators") expect(page).to have_tab_button("Collaborations") end it "displays a list of collaborators" do collaborator_1 collaborator_2 collaborator_3_pending visit collaborators_incomings_path [ { "Name" => collaborator_1.seller.username, "Products" => "2 products", "Your cut" => "35% - 50%", "Status" => "Accepted" }, { "Name" => collaborator_2.seller.username, "Products" => "2 products", "Your cut" => "35% - 50%", "Status" => "Accepted" }, { "Name" => collaborator_3_pending.seller.username, "Products" => seller_3_product_1.name, "Your cut" => "20%", "Status" => "Pending" }, ].each do |row| expect(page).to have_table_row(row) end end end context "invitations" do it "allows accepting an invitation" do collaborator_3_pending visit collaborators_incomings_path expect(page).to have_table_row( { "Name" => collaborator_3_pending.seller.username, "Status" => "Pending" } ) within find(:table_row, { "Name" => collaborator_3_pending.seller.username }) do click_on "Accept" end expect(page).to have_alert(text: "Invitation accepted") expect(page).to have_table_row( { "Name" => collaborator_3_pending.seller.username, "Status" => "Accepted" } ) end it "allows declining an invitation" do collaborator_3_pending visit collaborators_incomings_path expect(page).to have_table_row( { "Name" => collaborator_3_pending.seller.username, "Status" => "Pending" } ) within find(:table_row, { "Name" => collaborator_3_pending.seller.username }) do click_on "Decline" end expect(page).to have_alert(text: "Invitation declined") expect(page).to_not have_table_row({ "Name" => collaborator_3_pending.seller.username }) expect(page).to have_text("No collaborations yet") end end context "removing a collaborator" do it "allows removing a collaborator" do collaborator_1 visit collaborators_incomings_path expect(page).to have_table_row( { "Name" => collaborator_1.seller.username, "Status" => "Accepted" } ) find(:table_row, { "Name" => collaborator_1.seller.username }).click within_modal collaborator_1.seller.username do click_on "Remove" end expect(page).to have_alert(text: "Collaborator removed") expect(page).to_not have_table_row({ "Name" => collaborator_1.seller.username }) expect(page).to have_text("No collaborations yet") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/widget_spec.rb
spec/requests/widget_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Widget Page scenario", js: true, type: :system do context "when no user is logged in" do before do @demo_product = create(:product, user: create(:named_user), unique_permalink: "demo") end it "allows to copy overlay code for the demo product" do visit("/widgets") expect(page).to have_field("Widget code", with: %(<script src="#{UrlService.root_domain_with_protocol}/js/gumroad.js"></script>\n<a class="gumroad-button" href="#{@demo_product.long_url}">Buy on</a>)) copy_button = find_button("Copy embed code") copy_button.hover expect(page).to have_content("Copy to Clipboard") copy_button.click expect(page).to have_content("Copied!") end it "allows creator to copy embed code of the product" do visit("/widgets") select_tab("Embed") expect(page).to have_field("Widget code", with: %(<script src="#{UrlService.root_domain_with_protocol}/js/gumroad-embed.js"></script>\n<div class="gumroad-product-embed"><a href="#{@demo_product.long_url}">Loading...</a></div>)) # wait for embed iframe to load, so no layout shift happens when hovering the copy button expect(page).to have_css("iframe[src*='embed=true'][style*='height']", wait: 10) copy_button = find_button("Copy embed code") copy_button.hover expect(page).to have_content("Copy to Clipboard") copy_button.click expect(page).to have_content("Copied!") end end context "when seller is logged in" do before :each do @creator = create(:affiliate_user) @product = create(:product, user: @creator) @affiliated_product = create(:product, name: "The Minimalist Entrepreneur") @direct_affiliate = create(:direct_affiliate, affiliate_user: @creator, seller: @affiliated_product.user, products: [@affiliated_product]) @base_url = UrlService.root_domain_with_protocol login_as(@creator) end it "allows creator to copy overlay code of the product" do visit("/widgets") within_section "Share your product", section_element: :section do expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad.js"></script>\n<a class="gumroad-button" href="#{@product.long_url}">Buy on</a>)) expect(page).not_to have_content("Copy to Clipboard") copy_button = find_button("Copy embed code") copy_button.hover expect(page).to have_content("Copy to Clipboard") copy_button.click expect(page).to have_content("Copied!") # Hover somewhere else to trigger mouseout first("textarea").hover expect(page).not_to have_content("Copy to Clipboard") expect(page).not_to have_content("Copied!") copy_button.hover expect(page).to have_content("Copy to Clipboard") end end it "allows creator to copy embed code of the product" do visit("/widgets") within_section "Share your product", section_element: :section do select_tab("Embed") expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad-embed.js"></script>\n<div class="gumroad-product-embed"><a href="#{@product.long_url}">Loading...</a></div>)) # wait for embed iframe to load, so no layout shift happens when hovering the copy button expect(page).to have_css("iframe[src*='embed=true'][style*='height']", wait: 10) copy_button = find_button("Copy embed code") expect(copy_button).not_to have_tooltip(text: "Copy to Clipboard") copy_button.hover expect(copy_button).to have_tooltip(text: "Copy to Clipboard") copy_button.click expect(page).to have_content("Copied!") # Hover somewhere else to trigger mouseout first("textarea").hover expect(page).not_to have_content("Copy to Clipboard") expect(page).not_to have_content("Copied!") copy_button.hover expect(copy_button).to have_tooltip(text: "Copy to Clipboard") end end it "allows creator to select products" do visit("/widgets") expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad.js"></script>\n<a class="gumroad-button" href="#{@product.long_url}">Buy on</a>)) select(@affiliated_product.name, from: "Choose your product") expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad.js"></script>\n<a class="gumroad-button" href="#{@direct_affiliate.referral_url_for_product(@affiliated_product)}">Buy on</a>)) select(@product.name, from: "Choose your product") expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad.js"></script>\n<a class="gumroad-button" href="#{@product.long_url}">Buy on</a>)) select_tab("Embed") expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad-embed.js"></script>\n<div class="gumroad-product-embed"><a href="#{@product.long_url}">Loading...</a></div>)) select(@affiliated_product.name, from: "Choose your product") expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad-embed.js"></script>\n<div class="gumroad-product-embed"><a href="#{@direct_affiliate.referral_url_for_product(@affiliated_product)}">Loading...</a></div>)) select(@product.name, from: "Choose your product") expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad-embed.js"></script>\n<div class="gumroad-product-embed"><a href="#{@product.long_url}">Loading...</a></div>)) end it "allows creator to configure the overlay settings" do visit("/widgets") expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad.js"></script>\n<a class="gumroad-button" href="#{@product.long_url}">Buy on</a>)) check "Send directly to checkout page" expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad.js"></script>\n<a class="gumroad-button" href="#{@product.long_url}" data-gumroad-overlay-checkout="true">Buy on</a>)) # Overlay code with custom text fill_in("Button text", with: "Custom Overlay Button Text") expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad.js"></script>\n<a class="gumroad-button" href="#{@product.long_url}" data-gumroad-overlay-checkout="true">Custom Overlay Button Text</a>)) uncheck "Send directly to checkout page" expect(page).to have_field("Widget code", with: %(<script src="#{@base_url}/js/gumroad.js"></script>\n<a class="gumroad-button" href="#{@product.long_url}">Custom Overlay Button Text</a>)) end context "when creator has an active custom domain that correctly points to our servers" do let!(:creator_custom_domain) { create(:custom_domain, user: @creator, state: "verified") } let!(:affiliated_product_creator_custom_domain) { create(:custom_domain, user: @direct_affiliate.seller, state: "verified") } let(:expected_base_url_for_affiliated_products) { @base_url } let(:expected_base_url_for_own_products) { "#{PROTOCOL}://#{creator_custom_domain.domain}" } before do creator_custom_domain.set_ssl_certificate_issued_at! affiliated_product_creator_custom_domain.set_ssl_certificate_issued_at! allow(CustomDomainVerificationService) .to receive(:new) .with(domain: creator_custom_domain.domain) .and_return(double(domains_pointed_to_gumroad: [creator_custom_domain.domain])) allow(CustomDomainVerificationService) .to receive(:new) .with(domain: affiliated_product_creator_custom_domain.domain) .and_return(double(domains_pointed_to_gumroad: [affiliated_product_creator_custom_domain.domain])) end it "shows widget installation codes with custom domain for own products and with root domain for affiliated products" do visit("/widgets") # Overlay code for own product expect(page).to have_field("Widget code", with: %(<script src="#{expected_base_url_for_own_products}/js/gumroad.js"></script>\n<a class="gumroad-button" href="#{short_link_url(@product, host: expected_base_url_for_own_products)}">Buy on</a>)) # Overlay code for an affiliated product select(@affiliated_product.name, from: "Choose your product") expect(page).to have_field("Widget code", with: %(<script src="#{expected_base_url_for_affiliated_products}/js/gumroad.js"></script>\n<a class="gumroad-button" href="#{@direct_affiliate.referral_url_for_product(@affiliated_product)}">Buy on</a>)) select_tab("Embed") # Embed code for an affiliated product expect(page).to have_field("Widget code", with: %(<script src="#{expected_base_url_for_affiliated_products}/js/gumroad-embed.js"></script>\n<div class="gumroad-product-embed"><a href="#{@direct_affiliate.referral_url_for_product(@affiliated_product)}">Loading...</a></div>)) # Embed code for own product select(@product.name, from: "Choose your product") expect(page).to have_field("Widget code", with: %(<script src="#{expected_base_url_for_own_products}/js/gumroad-embed.js"></script>\n<div class="gumroad-product-embed"><a href="#{short_link_url(@product, host: expected_base_url_for_own_products)}">Loading...</a></div>)) end end end describe "Subscribe form" do let(:seller) { create(:named_seller) } let!(:product) { create(:product, user: seller) } context "with seller as logged_in_user" do before do login_as(seller) end context "with seller as current_seller" do it "allows copying the follow page URL" do visit widgets_path copy_button = find_button("Copy link") copy_button.hover expect(copy_button).to have_tooltip(text: "Copy link") copy_button.click expect(copy_button).to have_tooltip(text: "Copied!") end it "allows copying the follow form embed HTML" do visit widgets_path within_section "Subscribe form", section_element: :section do expect(page).to have_field("Subscribe form embed code", text: seller.external_id) copy_button = find_button("Copy embed code") copy_button.hover expect(copy_button).to have_tooltip(text: "Copy to Clipboard") copy_button.click expect(copy_button).to have_tooltip(text: "Copied!") end end it "allows previewing follow form embed" do visit widgets_path within_section "Subscribe form", section_element: :section do fill_in "Your email address", with: "test@gumroad.com" click_on "Follow" end wait_for_ajax expect(seller.reload.followers.last.email).to eq("test@gumroad.com") end end end context "with switching account to user as admin for seller" do include_context "with switching account to user as admin for seller" it "uses seller's external id" do visit widgets_path within_section "Subscribe form", section_element: :section do expect(page).to have_field("Subscribe form embed code", text: seller.external_id) end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/dashboard_mobile_table_spec.rb
spec/requests/dashboard_mobile_table_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Dashboard - Mobile Table Labels", type: :system, js: true, mobile_view: true do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller, name: "Test eBook", price_cents: 1000) } let!(:purchase_1) { create(:purchase_in_progress, seller: seller, link: product) } let!(:purchase_2) { create(:purchase_in_progress, seller: seller, link: product) } let!(:purchase_3) { create(:purchase_in_progress, seller: seller, link: product) } before do [purchase_1, purchase_2, purchase_3].each do |p| p.process! p.update_balance_and_mark_successful! end index_model_records(Purchase) index_model_records(Link) index_model_records(Balance) login_as(seller) end it "shows correct labels with proper data types in the best selling table", :sidekiq_inline, :elasticsearch_wait_for_refresh do visit(dashboard_path) expect(page).to have_text("Best selling") sales_cells = page.all("td", text: /^Sales$/i) within(sales_cells.first) do expect(page).to have_text("Sales") expect(page).to have_text("3") expect(page.text.gsub("Sales", "").strip).not_to match(/^\$/) end revenue_cells = page.all("td", text: /^Revenue$/i) within(revenue_cells.first) do expect(page).to have_text("Revenue") expect(page).to have_text("$30", normalize_ws: true) end visits_cells = page.all("td", text: /^Visits$/i) within(visits_cells.first) do expect(page).to have_text("Visits") expect(page.text.gsub("Visits", "").strip).not_to match(/^\$/) end today_cells = page.all("td", text: /^Today$/i) within(today_cells.first) do expect(page).to have_text("Today") expect(page).to have_text("$30", normalize_ws: true) end last_7_cells = page.all("td", text: /Last 7 days/i) within(last_7_cells.first) do expect(page).to have_text("Last 7 days") expect(page).to have_text("$30", normalize_ws: true) end last_30_cells = page.all("td", text: /Last 30 days/i) within(last_30_cells.first) do expect(page).to have_text("Last 30 days") expect(page).to have_text("$30", normalize_ws: true) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/account_confirmation_spec.rb
spec/requests/account_confirmation_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Account Confirmation", js: true, type: :system do let(:user) { create(:user) } it "confirms the unconfirmed email and signs out from all other active sessions" do session_1 = :session_1 session_2 = :session_2 Capybara.using_session(session_1) do travel_to(1.hour.ago) { login_as(user) } visit(settings_main_path) end # Change email from :session_1 Capybara.using_session(session_1) do within(find("header", text: "User details").ancestor("section")) do fill_in("Email", with: "new@example.com") end expect do click_on("Update settings") wait_for_ajax end.to_not change { user.reload.last_active_sessions_invalidated_at } refresh expect(page).to have_current_path(settings_main_path) end # Access the email confirmation link received in inbox from :session_1 Capybara.using_session(session_1) do old_email = user.email freeze_time do expect do visit(user_confirmation_path(confirmation_token: user.confirmation_token)) end.to change { user.reload.email }.from(old_email).to("new@example.com") .and change { user.unconfirmed_email }.from("new@example.com").to(nil) .and change { user.reload.last_active_sessions_invalidated_at }.from(nil).to(DateTime.current) end expect(page).to have_current_path(dashboard_path) # Ensure this session remains active visit(settings_main_path) expect(page).to have_current_path(settings_main_path) end # Verify that session_2 is no longer active Capybara.using_session(session_2) do visit(settings_main_path) expect(page).to have_current_path(login_path + "?next=" + CGI.escape(settings_main_path)) end end context "when user has already requested password reset instructions" do before do # User requests reset password instructions @raw_token = user.send_reset_password_instructions end it "confirms the unconfirmed email and invalidates the requested reset password token" do user_session = :user_session attacker_session = :attacker_session # User remembers their credentials and logs in with it Capybara.using_session(user_session) do login_as(user) # User realizes that their email is compromised, hence changes it visit(settings_main_path) within(find("header", text: "User details").ancestor("section")) do fill_in("Email", with: "new@example.com") end click_on("Update settings") wait_for_ajax expect(page).to(have_alert(text: "Your account has been updated!")) # User confirms the changed email by accessing the confirmation link # received on their changed email address. # Doing so also invalidates the already received reset password link # on the old compromised email. compromised_email = user.email expect do visit(user_confirmation_path(confirmation_token: user.confirmation_token)) end.to change { user.reload.email }.from(compromised_email).to("new@example.com") .and change { user.reset_password_token }.to(nil) .and change { user.reset_password_sent_at }.to(nil) .and change { User.with_reset_password_token(@raw_token) }.from(an_instance_of(User)).to(nil) expect(page).to(have_alert(text: "Your account has been successfully confirmed!")) expect(page).to have_current_path(dashboard_path) end # Attacker gains access to user's old email inbox and finds an active # reset password link mail; uses it to try resetting the user's password! Capybara.using_session(attacker_session) do reset_password_link = edit_user_password_path(reset_password_token: @raw_token) visit(reset_password_link) # Attacker finds that the reset password link doesn't work! expect(page).to(have_alert(text: "That reset password token doesn't look valid (or may have expired).")) expect(page).to have_current_path(login_path) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/signup_spec.rb
spec/requests/signup_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Signup Feature Scenario", js: true, type: :system do let(:user) { create(:user) } it "supports signing up with password" do visit signup_path expect(page).to_not have_alert expect(page).to have_link "Gumroad", href: UrlService.root_domain_with_protocol fill_in "Email", with: Faker::Internet.email fill_in "Password", with: SecureRandom.hex(16) expect do click_on "Create account" expect(page).to have_selector("iframe[title*=recaptcha]", visible: false) wait_for_ajax expect(page).to have_content("Dashboard") end.to change(User, :count).by(1) end it "supports signing in via the signup form" do visit signup_path expect(page).to_not have_alert fill_in "Email", with: user.email fill_in "Password", with: user.password expect do click_on "Create account" wait_for_ajax expect(page).to have_content("Dashboard") end.not_to change(User, :count) end it "shows an error when signup fails" do visit signup_path expect(page).to_not have_alert fill_in "Email", with: user.email fill_in "Password", with: "someotherpassword" click_on "Create account" wait_for_ajax expect(page).to have_alert("An account already exists with this email.") expect(page).to have_button("Create account") end it "supports signing up via referral" do referrer = create(:user, name: "I am a referrer") visit signup_path(referrer: referrer.username) expect(page).to have_content("Join I am a referrer on Gumroad") fill_in "Email", with: Faker::Internet.email fill_in "Password", with: SecureRandom.hex(16) expect do click_on "Create account" wait_for_ajax expect(page).to have_content("Dashboard") end.to change(User, :count).by(1) expect(Invite.last).to have_attributes(sender_id: referrer.id, receiver_email: User.last.email, invite_state: "signed_up") end describe "Sign up and connect OAuth app" do before do @oauth_application = create(:oauth_application) @oauth_authorize_url = oauth_authorization_path(client_id: @oauth_application.uid, redirect_uri: @oauth_application.redirect_uri, scope: "edit_products") visit signup_path(next: @oauth_authorize_url) end it "sets the application name and 'next' query string in login link" do expect(page).to have_content("Sign up for Gumroad and connect #{@oauth_application.name}") expect(page).to have_link("Log in", href: login_path(next: @oauth_authorize_url)) end it "navigates to OAuth authorization page" do fill_in "Email", with: user.email fill_in "Password", with: user.password click_on "Create account" wait_for_ajax expect(page).to have_content("Authorize #{@oauth_application.name} to use your account?") end end describe "Social signup" do before do OmniAuth.config.test_mode = true end it "supports signing up with Facebook" do OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new(JSON.parse(File.read("#{Rails.root}/spec/support/fixtures/facebook_omniauth.json"))) visit signup_path expect do click_button "Facebook" click_button "Login" # 2FA expect(page).to have_content("We're here to help you get paid for your work.") end.to change(User, :count).by(1) end it "supports signing up with Google" do OmniAuth.config.mock_auth[:google_oauth2] = OmniAuth::AuthHash.new(JSON.parse(File.read("#{Rails.root}/spec/support/fixtures/google_omniauth.json"))) visit signup_path expect do click_button "Google" click_button "Login" # 2FA expect(page).to have_content("We're here to help you get paid for your work.") end.to change(User, :count).by(1) end it "supports signing up with X" do OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new(JSON.parse(File.read("#{Rails.root}/spec/support/fixtures/twitter_omniauth.json"))) visit signup_path expect do click_button "X" expect(page).to have_alert(text: "Please enter an email address!") end.to change(User, :count).by(1) end it "supports signing up with Stripe" do OmniAuth.config.mock_auth[:stripe_connect] = OmniAuth::AuthHash.new(JSON.parse(File.read("#{Rails.root}/spec/support/fixtures/stripe_connect_omniauth.json"))) visit signup_path expect do click_button "Stripe" expect(page).to have_content("We're here to help you get paid for your work.") end.to change(User, :count).by(1) end end describe "Prefill team invitation email" do let(:team_invitation) { create(:team_invitation) } it "prefills the email" do visit signup_path(next: accept_settings_team_invitation_path(team_invitation.external_id, email: team_invitation.email)) expect(page).to have_field("Email", with: team_invitation.email) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/library_spec.rb
spec/requests/library_spec.rb
# frozen_string_literal: true require "spec_helper" describe("Library Scenario", type: :system, js: true) do include ManageSubscriptionHelpers before :each do @user = create(:named_user) login_as @user allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000) end def expect_to_show_purchases_in_order(purchases) purchases.each_with_index do |purchase, index| variants = purchase.variant_attributes&.map(&:name)&.join(", ") expect(page).to have_selector("article:nth-of-type(#{index + 1})", text: "#{purchase.link.name}#{variants.present? ? " - #{variants}" : ""}") end end context "membership purchases" do let(:product) do create(:membership_product, block_access_after_membership_cancellation: true, product_files: [create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png"), create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pen.png")]) end let!(:purchase1) do create(:membership_purchase, created_at: 1.month.ago, link: product, purchaser: @user).tap { _1.create_url_redirect! } end let!(:purchase2) do create(:membership_purchase, link: product, purchaser: @user).tap { _1.create_url_redirect! } end let!(:purchase3) do create(:membership_purchase, link: product, purchaser: @user).tap do _1.create_url_redirect! _1.subscription.update!(cancelled_at: 1.day.ago) end end it "shows all live subscription purchases" do Link.import(refresh: true, force: true) visit "/library" expect(page).to have_product_card(product, count: 2) expect(page).to have_link(href: purchase1.url_redirect.download_page_url) expect(page).to have_link(href: purchase2.url_redirect.download_page_url) expect(page).not_to have_link(href: purchase3.url_redirect.download_page_url) end end it "shows preorders purchases" do link = create(:product_with_video_file, price_cents: 600, is_in_preorder_state: true, name: "preorder link") Link.import(refresh: true, force: true) preorder_link = create(:preorder_link, link:, release_at: 2.days.from_now) good_card = build(:chargeable) preorder = create(:preorder, preorder_link_id: preorder_link.id, seller_id: link.user.id) create(:purchase, purchaser: @user, link: preorder_link.link, chargeable: good_card, purchase_state: "in_progress", preorder_id: preorder.id, is_preorder_authorization: true) preorder.authorize! preorder.mark_authorization_successful! visit "/library" expect(page).to have_product_card(link) end describe "Product thumbnails", :sidekiq_inline do it "displays product thumbnail instead of previews" do creator = create(:user) product = create(:product, user: creator) create(:purchase, link: product, purchaser: @user) create(:thumbnail, product:) product.reload index_model_records(Link) visit "/library" within find_product_card(product) do expect(find("figure")).to have_image(src: product.thumbnail.url) end end context "when asset preview dimensions are nil" do let(:product) { create(:product) } let!(:asset_preview) { create(:asset_preview, link: product) } let!(:purchase) { create(:purchase, link: product, purchaser: @user) } it "displays the purchased product card" do allow_any_instance_of(AssetPreview).to receive(:width).and_return(nil) allow_any_instance_of(AssetPreview).to receive(:height).and_return(nil) visit "/library" expect(page).to have_product_card(product) end end end it "shows subscriptions where the original purchase is refunded" do subscription_link = create(:subscription_product, name: "some name", user: @user) subscription = create(:subscription, user: @user, link: subscription_link, created_at: 3.days.ago) purchase = create(:purchase, link: subscription_link, subscription:, is_original_subscription_purchase: true, created_at: 3.days.ago, purchaser: @user) create(:url_redirect, purchase:) non_subscription_link = create(:product, is_recurring_billing: false, user: @user) normal_purchase = create(:purchase, link: non_subscription_link, purchaser: @user) create(:url_redirect, purchase: normal_purchase) create(:purchase, link: subscription_link, subscription:, is_original_subscription_purchase: false, purchaser: @user) purchase.update_attribute(:stripe_refunded, true) Link.import(refresh: true, force: true) visit "/library" expect(page).to have_product_card(subscription_link) end it "shows subscriptions where the subscription plan has been upgraded" do setup_subscription(with_product_files: true) travel_to(@originally_subscribed_at + 1.month) do params = { price_id: @yearly_product_price.external_id, variants: [@original_tier.external_id], use_existing_card: true, perceived_price_cents: @original_tier_yearly_price.price_cents, perceived_upgrade_price_cents: @original_tier_yearly_upgrade_cost_after_one_month, } result = Subscription::UpdaterService.new(subscription: @subscription, gumroad_guid: "abc123", params:, logged_in_user: @user, remote_ip: "1.1.1.1").perform expect(result[:success]).to eq true login_as @user visit "/library" expect(page).to have_product_card(@product) end end it "allows archiving purchases" do purchase = create(:purchase, purchaser: @user) Link.import(refresh: true, force: true) # The library shows this purchase visit "/library" expect(page).to have_product_card(purchase.link) # Archive the purchase, which disappears from the library visit "/library" find_product_card(purchase.link).hover within find_product_card(purchase.link) do find_and_click('[aria-label="Open product action menu"]') click_on "Archive" end expect(page).to_not have_product_card(purchase.link) end it "allows unarchiving purchases" do purchase = create(:purchase, purchaser: @user, is_archived: true) Link.import(refresh: true, force: true) visit "/library?show_archived_only=true" expect(page).to have_product_card(purchase.link) # Unarchive the purchase, which disappears from the archives find_product_card(purchase.link).hover within find_product_card(purchase.link) do find_and_click('[aria-label="Open product action menu"]') click_on "Unarchive" end expect(page).to have_current_path("/library?sort=recently_updated") # Purchase appears again in the library visit "/library" expect(page).to have_product_card(purchase.link) end it "manages archived purchases banner and interactions" do product1 = create(:product, name: "Product 1") product2 = create(:product, name: "Product 2") product3 = create(:product, name: "Product 3") purchase1 = create(:purchase, purchaser: @user, link: product1) purchase2 = create(:purchase, purchaser: @user, link: product2) purchase3 = create(:purchase, purchaser: @user, link: product3, is_archived: true) Link.import(refresh: true, force: true) visit "/library" expect(page).to have_product_card(purchase1.link) expect(page).to have_product_card(purchase2.link) expect(page).to_not have_product_card(purchase3.link) expect(page).to have_status(text: "You have 1 archived purchase. Click here to view") within find_product_card(purchase1.link) do find_and_click('[aria-label="Open product action menu"]') click_on "Archive" end expect(page).to have_status(text: "You have 2 archived purchases. Click here to view") click_on "Click here to view" expect(page.current_url).to include("show_archived_only=true") expect(page).to have_checked_field("Show archived only") expect(page).to have_product_card(purchase1.link) expect(page).to have_product_card(purchase3.link) expect(page).to_not have_product_card(purchase2.link) expect(page).to_not have_status(text: "You have 2 archived purchases. Click here to view") within find_product_card(purchase1.link) do find_and_click('[aria-label="Open product action menu"]') click_on "Unarchive" end expect(page).to have_current_path("/library?show_archived_only=true&sort=recently_updated") expect(page).to have_product_card(purchase3.link) expect(page).to_not have_product_card(purchase1.link) visit "/library" expect(page).to have_product_card(purchase1.link) expect(page).to have_product_card(purchase2.link) expect(page).to have_status(text: "You have 1 archived purchase. Click here to view") find_product_card(purchase2.link).hover within find_product_card(purchase2.link) do find_and_click('[aria-label="Open product action menu"]') click_on "Archive" end find_product_card(purchase1.link).hover within find_product_card(purchase1.link) do find_and_click('[aria-label="Open product action menu"]') click_on "Archive" end expect(page).to_not have_status(text: "You have 3 archived purchases. Click here to view") click_on "See archive" find_product_card(purchase3.link).hover within find_product_card(purchase3.link) do find_and_click('[aria-label="Open product action menu"]') click_on "Unarchive" end wait_for_ajax expect(page).to have_current_path("/library?show_archived_only=true&sort=recently_updated") visit "/library" wait_for_ajax expect(page).to have_product_card(purchase3.link) expect(page).to have_status(text: "You have 2 archived purchases. Click here to view") end it "lists the same product several times if purchased several times" do products = create_list(:product, 2, name: "MyProduct") category = create(:variant_category, link: products[0]) variant_1 = create(:variant, variant_category: category, name: "VariantOne") variant_2 = create(:variant, variant_category: category, name: "VariantTwo") index_model_records(Link) purchase_1 = create(:purchase, link: products[0], created_at: 50.minutes.ago, purchaser: @user) purchase_1.variant_attributes << variant_1 purchase_2 = create(:purchase, link: products[1], created_at: 40.minutes.ago, purchaser: @user) purchase_3 = create(:purchase, link: products[0], created_at: 30.minutes.ago, purchaser: @user) purchase_3.variant_attributes << variant_2 visit "/library" expect(page).to have_product_card(count: 3) expect_to_show_purchases_in_order([purchase_3, purchase_2, purchase_1]) end describe("Search, sort and filtering") do before do @creator = create(:user, name: "A user") @j = create(:purchase, link: create(:product, user: @creator, name: "Product J", created_at: 50.minutes.ago, content_updated_at: 5.minutes.ago), purchaser: @user) @i = create(:purchase, link: create(:product, user: @creator, name: "Product I", created_at: 40.minutes.ago, content_updated_at: 6.minutes.ago), purchaser: @user) @h = create(:purchase, link: create(:product, user: @creator, name: "Product H", created_at: 13.minutes.ago), purchaser: @user) @g = create(:purchase, link: create(:product, user: @creator, name: "Product G", created_at: 14.minutes.ago), purchaser: @user) @f = create(:purchase, link: create(:product, user: @creator, name: "Product F", created_at: 15.minutes.ago), purchaser: @user) @e = create(:purchase, link: create(:product, user: @creator, name: "Product E", created_at: 16.minutes.ago), purchaser: @user) @d = create(:purchase, link: create(:product, user: @creator, name: "Product D", created_at: 17.minutes.ago), purchaser: @user) @c = create(:purchase, link: create(:product, user: @creator, name: "Product C", created_at: 18.minutes.ago), purchaser: @user) @b = create(:purchase, link: create(:product, user: @creator, name: "Product B", created_at: 19.minutes.ago), purchaser: @user) @a = create(:purchase, link: create(:product, user: @creator, name: "Product A", created_at: 20.minutes.ago), purchaser: @user) Link.import(refresh: true, force: true) end it("allows the purchaser to sort the library") do visit "/library" # default sorting by recently expect(page).to have_field("Sort by", text: "Recently Updated") scroll_to find_product_card(@b.link) expect(page).to have_product_card(count: 10) expect_to_show_purchases_in_order([@j, @i, @h, @g, @f, @e, @d, @c, @b, @a]) expect(page).to have_current_path(library_path) # Sort by purchase date select "Purchase Date", from: "Sort by" scroll_to find_product_card(@i.link) expect_to_show_purchases_in_order([@a, @b, @c, @d, @e, @f, @g, @h, @i, @j]) expect(page).to have_current_path(library_path(sort: "purchase_date")) # Sort by recently updated select "Recently Updated", from: "Sort by" scroll_to find_product_card(@j.link) scroll_to find_product_card(@b.link) expect_to_show_purchases_in_order([@j, @i, @h, @g, @f, @e, @d, @c, @b, @a]) expect(page).to have_current_path(library_path(sort: "recently_updated")) end it("allows the purchaser to search the library") do visit("/library") search_field = find_field("Search products") search_field.fill_in with: "product B" search_field.native.send_keys(:enter) expect(page).to have_product_card(count: 1) expect(page).to have_product_card(@b.link) search_field.set("product C") search_field.native.send_keys(:enter) expect(page).to have_product_card(count: 1) expect(page).to have_product_card(@c.link) end it "allows the purchaser to filter products by creator" do @another_creator = create(:user, username: nil, name: "Another user") create(:product, user: @another_creator, name: "Another Creator's Product C") create(:product, user: @another_creator, name: "Another Creator's Product D") another_a = create(:purchase, link: create(:product, user: @another_creator, name: "Another Creator's Product A", content_updated_at: 3.minutes.ago), purchaser: @user) another_b = create(:purchase, link: create(:product, user: @another_creator, name: "Another Creator's Product B", content_updated_at: 2.minutes.ago), purchaser: @user) # another_creator has 4 total products but just 2 purchased by this user to ensure counts reflect user purchases only Link.import(refresh: true, force: true) visit "/library" expect(page).to have_text("Showing 1-12 of 12") expect(find("label", text: @creator.name)).to have_text("(10)") expect(find("label", text: @another_creator.name)).to have_text("(2)") expect(find_field("All Creators", visible: false).checked?).to eq(true) find_and_click("label", text: @creator.name) expect(find_field("All Creators", visible: false).checked?).to eq(false) expect(find_field(@creator.name, visible: false).checked?).to eq(true) expect(find_field(@another_creator.name, visible: false).checked?).to eq(false) expect(page).to have_text("Showing 1-10 of 10") scroll_to find_product_card(@b.link) expect(page).to have_product_card(count: 10) expect_to_show_purchases_in_order([@j, @i, @h, @g, @f, @e, @d, @c, @b, @a]) find_and_click("label", text: @creator.name) find_and_click("label", text: @another_creator.name) expect(find_field(@creator.name, visible: false).checked?).to eq(false) expect(find_field(@another_creator.name, visible: false).checked?).to eq(true) expect(find_field("All Creators", visible: false).checked?).to eq(false) expect(page).to have_text("Showing 1-2 of 2") expect(page).to have_product_card(count: 2) expect_to_show_purchases_in_order([another_b, another_a]) find_and_click("label", text: "All Creators") expect(find_field("All Creators", visible: false).checked?).to eq(true) expect(find_field(@creator.name, visible: false).checked?).to eq(false) expect(find_field(@another_creator.name, visible: false).checked?).to eq(false) expect(page).to have_text("Showing 1-12 of 12") scroll_to find_product_card(@d.link) expect_to_show_purchases_in_order([another_b, another_a, @j, @i, @h, @g, @f, @e, @d, @c, @b, @a]) end it "limits the creator filter list to 5 with a show more" do creator_2 = create(:named_user, name: "User 2") create(:purchase, link: create(:product, user: creator_2), purchaser: @user) create(:purchase, link: create(:product, user: creator_2), purchaser: @user) create(:purchase, link: create(:product, user: creator_2), purchaser: @user) create(:purchase, link: create(:product, user: creator_2), purchaser: @user) create(:purchase, link: create(:product, user: creator_2), purchaser: @user) creator_3 = create(:named_user, name: "User 3") create(:purchase, link: create(:product, user: creator_3), purchaser: @user) create(:purchase, link: create(:product, user: creator_3), purchaser: @user) create(:purchase, link: create(:product, user: creator_3), purchaser: @user) create(:purchase, link: create(:product, user: creator_3), purchaser: @user) creator_4 = create(:named_user, name: "User 4") create(:purchase, link: create(:product, user: creator_4), purchaser: @user) create(:purchase, link: create(:product, user: creator_4), purchaser: @user) create(:purchase, link: create(:product, user: creator_4), purchaser: @user) creator_5 = create(:named_user, name: "User 5") create(:purchase, link: create(:product, user: creator_5), purchaser: @user) create(:purchase, link: create(:product, user: creator_5), purchaser: @user) creator_6 = create(:named_user, name: "User 6") create(:purchase, link: create(:product, user: creator_6), purchaser: @user) Link.import(refresh: true, force: true) visit "/library" expect(page).to have_selector("label", text: @creator.name) expect(page).to have_selector("label", text: creator_2.name) expect(page).to have_selector("label", text: creator_3.name) expect(page).to have_selector("label", text: creator_4.name) expect(page).to have_selector("label", text: creator_5.name) expect(page).to_not have_selector("label", text: creator_6.name) find(".creator").click_on("Show more") expect(page).to have_selector("label", text: creator_6.name) expect(find(".creator")).to_not have_text("Show more") end it "sort the creator list by number of products" do creator_with_3_products = create(:named_user, name: "User 2") create(:purchase, link: create(:product, user: creator_with_3_products), purchaser: @user) create(:purchase, link: create(:product, user: creator_with_3_products), purchaser: @user) create(:purchase, link: create(:product, user: creator_with_3_products), purchaser: @user) creator_with_5_products = create(:named_user, name: "User 3") create(:purchase, link: create(:product, user: creator_with_5_products), purchaser: @user) create(:purchase, link: create(:product, user: creator_with_5_products), purchaser: @user) create(:purchase, link: create(:product, user: creator_with_5_products), purchaser: @user) create(:purchase, link: create(:product, user: creator_with_5_products), purchaser: @user) create(:purchase, link: create(:product, user: creator_with_5_products), purchaser: @user) creator_with_1_product = create(:named_user, name: "User 4") create(:purchase, link: create(:product, user: creator_with_1_product), purchaser: @user) Link.import(refresh: true, force: true) visit "/library" expect(page).to have_selector("label:has(input[type=checkbox]):nth-of-type(2)", text: @creator.name, visible: false) expect(page).to have_selector("label:has(input[type=checkbox]):nth-of-type(3)", text: creator_with_5_products.name, visible: false) expect(page).to have_selector("label:has(input[type=checkbox]):nth-of-type(4)", text: creator_with_3_products.name, visible: false) expect(page).to have_selector("label:has(input[type=checkbox]):nth-of-type(5)", text: creator_with_1_product.name, visible: false) end end it "allow marking deleted by the buyer" do purchase = create(:purchase, purchaser: @user) Link.import(refresh: true, force: true) visit "/library" expect(page).to have_product_card(purchase.link) within find_product_card(purchase.link).hover do find_and_click "[aria-label='Open product action menu']" click_on "Delete" end expect(page).to have_text("Are you sure you want to delete #{purchase.link_name}?") click_on "Confirm" wait_for_ajax expect(page).to_not have_product_card(purchase.link) end it "shows new results upon scrolling to the bottom of the page" do products = [] 30.times do |n| product = create(:product, name: "Product #{n}", price_cents: 0) products << product create(:purchase, link: product, purchaser: @user) end Link.import(refresh: true, force: true) visit library_path expect(page).to have_text("Showing 1-15 of 30 products") 15.times do |n| expect(page).to have_product_card(products[29 - n], exact_text: true) end 15.times do |n| expect(page).to_not have_product_card(products[n], exact_text: true) end scroll_to find(:section, "15", section_element: :article) 15.times do |n| expect(page).to have_product_card(products[n], exact_text: true) end end describe "bundle purchases" do let(:purchase) { create(:purchase, purchaser: @user, link: create(:product, :bundle)) } before do purchase.create_artifacts_and_send_receipt! 14.times do |i| product = create(:product, name: "Product #{i}") create(:purchase, link: product, purchaser: @user) end end it "filters by bundle" do visit library_path (0..13).each do |i| expect(page).to have_section("Product #{i}", exact: true) end expect(page).to have_section("Bundle Product 2") expect(page).to_not have_section("Bundle Product 1") select_combo_box_option search: "Bundle", from: "Bundles" (0..13).each do |i| expect(page).to_not have_section("Product #{i}", exact: true) end within_section "Bundle Product 2", section_element: :article do expect(page).to have_link("Bundle Product 2", href: purchase.product_purchases.second.url_redirect.download_page_url) end within_section "Bundle Product 1", section_element: :article do expect(page).to have_link("Bundle Product 1", href: purchase.product_purchases.first.url_redirect.download_page_url) end end context "product was previously not a bundle" do before do purchase.update!(is_bundle_purchase: false) end it "shows the card for that product" do visit library_path search_field = find_field("Search products") search_field.fill_in with: "Bundle" search_field.native.send_keys(:enter) expect(page).to have_selector("[itemprop='name']", text: "Bundle", exact_text: true) end end end it "allows the application of multiple filters/sorts at once" do seller1 = create(:user, name: "Seller 1") seller2 = create(:user, name: "Seller 2") purchase1 = create(:purchase, purchaser: @user, link: create(:product, name: "Audiobook 1", user: seller1)) purchase2 = create(:purchase, purchaser: @user, link: create(:product, name: "Course 1", user: seller1, content_updated_at: 1.day.ago)) create(:purchase, purchaser: @user, link: create(:product, name: "Audiobook 2", user: seller2)) create(:purchase, purchaser: @user, link: create(:product, name: "Course 2", user: seller2)) visit library_path({ creators: seller1.external_id }) expect(page).to have_checked_field("Seller 1") expect(page).to have_unchecked_field("Seller 2") expect(page).to have_unchecked_field("All Creators") expect_to_show_purchases_in_order([purchase1, purchase2]) expect(page).to_not have_section("Course 2") expect(page).to_not have_section("Audiobook 2") select "Purchase Date", from: "Sort by" expect_to_show_purchases_in_order([purchase2, purchase1]) expect(page).to_not have_section("Course 2") expect(page).to_not have_section("Audiobook 2") search_field = find_field("Search products") search_field.fill_in with: "Audiobook 1" search_field.native.send_keys(:enter) expect(page).to have_section("Audiobook 1") expect(page).to_not have_section("Course 1") expect(page).to_not have_section("Course 2") expect(page).to_not have_section("Audiobook 2") end it "shows navigation" do visit library_path expect(page).to have_tab_button("Purchases") expect(page).to have_tab_button("Saved") expect(page).to have_tab_button("Following") end context "follow_wishlists feature flag is disabled" do before { Feature.deactivate(:follow_wishlists) } it "shows only the wishlists tab" do visit wishlists_path expect(page).to have_tab_button("Wishlists") expect(page).not_to have_tab_button("Following") end end context "reviews_page feature flag is disabled" do it "does not show the reviews tab" do visit library_path expect(page).to_not have_link("Reviews") end end context "reviews_page feature flag is enabled" do let(:user) { create(:user) } before { Feature.activate_user(:reviews_page, user) } context "user has reviews" do let(:seller) { create(:user, name: "Seller") } let!(:reviews) do build_list(:product_review, 3) do |review, i| review.purchase.purchaser = user review.message = if i > 0 then "Message #{i}" else nil end review.update!(rating: i + 1) review.link.update!(user: seller, name: "Product #{i}") review.purchase.update!(seller:) end end let!(:thumbnail) { create(:thumbnail, product: reviews.first.link) } it "shows the user's reviews" do login_as user visit library_path select_tab "Reviews" expect(page).to have_current_path(reviews_path) expect(page).to have_text("You've reviewed all your products!") expect(page).to have_link("Discover more", href: discover_url(host: DISCOVER_DOMAIN)) within find("tr", text: "Product 0") do expect(page).to have_image(src: thumbnail.url) expect(page).to_not have_text('"') expect(page).to have_link("Product 0", href: reviews.first.link.long_url(recommended_by: "library")) expect(page).to have_link("Seller", href: reviews.first.link.user.profile_url) expect(page).to have_selector("[aria-label='1 star']") click_on "Edit" within "form" do expect(page).to have_radio_button("1 star", checked: true) (2..5).each do |i| expect(page).to have_radio_button("#{i} stars", checked: false) end click_on "Edit" choose "4 stars" fill_in "Want to leave a written review?", with: "Message 0" click_on "Update review" end end expect(page).to have_alert(text: "Review submitted successfully!") within find("tr", text: "Product 0") do within "form" do expect(page).to have_radio_button("1 star", checked: false) [2, 3, 5].each do |i| expect(page).to have_radio_button("#{i} stars", checked: false) end expect(page).to have_radio_button("4 stars", checked: true) expect(page).to have_text('"Message 0"') end click_on "Edit", match: :first expect(page).to have_selector("[aria-label='4 stars']") expect(page).to have_text('"Message 0"') end reviews.first.reload expect(reviews.first.rating).to eq(4) expect(reviews.first.message).to eq("Message 0") within find("tr", text: "Product 1") do # Products without a thumbnail use an inline placeholder expect(page).to have_image(src: "data:image/") expect(page).to have_text("Message 1") expect(page).to have_link("Product 1", href: reviews.second.link.long_url(recommended_by: "library")) expect(page).to have_link("Seller", href: reviews.second.link.user.profile_url) expect(page).to have_selector("[aria-label='2 stars']") end within find("tr", text: "Product 2") do expect(page).to have_image(src: "data:image/") expect(page).to have_text("Message 2") expect(page).to have_link("Product 2", href: reviews.third.link.long_url(recommended_by: "library")) expect(page).to have_link("Seller", href: reviews.third.link.user.profile_url) expect(page).to have_selector("[aria-label='3 stars']") end end end context "user has purchases awaiting review" do let!(:product1) { create(:product, name: "Product 1") } let!(:product2) { create(:product, name: "Product 2") } let!(:product3) { create(:product, name: "Product 3") } let!(:purchase1) { create(:purchase, purchaser: user, link: product1) } let!(:purchase2) { create(:purchase, purchaser: user, link: product2) } let!(:purchase3) { create(:purchase, purchaser: user, link: product3, created_at: 3.years.ago) } let!(:thumbnail) { create(:thumbnail, product: product1) } before { purchase3.seller.update!(disable_reviews_after_year: true) } it "does not show the empty state placeholder when there are purchases awaiting review" do login_as user visit reviews_path expect(page).not_to have_text("You haven't bought anything... yet!") expect(page).not_to have_text("Once you do, it'll show up here so you can review them.") expect(page).not_to have_link("Discover products", href: discover_url(host: DISCOVER_DOMAIN)) end it "shows review forms for purchases awaiting review" do login_as user visit library_path select_tab "Reviews" within "[role='listitem']", text: "Product 1" do expect(page).to have_image(src: thumbnail.url) expect(page).to have_link("Product 1", href: product1.long_url(recommended_by: "library")) expect(page).to have_link(product1.user.username, href: product1.user.profile_url) fill_in "Want to leave a written review?", with: "Message 1" choose "1 star" click_on "Post review" end expect(page).to have_alert(text: "Review submitted successfully!") expect(page).to_not have_selector("[role='listitem']", text: "Product 1") within "[role='listitem']", text: "Product 2" do expect(page).to have_field("Want to leave a written review?", focused: true) expect(page).to have_link("Product 2") choose "2 stars" click_on "Post review" end expect(page).to have_alert(text: "Review submitted successfully!") expect(page).to_not have_selector("[role='listitem']", text: "Product 2") expect(page).to_not have_selector("[role='listitem']", text: "Product 3") review1 = purchase1.reload.product_review expect(review1.rating).to eq(1) expect(review1.message).to eq("Message 1") review2 = purchase2.reload.product_review expect(review2.rating).to eq(2) expect(review2.message).to be_nil end end context "user has no purchases or reviews" do it "shows a placeholder" do login_as user visit reviews_path expect(page).to have_text("You haven't bought anything... yet!") expect(page).to have_text("Once you do, it'll show up here so you can review them.")
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/secure_redirect_spec.rb
spec/requests/secure_redirect_spec.rb
# frozen_string_literal: true require "spec_helper" describe("Secure Redirect", js: true, type: :system) do let(:user) { create(:user) } let(:destination_url) { api_url(host: UrlService.domain_with_protocol) } let(:confirmation_text_1) { "example@example.com" } let(:confirmation_text_2) { user.email } let(:message) { "Please enter your email address to unsubscribe" } let(:field_name) { "Email address" } let(:error_message) { "Email address does not match" } let(:secure_payload) do { destination: destination_url, confirmation_texts: [confirmation_text_1, confirmation_text_2], created_at: Time.current.to_i } end let(:encrypted_payload) { SecureEncryptService.encrypt(secure_payload.to_json) } describe "GET /secure_url_redirect" do context "with valid parameters" do it "displays the confirmation page with custom messages" do visit secure_url_redirect_path( encrypted_payload: encrypted_payload, message: message, field_name: field_name, error_message: error_message ) expect(page).to have_content(message) expect(page).to have_field(field_name) end it "displays the confirmation page with default messages" do visit secure_url_redirect_path( encrypted_payload: encrypted_payload ) expect(page).to have_content("Please enter the confirmation text to continue to your destination.") expect(page).to have_field("Confirmation text") end end context "with invalid parameters" do it "redirects to the root path if encrypted_payload is missing" do visit secure_url_redirect_path expect(page).to have_current_path(login_path) end end end describe "POST /secure_url_redirect" do before do visit secure_url_redirect_path( encrypted_payload: encrypted_payload, message: message, field_name: field_name, error_message: error_message ) end context "with correct confirmation text" do it "redirects to the destination" do fill_in field_name, with: confirmation_text_2 click_button "Continue" expect(page).to have_current_path(destination_url) end end context "with incorrect confirmation text" do it "shows an error message" do fill_in field_name, with: "wrong text" click_button "Continue" wait_for_ajax expect(page).to have_content(error_message) expect(page).to have_current_path(secure_url_redirect_path, ignore_query: true) end end context "with blank confirmation text" do it "shows an error message" do fill_in field_name, with: "" click_button "Continue" wait_for_ajax expect(page).to have_content("Please enter your email address to unsubscribe") expect(page).to have_current_path(secure_url_redirect_path, ignore_query: true) end end context "with an invalid payload" do let(:invalid_secure_payload) do { destination: nil, confirmation_texts: [confirmation_text_2], created_at: Time.current.to_i } end let(:invalid_encrypted_payload) { SecureEncryptService.encrypt(invalid_secure_payload.to_json) } before do visit secure_url_redirect_path( encrypted_payload: invalid_encrypted_payload, message: message, field_name: field_name, error_message: error_message ) end it "shows an error message" do fill_in field_name, with: confirmation_text_2 click_button "Continue" wait_for_ajax expect(page).to have_content("Invalid destination") expect(page).to have_current_path(secure_url_redirect_path, ignore_query: true) end end context "with a tampered payload" do let(:tampered_encrypted_payload) { "tampered" } before do visit secure_url_redirect_path( encrypted_payload: tampered_encrypted_payload, message: message, field_name: field_name, error_message: error_message ) end it "shows an error message" do fill_in field_name, with: confirmation_text_2 click_button "Continue" wait_for_ajax expect(page).to have_content("Invalid request") expect(page).to have_current_path(secure_url_redirect_path, ignore_query: 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/requests/embed_spec.rb
spec/requests/embed_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Embed scenario", type: :system, js: true do include EmbedHelpers after(:all) { cleanup_embed_artifacts } let(:product) { create(:physical_product) } let!(:js_nonce) { SecureRandom.base64(32).chomp } it "accepts product URL" do product = create(:product) visit(create_embed_page(product, url: product.long_url, gumroad_params: "&email=sam@test.com", outbound: false)) within_frame { click_on "Add to cart" } check_out(product) end it "accepts affiliated product URL with query params" do affiliate_user = create(:affiliate_user) pwyw_product = create(:product, price_cents: 0, customizable_price: true) direct_affiliate = create(:direct_affiliate, affiliate_user:, seller: pwyw_product.user, affiliate_basis_points: 1000, products: [pwyw_product]) visit(create_embed_page(pwyw_product, url: "#{direct_affiliate.referral_url_for_product(pwyw_product)}?email=john@test.com", gumroad_params: "&price=75", outbound: false)) within_frame { click_on "Add to cart" } expect do check_out(pwyw_product, email: nil) end.to change { AffiliateCredit.count }.from(0).to(1) purchase = pwyw_product.sales.successful.last expect(purchase.email).to eq("john@test.com") expect(purchase.price_cents).to eq(7500) expect(purchase.affiliate_credit.affiliate).to eq(direct_affiliate) expect(purchase.affiliate_credit.amount_cents).to eq(645) end it "embeds affiliated product with destination URL" do affiliate_user = create(:affiliate_user) pwyw_product = create(:product, price_cents: 0, customizable_price: true) direct_affiliate = create(:direct_affiliate, affiliate_user:, seller: pwyw_product.user, affiliate_basis_points: 1000, products: [pwyw_product], destination_url: "https://gumroad.com") visit(create_embed_page(pwyw_product, url: "#{direct_affiliate.referral_url_for_product(pwyw_product)}?", outbound: false)) within_frame do fill_in "Name a fair price", with: 75 click_on "Add to cart" end expect do check_out(pwyw_product) end.to change { AffiliateCredit.count }.from(0).to(1) purchase = pwyw_product.sales.successful.last expect(purchase.email).to eq("test@gumroad.com") expect(purchase.price_cents).to eq(7500) expect(purchase.affiliate_credit.affiliate).to eq(direct_affiliate) expect(purchase.affiliate_credit.amount_cents).to eq(645) end it "embeds a product that has a custom permalink" do product = create(:product, custom_permalink: "custom") visit(create_embed_page(product, url: short_link_url(product, host: "#{PROTOCOL}://#{DOMAIN}"), outbound: false)) within_frame { click_on "Add to cart" } check_out(product) end it "embeds a product by accepting only 'data-gumroad-product-id' attribute and without inserting an anchor tag" do product = create(:product) visit(create_embed_page(product, insert_anchor_tag: false, outbound: false)) within_frame { click_on "Add to cart" } check_out(product) end context "discount code in URL" do let(:offer_code) { create(:offer_code, user: product.user, products: [product]) } it "applies the discount code" do visit(create_embed_page(product, url: "#{product.long_url}/#{offer_code.code}", outbound: false)) within_frame do expect(page).to have_status(text: "$1 off will be applied at checkout (Code SXSW)") click_on "Add to cart" end check_out(product, is_free: true) purchase = Purchase.last expect(purchase).to be_successful expect(purchase.offer_code).to eq(offer_code) end end context "when an affiliated product purchased from a browser that doesn't support setting third-party affiliate cookie" do let(:affiliate_user) { create(:affiliate_user) } let(:product) { create(:product, price_cents: 7500) } let(:direct_affiliate) { create(:direct_affiliate, affiliate_user:, seller: product.user, affiliate_basis_points: 1000, products: [product]) } before(:each) do expect_any_instance_of(OrdersController).to receive(:affiliate_from_cookies).with(an_instance_of(Link)).and_return(nil) end it "successfully credits the affiliate commission for the product bought using its affiliated product URL" do visit(create_embed_page(product, url: direct_affiliate.referral_url_for_product(product), outbound: false)) within_frame { click_on "Add to cart" } check_out(product) purchase = product.sales.successful.last expect(purchase.affiliate_credit.affiliate).to eq(direct_affiliate) expect(purchase.affiliate_credit.amount_cents).to eq(645) end Affiliate::QUERY_PARAMS.each do |query_param| it "successfully credits the affiliate commission for the product bought from a page that contains '#{query_param}' query parameter" do visit(create_embed_page(product, url: short_link_url(product, host: UrlService.domain_with_protocol), outbound: false, query_params: { query_param => direct_affiliate.external_id_numeric })) within_frame { click_on "Add to cart" } check_out(product) purchase = product.sales.successful.last expect(purchase.affiliate_credit.affiliate).to eq(direct_affiliate) expect(purchase.affiliate_credit.amount_cents).to eq(645) end end end it "prefils the values for quantity, variant, price, and custom fields from the URL" do physical_skus_product = create(:physical_product, skus_enabled: true, price_cents: 0, customizable_price: true) variant_category_1 = create(:variant_category, link: physical_skus_product) %w[Red Blue Green].each { |name| create(:variant, name:, variant_category: variant_category_1) } variant_category_2 = create(:variant_category, link: physical_skus_product) ["Small", "Medium", "Large", "Extra Large"].each { |name| create(:variant, name:, variant_category: variant_category_2) } variant_category_3 = create(:variant_category, link: physical_skus_product) %w[Polo Round].each { |name| create(:variant, name:, variant_category: variant_category_3) } Product::SkusUpdaterService.new(product: physical_skus_product).perform physical_skus_product.custom_fields << [ create(:custom_field, name: "Age"), create(:custom_field, name: "Gender") ] physical_skus_product.save! embed_page_url = create_embed_page(physical_skus_product, template_name: "embed_page.html.erb", outbound: false, gumroad_params: "quantity=2&price=3&Age=21&Gender=Male&option=#{physical_skus_product.skus.find_by(name: "Blue - Extra Large - Polo").external_id}") visit(embed_page_url) within_frame do expect(page).to have_radio_button("Blue - Extra Large - Polo", checked: true) expect(page).to have_field("Quantity", with: 2) expect(page).to have_field("Name a fair price", with: 3) click_on "Add to cart" end expect(page).to have_field("Age", with: "21") expect(page).to have_field("Gender", with: "Male") expect do check_out(physical_skus_product) end.to change { Purchase.successful.count }.by(1) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/catch_bad_request_errors_spec.rb
spec/requests/catch_bad_request_errors_spec.rb
# frozen_string_literal: true require "spec_helper" describe "CatchBadRequestErrors middleware" do let!(:user) { create(:user) } let!(:oauth_application) { create(:oauth_application, owner: user) } context "when a request contains invalid params" do it "returns 400 (Bad Request) response" do post oauth_token_path, params: "hello-%" expect(response).to have_http_status(:bad_request) expect(response.body).to eq("") end it "returns error JSON response with 400 (Bad Request) status for a JSON request" do post oauth_token_path, params: "hello-%", headers: { "ACCEPT" => "application/json" } expect(response).to have_http_status(:bad_request) expect(response.parsed_body["success"]).to eq(false) end end context "when a request contains valid params" do it "returns 200 (OK) response" do post oauth_token_path, params: { grant_type: "password", scope: "edit_products", username: user.email, password: user.password, client_id: oauth_application.uid, client_secret: oauth_application.secret } expect(response).to have_http_status(:ok) expect(response.parsed_body.keys).to match_array(%w(access_token created_at refresh_token scope token_type)) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/acme_challenges_spec.rb
spec/requests/acme_challenges_spec.rb
# frozen_string_literal: true require "spec_helper" describe "ACME Challenges", type: :request do let(:token) { "a" * 43 } let(:challenge_content) { "challenge-response-content" } describe "GET /.well-known/acme-challenge/:token" do context "when request is from a user custom domain" do let(:user) { create(:user) } let!(:custom_domain) { create(:custom_domain, user:) } before do $redis.set(RedisKey.acme_challenge(token), challenge_content) end after do $redis.del(RedisKey.acme_challenge(token)) end it "returns the challenge content" do get "/.well-known/acme-challenge/#{token}", headers: { "HOST" => custom_domain.domain } expect(response.status).to eq(200) expect(response.body).to eq(challenge_content) end end context "when request is from a product custom domain" do let(:product) { create(:product) } let!(:custom_domain) { create(:custom_domain, user: nil, product:) } before do $redis.set(RedisKey.acme_challenge(token), challenge_content) end after do $redis.del(RedisKey.acme_challenge(token)) end it "returns the challenge content" do get "/.well-known/acme-challenge/#{token}", headers: { "HOST" => custom_domain.domain } expect(response.status).to eq(200) expect(response.body).to eq(challenge_content) end end context "when request is from default Gumroad domain" do it "does not route to the controller" do get "/.well-known/acme-challenge/#{token}", headers: { "HOST" => DOMAIN } expect(response.status).to eq(404) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/product_custom_domain_spec.rb
spec/requests/product_custom_domain_spec.rb
# frozen_string_literal: true require "spec_helper" describe "ProductCustomDomainScenario", type: :system, js: true do let(:product) { create(:product) } let(:custom_domain) { create(:custom_domain, domain: "test-custom-domain.gumroad.com", user: nil, product:) } let(:port) { Capybara.current_session.server.port } before do allow(Resolv::DNS).to receive_message_chain(:new, :getresources).and_return([double(name: "domains.gumroad.com")]) Link.__elasticsearch__.create_index!(force: true) product.__elasticsearch__.index_document Link.__elasticsearch__.refresh_index! end it "successfully purchases the linked product" do visit "http://#{custom_domain.domain}:#{port}/" click_on "I want this!" check_out(product) expect(product.sales.successful.count).to eq(1) end context "when buyer is logged in" do let(:buyer) { create(:user) } before do login_as buyer end it "autofills the buyer's email address and purchases the product" do visit "http://#{custom_domain.domain}:#{port}/" click_on "I want this!" expect(page).to have_field("Email address", with: buyer.email, disabled: true) check_out(product, logged_in_user: buyer) expect(product.sales.successful.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/requests/affiliates_spec.rb
spec/requests/affiliates_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Affiliates", type: :system, js: true do it "redirects to the product page and applies discount based on the offer_code parameter in the query string" do user = create(:user) product = create(:product, user:, price_cents: 2000) direct_affiliate = create(:direct_affiliate, seller_id: user.id, products: [product]) offer_code = create(:offer_code, code: "free", products: [product], amount_cents: 2000) visit direct_affiliate.referral_url expect(page).to(have_selector("[itemprop='price']", text: "$20")) visit "#{direct_affiliate.referral_url}/?offer_code=#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "$20 off will be applied at checkout (Code FREE)") expect(page).to have_selector("[itemprop='price']", text: "$20 $0") click_on "I want this!" fill_in("Your email address", with: "test@gumroad.com") click_on "Get" expect(page).to have_alert(text: "Your purchase was successful!") end it "displays affiliates based on initial page load query parameters" do stub_const("AffiliatesPresenter::PER_PAGE", 1) seller = create(:user) product = create(:product, user: seller, price_cents: 2000) create(:direct_affiliate, seller:, products: [product], affiliate_user: create(:user, name: "Jane")) affiliate2 = create(:direct_affiliate, seller:, products: [product], affiliate_user: create(:user, name: "Edgar")) affiliate3 = create(:direct_affiliate, seller:, products: [product], affiliate_user: create(:user, name: "Edgar 2")) affiliate_request = create(:affiliate_request, seller:) sign_in seller params = { query: "Edgar", column: "affiliate_user_name", sort: "asc", page: "2" } visit affiliates_path(params) expect(page).to have_current_path(affiliates_path(params)) expect(page).to have_tab_button("Affiliates", open: true) expect(page).to have_table "Affiliates", with_rows: [ { "Name" => affiliate3.affiliate_user.name }, ] expect(page).to_not have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] # Ensure that all affiliates and affiliate requests come back when clearing the search select_disclosure "Search" do fill_in "Search", with: "" end expect(page).to have_table "Affiliates", with_rows: [ { "Name" => affiliate2.affiliate_user.name }, ] expect(page).to have_current_path("#{affiliates_path}?column=affiliate_user_name&sort=asc") expect(page).to have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] end it "allows filtering for affiliates" do seller = create(:user) product = create(:product, user: seller, price_cents: 2000) affiliate1 = create(:direct_affiliate, seller:, products: [product], affiliate_user: create(:user, name: "Jane Affiliate")) affiliate2 = create(:direct_affiliate, seller:, products: [product], affiliate_user: create(:user, name: "Edgar")) affiliate_request = create(:affiliate_request, seller:) sign_in seller visit affiliates_path expect(page).to have_tab_button("Affiliates", open: true) expect(page).to have_table "Affiliates", with_rows: [ { "Name" => affiliate1.affiliate_user.name, "Product" => product.name, "Commission" => "3%" }, { "Name" => affiliate2.affiliate_user.name, "Product" => product.name, "Commission" => "3%" }, ] expect(page).to have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] select_disclosure "Search" do fill_in "Search", with: "Jane" end expect(page).to have_table "Affiliates", with_rows: [ { "Name" => affiliate1.affiliate_user.name, "Product" => product.name, "Commission" => "3%" }, ] expect(page).to have_current_path(affiliates_path({ query: "Jane" })) expect(page).to_not have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] # Clear the search and make sure the requests table is back select_disclosure "Search" do fill_in "Search", with: "" end expect(page).to have_table "Affiliates", with_rows: [ { "Name" => affiliate1.affiliate_user.name, "Product" => product.name, "Commission" => "3%" }, { "Name" => affiliate2.affiliate_user.name, "Product" => product.name, "Commission" => "3%" }, ] expect(page).to have_current_path(affiliates_path) expect(page).to have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] end context "pagination" do let(:seller) { create(:user) } let(:product) { create(:product, user: seller, price_cents: 2000) } let!(:affiliate_request) { create(:affiliate_request, seller:) } before do aff1 = create(:direct_affiliate, seller_id: seller.id, products: [product], affiliate_user: create(:user, name: "Jane Affiliate")) ProductAffiliate.find_by(affiliate_id: aff1.id).update!(updated_at: 1.day.ago) aff2 = create(:direct_affiliate, seller_id: seller.id, products: [product], affiliate_user: create(:user, name: "Jim Affiliate")) ProductAffiliate.find_by(affiliate_id: aff2.id).update!(updated_at: 2.days.ago) aff3 = create(:direct_affiliate, seller_id: seller.id, products: [product], affiliate_user: create(:user, name: "Edgar")) ProductAffiliate.find_by(affiliate_id: aff3.id).update!(updated_at: 1.week.ago) stub_const("AffiliatesPresenter::PER_PAGE", 1) sign_in seller visit affiliates_path end it "paginates through the affiliates table" do expect(page).to have_button("Previous", disabled: true) expect(page).to have_button("Next") expect(page).to have_table "Affiliates", with_rows: [ { "Name" => "Jane Affiliate", "Product" => product.name, "Commission" => "3%" }, ] click_on "2" wait_for_ajax expect(page).to have_button("Previous") expect(page).to have_button("Next") expect(page).to have_table "Affiliates", with_rows: [ { "Name" => "Jim Affiliate", "Product" => product.name, "Commission" => "3%" }, ] expect(page).to have_current_path(affiliates_path({ page: "2" })) expect(page).to_not have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] click_on "3" wait_for_ajax expect(page).to have_button("Previous") expect(page).to have_button("Next", disabled: true) expect(page).to have_table "Affiliates", with_rows: [ { "Name" => "Edgar", "Product" => product.name, "Commission" => "3%" }, ] expect(page).to have_current_path(affiliates_path({ page: "3" })) expect(page).to_not have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] click_on "1" wait_for_ajax expect(page).to have_table "Affiliates", with_rows: [ { "Name" => "Jane Affiliate", "Product" => product.name, "Commission" => "3%" }, ] expect(page).to have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] end it "paginates through search results" do select_disclosure "Search" do fill_in "Search", with: "Affiliate" end expect(page).to have_table "Affiliate", with_rows: [ { "Name" => "Jane Affiliate", "Product" => product.name, "Commission" => "3%" }, ] expect(page).to have_button("Previous", disabled: true) expect(page).to have_button("Next") expect(page).to have_current_path(affiliates_path({ query: "Affiliate" })) expect(page).to_not have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] click_on "2" wait_for_ajax expect(page).to have_table "Affiliate", with_rows: [ { "Name" => "Jim Affiliate", "Product" => product.name, "Commission" => "3%" }, ] expect(page).to have_button("Previous") expect(page).to have_button("Next", disabled: true) expect(page).to have_current_path("#{affiliates_path}?query=Affiliate&page=2") expect(page).to_not have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] end end it "can view individual affiliates and sort them by sales" do seller = create(:user) product = create(:product, name: "Gumbot bits", user: seller, price_cents: 10_00) product_2 = create(:product, name: "100 ChatGPT4 prompts to increase productivity", user: seller, price_cents: 5_00) affiliate_user1 = create(:user, name: "Jane Affiliate") affiliate_user2 = create(:user, name: "Edgar") affiliate_user3 = create(:user, name: "Sally Affiliate") affiliate1 = create(:direct_affiliate, seller:, products: [product, product_2], affiliate_user: affiliate_user1) affiliate2 = create(:direct_affiliate, seller:, products: [product], affiliate_user: affiliate_user2) create(:direct_affiliate, seller:, products: [product], affiliate_user: affiliate_user3) create_list(:purchase_with_balance, 2, affiliate_credit_cents: 100, affiliate: affiliate1, link: product) create(:purchase_with_balance, affiliate_credit_cents: 100, affiliate: affiliate1, link: product_2) create(:purchase_with_balance, affiliate_credit_cents: 100, affiliate: affiliate2, link: product) sign_in seller visit affiliates_path expect(page).to have_table "Affiliates", with_rows: [ { "Name" => affiliate_user1.name, "Product" => "2 products", "Commission" => "3%", "Sales" => "$25" }, { "Name" => affiliate_user2.name, "Product" => product.name, "Commission" => "3%", "Sales" => "$10" }, { "Name" => affiliate_user3.name, "Product" => product.name, "Commission" => "3%", "Sales" => "$0" }, ] find(:table_row, { "Name" => affiliate_user1.name, "Product" => "2 products" }).click within_modal affiliate_user1.name do within_section product.name do expect(page).to have_text("Revenue $20", normalize_ws: true) expect(page).to have_text("Sales 2", normalize_ws: true) expect(page).to have_text("Commission 3%", normalize_ws: true) expect(page).to have_button("Copy link") end within_section product_2.name do expect(page).to have_text("Revenue $5", normalize_ws: true) expect(page).to have_text("Sales 1", normalize_ws: true) expect(page).to have_text("Commission 3%", normalize_ws: true) expect(page).to have_button("Copy link") end expect(page).to have_link("Edit") expect(page).to have_button("Delete") end find(:table_row, { "Name" => affiliate_user2.name, "Product" => product.name }).click within_modal affiliate_user2.name do within_section product.name do expect(page).to have_text("Revenue $10", normalize_ws: true) expect(page).to have_text("Sales 1", normalize_ws: true) expect(page).to have_text("Commission 3%", normalize_ws: true) expect(page).to have_button("Copy link") end expect(page).to have_link("Edit") expect(page).to have_button("Delete") end find(:table_row, { "Name" => affiliate_user3.name, "Product" => product.name }).click within_modal affiliate_user3.name do within_section product.name do expect(page).to have_text("Revenue $0", normalize_ws: true) expect(page).to have_text("Sales 0", normalize_ws: true) expect(page).to have_text("Commission 3%", normalize_ws: true) expect(page).to have_button("Copy link") end expect(page).to have_link("Edit") expect(page).to have_button("Delete") end end context "creating an affiliate" do let(:seller) { create(:named_seller) } include_context "with switching account to user as admin for seller" context "when the creator already has affiliates" do let!(:product_one) { create(:product, user: seller, name: "a product") } let!(:product_two) { create(:product, user: seller, name: "second_product") } let!(:archived_product) { create(:product, user: seller, name: "Archived product", archived: true) } let!(:collab_product) { create(:product, :is_collab, user: seller, name: "Collab product") } let(:existing_affiliate_user) { create(:user, name: "Jane Affiliate", email: "existing_affiliate_user@gum.co") } let!(:existing_affiliate) do create(:direct_affiliate, affiliate_user: existing_affiliate_user, seller:, affiliate_basis_points: 1500, destination_url: "https://example.com") end let(:new_affiliate_user) { create(:user, name: "Joe Affiliate", email: "new_affiliate@gum.co") } let!(:affiliate_request) { create(:affiliate_request, seller:) } before { create(:product_affiliate, product: product_one, affiliate: existing_affiliate, affiliate_basis_points: 1500) } it "creates a new affiliate for all eligible products" do visit affiliates_path wait_for_ajax click_on "Add affiliate" fill_in "Email", with: new_affiliate_user.email expect(page).not_to have_content "Collab product" # excludes ineligible products within :table_row, { "Product" => "All products" } do check "Enable all products" fill_in "Commission", with: "10" fill_in "https://link.com", with: "foo" end click_on "Add affiliate" within :table_row, { "Product" => "All products" } do # validates URL expect(find("fieldset.danger")).to have_field("https://link.com", with: "foo") fill_in "https://link.com", with: "https://my-site.com#section?foo=bar&baz=qux" end click_on "Add affiliate" # Show the most recently updated affiliate as the first row expect(page).to have_table "Affiliates", with_rows: [ { "Name" => new_affiliate_user.name, "Products" => "2 products", "Commission" => "10%" }, { "Name" => existing_affiliate_user.name, "Products" => product_one.name, "Commission" => "15%" } ] expect(page).to have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] find(:table_row, { "Name" => new_affiliate_user.name, "Product" => "2 products" }).click within_modal new_affiliate_user.name do within_section product_one.name do expect(page).to have_text("Revenue $0", normalize_ws: true) expect(page).to have_text("Sales 0", normalize_ws: true) expect(page).to have_text("Commission 10%", normalize_ws: true) expect(page).to have_button("Copy link") end within_section product_two.name do expect(page).to have_text("Revenue $0", normalize_ws: true) expect(page).to have_text("Sales 0", normalize_ws: true) expect(page).to have_text("Commission 10%", normalize_ws: true) expect(page).to have_button("Copy link") end expect(page).to have_link("Edit") expect(page).to have_button("Delete") end new_direct_affiliate = DirectAffiliate.find_by(affiliate_user_id: new_affiliate_user.id) expect(new_direct_affiliate.apply_to_all_products).to be true expect(new_direct_affiliate.destination_url).to eq "https://my-site.com#section?foo=bar&baz=qux" expect(new_direct_affiliate.products).to match_array [product_one, product_two] end it "creates a new affiliate for one specific enabled product" do visit affiliates_path wait_for_ajax click_on "Add affiliate" fill_in "Email", with: new_affiliate_user.email within :table_row, { "Product" => "All products" } do check "Enable all products" fill_in "Commission", with: "10" uncheck "Enable all products" end within :table_row, { "Product" => product_one.name } do check "Enable product" fill_in "Commission", with: "5" end fill_in "https://link.com", with: "http://google.com/" click_on "Add affiliate" # Show the most recently updated affiliate as the first row expect(page).to have_table "Affiliates", with_rows: [ { "Name" => new_affiliate_user.name, "Product" => product_one.name, "Commission" => "5%" }, { "Name" => existing_affiliate_user.name, "Product" => product_one.name, "Commission" => "15%" } ] find(:table_row, { "Name" => new_affiliate_user.name, "Product" => product_one.name }).click within_modal new_affiliate_user.name do within_section product_one.name do expect(page).to have_text("Revenue $0", normalize_ws: true) expect(page).to have_text("Sales 0", normalize_ws: true) expect(page).to have_text("Commission 5%", normalize_ws: true) expect(page).to have_button("Copy link") end expect(page).to have_link("Edit") expect(page).to have_button("Delete") end new_direct_affiliate = DirectAffiliate.find_by(affiliate_user_id: new_affiliate_user.id) expect(new_direct_affiliate.apply_to_all_products).to be false product_affiliate = new_direct_affiliate.product_affiliates.first expect(product_affiliate.link_id).to eq product_one.id expect(product_affiliate.affiliate_basis_points).to eq 500 end it "creates a new affiliate for specific enabled products" do visit affiliates_path wait_for_ajax click_on "Add affiliate" fill_in "Email", with: new_affiliate_user.email within :table_row, { "Product" => product_one.name } do check "Enable product" fill_in "Commission", with: "15" fill_in "https://link.com", with: "https://gumroad.com" end within :table_row, { "Product" => product_two.name } do check "Enable product" fill_in "Commission", with: "5" fill_in "https://link.com", with: "http://google.com/" end click_on "Add affiliate" wait_for_ajax # Show the most recently updated affiliate as the first row expect(page).to have_table "Affiliates", with_rows: [ { "Name" => new_affiliate_user.name, "Products" => "2 products", "Commission" => "5% - 15%" }, { "Name" => existing_affiliate_user.name, "Products" => product_one.name, "Commission" => "15%" }, ] new_direct_affiliate = DirectAffiliate.find_by(affiliate_user_id: new_affiliate_user.id) within :table_row, { "Products" => "2 products" } do expect(page).to have_link("2 products", href: new_direct_affiliate.referral_url) find(:table_cell, "Products").find("a").hover expect(page).to have_text("#{product_one.name} (15%), #{product_two.name} (5%)") end within :table_row, { "Products" => product_one.name, "Name" => existing_affiliate_user.name } do expect(page).to have_link(product_one.name, href: existing_affiliate.referral_url_for_product(product_one)) end expect(new_direct_affiliate.apply_to_all_products).to be false product_affiliate_1, product_affiliate_2 = new_direct_affiliate.product_affiliates.to_a expect(product_affiliate_1.link_id).to eq product_one.id expect(product_affiliate_1.affiliate_basis_points).to eq 1500 expect(product_affiliate_1.destination_url).to eq "https://gumroad.com" expect(product_affiliate_2.link_id).to eq product_two.id expect(product_affiliate_2.affiliate_basis_points).to eq 500 expect(product_affiliate_2.destination_url).to eq "http://google.com/" end it "displays an error message if the user is already an affiliate with the same settings" do visit affiliates_path wait_for_ajax click_on "Add affiliate" fill_in "Email", with: existing_affiliate_user.email within :table_row, { "Product" => product_one.name } do check "Enable product" fill_in "Commission", with: "15" fill_in "https://link.com", with: existing_affiliate.destination_url end click_on "Add affiliate" expect_alert_message("This affiliate already exists.") end it "does not allow adding an affiliate if creator is using a Brazilian Stripe Connect account" do brazilian_stripe_account = create(:merchant_account_stripe_connect, user: seller, country: "BR") seller.update!(check_merchant_account_is_linked: true) expect(seller.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq brazilian_stripe_account visit affiliates_path link = find_link("Add affiliate", inert: true) link.hover expect(link[:style]).to eq "pointer-events: none; cursor: not-allowed; opacity: 0.3;" expect(link).to have_tooltip(text: "Affiliates with Brazilian Stripe accounts are not supported.") end end end context "editing an affiliate" do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller, name: "a product") } let!(:product_2) { create(:product, user: seller, name: "another product") } let!(:archived_product) { create(:product, user: seller, name: "Archived product", archived: true) } let!(:archived_product_not_selected) { create(:product, user: seller, name: "Archived product not selected", archived: true) } let!(:collab_product) { create(:product, :is_collab, user: seller, name: "Collab product") } let(:affiliate_user) { create(:user, name: "Gumbot1", email: "affiliate@gum.co") } let(:affiliate_user2) { create(:user, name: "Gumbot2", email: "affiliate2@gum.co") } let(:direct_affiliate) { create(:direct_affiliate, affiliate_user:, seller:, affiliate_basis_points: 1500) } let(:direct_affiliate2) { create(:direct_affiliate, affiliate_user: affiliate_user2, seller:, affiliate_basis_points: 1500) } let!(:affiliate_request) { create(:affiliate_request, seller:) } include_context "with switching account to user as admin for seller" before do create(:product_affiliate, affiliate: direct_affiliate, product:, affiliate_basis_points: 1500, destination_url: "https://example.com", updated_at: 4.days.ago) create(:product_affiliate, affiliate: direct_affiliate, product: archived_product, affiliate_basis_points: 1500, destination_url: "https://example.com", updated_at: 3.days.ago) create(:product_affiliate, affiliate: direct_affiliate2, product:, affiliate_basis_points: 1500, destination_url: "https://example.com", updated_at: 2.days.ago) end it "edits an affiliate" do visit affiliates_path within :table_row, { "Name" => "Gumbot1" } do click_on "Edit" end # make sure the fields are set expect(page).to have_field("Email", with: affiliate_user.email, disabled: true) expect(page).to have_unchecked_field("Enable all products") expect(page).not_to have_content "Collab product" # excludes ineligible products within :table_row, { "Product" => "a product" } do expect(page).to have_checked_field("Enable product") expect(page).to have_field("Commission", with: "15") expect(page).to have_field("https://link.com", with: "https://example.com") end within :table_row, { "Product" => "another product" } do expect(page).to have_unchecked_field("Enable product") expect(page).to have_field("Commission", with: "15", disabled: true) # edit fields check "Enable product" fill_in "Commission", with: "10" fill_in "https://link.com", with: "http://google.com/" end within :table_row, { "Product" => "Archived product" } do expect(page).to have_checked_field("Enable product") expect(page).to have_field("Commission", with: "15") expect(page).to have_field("https://link.com", with: "https://example.com") end expect(page).not_to have_table_row({ "Product" => archived_product_not_selected.name }) click_on "Save changes" expect_alert_message("Affiliate updated successfully") # Show the most recently updated affiliate as the first row expect(page).to have_table "Affiliates", with_rows: [ { "Name" => affiliate_user.name, "Products" => "3 products", "Commission" => "10% - 15%" }, { "Name" => affiliate_user2.name, "Products" => product.name, "Commission" => "15%" }, ] expect(page).to have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] product_affiliate = direct_affiliate.product_affiliates.find_by(link_id: product_2.id) expect(product_affiliate.affiliate_basis_points).to eq 1000 expect(product_affiliate.destination_url).to eq "http://google.com/" end it "refreshes table to page 1 after editting an affiliate" do stub_const("AffiliatesPresenter::PER_PAGE", 1) visit affiliates_path click_on "2" wait_for_ajax click_on "Edit" within :table_row, { "Product" => "another product" } do check "Enable product" fill_in "Commission", with: "10" fill_in "https://link.com", with: "http://google.com/" end click_on "Save changes" expect_alert_message("Affiliate updated successfully") expect(page).to have_current_path(affiliates_path) expect(page).to have_button("Previous", disabled: true) expect(page).to have_button("Next") # Show the most recently updated affiliate as the first row expect(page).to have_table "Affiliates", with_rows: [ { "Name" => affiliate_user.name, "Products" => "3 products", "Commission" => "10% - 15%" }, ] expect(page).to have_table "Requests", with_rows: [{ "Name" => affiliate_request.name }] end it "can associate an affiliate with all products" do visit affiliates_path within :table_row, { "Name" => "Gumbot1" } do click_on "Edit" end check "Enable all products" click_on "Save changes" expect_alert_message("Affiliate updated successfully") expect(page).to have_table "Affiliates" expect(direct_affiliate.reload.apply_to_all_products).to be true expect(direct_affiliate.affiliate_basis_points).to eq 1500 expect(direct_affiliate.product_affiliates.count).to eq(2) expect(page).to have_table_row({ "Name" => affiliate_user.name, "Products" => "2 products", "Commission" => "15%" }) end it "can clear affiliate products" do visit affiliates_path within :table_row, { "Name" => "Gumbot1" } do click_on "Edit" end # select then deselect all products check "Enable all products" uncheck "Enable all products" click_on "Save changes" expect_alert_message("Please enable at least one product") end end context "with switching account to user as admin for seller" do let(:seller) { create(:named_seller) } let(:affiliate_user) { create(:user, name: "Gumbot Affiliate", email: "old_affiliate@gum.co") } let(:product) { create(:product, user: seller, name: "a product") } include_context "with switching account to user as admin for seller" it "copies an affiliate link" do create(:direct_affiliate, affiliate_user:, seller:, affiliate_basis_points: 1500, products: [product]) visit affiliates_path click_on "Copy link" expect(page).to have_selector("[role='tooltip']", text: "Copied!") end it "removes an affiliate from the table" do create(:direct_affiliate, affiliate_user:, seller:, affiliate_basis_points: 1500, products: [product]) visit affiliates_path click_on "Delete" wait_for_ajax expect_alert_message("Affiliate deleted successfully") end it "removes an affiliate from the aside drawer" do create(:direct_affiliate, affiliate_user:, seller:, affiliate_basis_points: 1500, products: [product]) visit affiliates_path expect(page).to have_table "Affiliates", with_rows: [ { "Name" => affiliate_user.name, "Product" => product.name, "Commission" => "15%", "Sales" => "$0" } ] find(:table_row, { "Name" => affiliate_user.name, "Product" => product.name }).click within_modal affiliate_user.name do click_on "Delete" end wait_for_ajax expect_alert_message("Affiliate deleted successfully") end it "approves all pending affiliates" do Feature.activate_user(:auto_approve_affiliates, seller) pending_requests = create_list(:affiliate_request, 2, seller:) visit affiliates_path click_on "Approve all" wait_for_ajax expect_alert_message("Approved all pending affiliate requests!") pending_requests.each do |request| expect(request.reload).to be_approved end end end describe "Affiliate requests" do let(:seller) { create(:named_seller) } let(:affiliate_user) { create(:user) } let!(:request_one) { create(:affiliate_request, email: affiliate_user.email, seller:) } let!(:request_two) { create(:affiliate_request, name: "Jane Doe", seller:) } let!(:request_three) { create(:affiliate_request, name: "Will Smith", seller:) } let!(:request_four) { create(:affiliate_request, name: "Rob Cook", seller:) } before do request_three.approve! end include_context "with switching account to user as admin for seller" it "displays unattended affiliate requests and allows seller to approve and ignore them" do visit(affiliates_path) expect(page).to have_text("Jane") expect(page).to have_text("John") expect(page).to have_text("Will") expect(page).to have_text("Rob") # Sort by name find_and_click("th", text: "Name") # Verify that Will's request is already approved but because # he hasn't created an account yet, it shows disabled "Approved" button within all("tr")[4] do expect(page).to have_button("Approved", disabled: true) # Nothing should happen on clicking the disabled "Approved" button click_on("Approved", disabled: true) expect(page).to have_text("Will") # Ignore Will's request expect do click_on("Ignore") wait_for_ajax end.to change { request_three.reload.state }.to eq("ignored") end expect(page).to_not have_text("Will") # Ignore Jane's request within all("tr")[1] do expect do click_on("Ignore") wait_for_ajax end.to change { request_two.reload.state }.to eq("ignored") end expect(page).to_not have_text("Jane") # Approve John's request within all("tr")[1] do expect do click_on("Approve") wait_for_ajax end.to change { request_one.reload.state }.to eq("approved") end expect(page).to_not have_text("John") # Approve Rob's request within all("tr")[1] do expect do click_on("Approve") wait_for_ajax end.to change { request_four.reload.state }.to eq("approved") # But because Rob doesn't have an account yet, his request won't go away expect(page).to have_text("Rob") # Ignore Rob's request expect do click_on("Ignore") wait_for_ajax end.to change { request_four.reload.state }.to eq("ignored") end expect(page).to_not have_text("Rob") expect(page).to have_text("No requests yet") end end describe "sorting" do let!(:seller) { create(:user) } let!(:product1) { create(:product, user: seller, name: "p1", price_cents: 10_00) } let!(:product2) { create(:product, user: seller, name: "p2", price_cents: 10_00) } let!(:product3) { create(:product, user: seller, name: "p3", price_cents: 10_00) } let!(:product4) { create(:product, user: seller, name: "p4", price_cents: 10_00) } let!(:affiliate_user_1) { create(:direct_affiliate, seller:, affiliate_user: create(:user, name: "alice"), products: [product1]) } let!(:affiliate_user_2) { create(:direct_affiliate, seller:, affiliate_user: create(:user, name: "bob"), products: [product1, product2, product3]) } let!(:affiliate_user_3) { create(:direct_affiliate, seller:, affiliate_user: create(:user, name: "david@example.com"), products: [product1, product3]) } let!(:affiliate_user_4) { create(:direct_affiliate, seller:, affiliate_user: create(:user, name: "aff4"), products: [product1, product2, product3, product4]) } let!(:affiliate_request) { create(:affiliate_request, seller:) } before do MerchantAccount.find_or_create_by!(
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/workflows_spec.rb
spec/requests/workflows_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" require "shared_examples/creator_dashboard_page" describe("Workflows", js: true, type: :system) do include PostHelpers def find_email_row(name) find("[aria-label='Email'] h3", text: name, exact_text: true).ancestor("[aria-label='Email']") end def find_abandoned_cart_item(name) find("[role=listitem] h4", text: name, exact_text: true).ancestor("[role=listitem]") end def have_abandoned_cart_item(name) have_selector("[role=listitem] h4", text: name, exact_text: true) end let(:seller) { create(:named_seller) } before do @product = create(:product, name: "product name", user: seller, created_at: 2.hours.ago) @product2 = create(:product, name: "product 2 name", user: seller, created_at: 1.hour.ago) create(:purchase, link: @product) index_model_records(Purchase) allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE) create(:merchant_account_stripe_connect, user: seller) create(:payment_completed, user: seller) end include_context "with switching account to user as admin for seller" it_behaves_like "creator dashboard page", "Workflows" do let(:path) { workflows_path } end describe "workflow list page" do it "shows the workflows" do # When there are no alive workflows deleted_workflow = create(:workflow, seller:, name: "Deleted workflow", deleted_at: Time.current) visit workflows_path expect(page).to_not have_text(deleted_workflow.name) expect(page).to have_text("Automate emails with ease.") # When there is an alive workflow that is not published and doesn't have any installments unpublished_workflow = create(:workflow, seller:, name: "Test workflow") visit workflows_path expect(page).to_not have_text("Automate emails with ease.") expect(page).to_not have_table(unpublished_workflow.name) within_section unpublished_workflow.name, section_element: :section do expect(page).to have_text("Unpublished") expect(page).to have_text("No emails yet, add one") expect(page).to have_link("add one", href: workflow_emails_path(unpublished_workflow.external_id)) end # When there is an alive workflow that is published and doesn't have any installments published_workflow = create(:audience_workflow, seller:, name: "Greet new customers", published_at: 1.day.ago) visit workflows_path expect(page).to_not have_table(published_workflow.name) within_section published_workflow.name, section_element: :section do expect(page).to have_text("Published") expect(page).to have_text("No emails yet, add one") end # When there is an alive workflow that is unpublished and have installments unpublished_workflow_installment1 = create(:installment, workflow: unpublished_workflow, name: "Unpublished legacy installment") create(:installment_rule, installment: unpublished_workflow_installment1, time_period: "day", delayed_delivery_time: 1.hour.to_i) unpublished_workflow_installment2 = create(:published_installment, workflow: unpublished_workflow, name: "Installment 2") create(:installment_rule, installment: unpublished_workflow_installment2, time_period: "hour", delayed_delivery_time: 1.day.to_i) unpublished_workflow_installment3 = create(:published_installment, workflow: unpublished_workflow, name: "Installment 3") create(:installment_rule, installment: unpublished_workflow_installment3, time_period: "hour", delayed_delivery_time: 2.hours.to_i) visit workflows_path within_table unpublished_workflow.name do expect(page).to have_text("Unpublished") expect(page).to have_table_row({ "Email" => unpublished_workflow_installment1.name }) expect(page).to have_table_row({ "Email" => unpublished_workflow_installment2.name }) expect(page).to_not have_table_row({ "Email" => unpublished_workflow_installment2.name, "Delay" => "24 Hours", "Sent" => "0", "Opens" => "0%", "Clicks" => "0" }) expect(page).to have_table_row({ "Email" => unpublished_workflow_installment3.name }) expect(page).to_not have_table_row({ "Email" => unpublished_workflow_installment3.name, "Delay" => "2 Hours", "Sent" => "0", "Opens" => "0%", "Clicks" => "0" }) end # When there is an alive workflow that is published and have installments published_workflow_installment1 = create(:installment, workflow: published_workflow, name: "Unpublished legacy installment") create(:installment_rule, installment: published_workflow_installment1, time_period: "day", delayed_delivery_time: 1.hour.to_i) published_workflow_installment2 = create(:published_installment, workflow: published_workflow, name: "Installment 2") create(:installment_rule, installment: published_workflow_installment2, time_period: "hour", delayed_delivery_time: 1.day.to_i) published_workflow_installment3 = create(:published_installment, workflow: published_workflow, name: "Installment 3") create(:installment_rule, installment: published_workflow_installment3, time_period: "hour", delayed_delivery_time: 2.hours.to_i) visit workflows_path within_table published_workflow.name do expect(page).to have_text("Published") expect(page).to have_table_row({ "Email" => published_workflow_installment1.name }) expect(page).to have_table_row({ "Email" => published_workflow_installment2.name, "Delay" => "24 Hours", "Sent" => "0", "Opens" => "0%", "Clicks" => "0" }) expect(page).to have_table_row({ "Email" => published_workflow_installment3.name, "Delay" => "2 Hours", "Sent" => "0", "Opens" => "0%", "Clicks" => "0" }) end # Deletes a workflow within_table published_workflow.name do click_on "Delete" end expect(page).to have_text(%Q(Are you sure you want to delete the workflow "#{published_workflow.name}"? This action cannot be undone.)) click_on "Cancel" expect(page).to_not have_alert(text: "Workflow deleted!") expect(page).to have_text(published_workflow.name) within_table published_workflow.name do click_on "Delete" end expect do click_on "Delete" expect(page).to have_alert(text: "Workflow deleted!") expect(page).to_not have_text(published_workflow.name) end.to change { Workflow.alive.count }.by(-1) .and change { published_workflow.reload.deleted_at }.from(nil).to(be_within(5.seconds).of(DateTime.current)) end end describe "new workflow scenario" do before do create(:payment_completed, user: seller) end it "performs validations" do visit workflows_path click_on "New workflow", match: :first expect(page).to have_radio_button "Purchase", checked: true click_on "Save and continue" expect(find_field("Name")).to have_ancestor("fieldset.danger") fill_in "Name", with: "A workflow" expect(find_field("Name")).to_not have_ancestor("fieldset.danger") click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") workflow = Workflow.last expect(workflow.name).to eq("A workflow") edit_workflow_path = edit_workflow_path(workflow.external_id) visit edit_workflow_path expect(page).to have_input_labelled "Name", with: "A workflow" fill_in "Paid more than", with: "10" fill_in "Paid less than", with: "1" click_on "Save changes" expect(find_field("Paid more than")).to have_ancestor("fieldset.danger") expect(find_field("Paid less than")).to have_ancestor("fieldset.danger") fill_in "Paid less than", with: "20" expect(find_field("Paid more than")).to_not have_ancestor("fieldset.danger") expect(find_field("Paid less than")).to_not have_ancestor("fieldset.danger") click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(workflow.reload.paid_more_than_cents).to eq(1_000) expect(workflow.paid_less_than_cents).to eq(2_000) visit edit_workflow_path expect(page).to have_input_labelled "Paid more than", with: "10" expect(page).to have_input_labelled "Paid less than", with: "20" fill_in "Purchased after", with: "01/01/2023" fill_in "Purchased before", with: "01/01/2022" click_on "Save changes" expect(find_field("Purchased after")).to have_ancestor("fieldset.danger") expect(find_field("Purchased before")).to have_ancestor("fieldset.danger") fill_in "Purchased before", with: "01/01/2024" expect(find_field("Purchased after")).to_not have_ancestor("fieldset.danger") expect(find_field("Purchased before")).to_not have_ancestor("fieldset.danger") click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") timezone = ActiveSupport::TimeZone[workflow.seller.timezone] expect(workflow.reload.created_after).to eq(timezone.parse("2023-01-01").as_json) expect(workflow.created_before).to eq(timezone.parse("2024-01-01").end_of_day.as_json) visit edit_workflow_path expect(page).to have_input_labelled "Purchased after", with: "2023-01-01" expect(page).to have_input_labelled "Purchased before", with: "2024-01-01" end it "shows corresponding fields on choosing a trigger" do visit workflows_path click_on "New workflow", match: :first expect(page).to have_radio_button "Purchase", checked: true expect(page).to have_unchecked_field "Also send to past customers" expect(page).to have_combo_box "Has bought" expect(page).to have_combo_box "Has not yet bought" expect(page).to have_input_labelled "Paid more than", with: "" expect(page).to have_input_labelled "Paid less than", with: "" expect(page).to have_input_labelled "Purchased after", with: "" expect(page).to have_input_labelled "Purchased before", with: "" expect(page).to have_select "From", selected: "Anywhere" choose "New subscriber" expect(page).to have_unchecked_field "Also send to past email subscribers" expect(page).to have_combo_box "Has bought" expect(page).to have_combo_box "Has not yet bought" expect(page).to_not have_field "Paid more than" expect(page).to_not have_field "Paid less than" expect(page).to have_input_labelled "Subscribed after", with: "" expect(page).to have_input_labelled "Subscribed before", with: "" expect(page).to_not have_select "From" choose "Member cancels" expect(page).to have_unchecked_field "Also send to past members who canceled" expect(page).to have_combo_box "Is a member of" expect(page).to_not have_combo_box "Has not yet bought" expect(page).to have_input_labelled "Paid more than", with: "" expect(page).to have_input_labelled "Paid less than", with: "" expect(page).to have_input_labelled "Canceled after", with: "" expect(page).to have_input_labelled "Canceled before", with: "" expect(page).to have_select "From", selected: "Anywhere" choose "New affiliate" expect(page).to have_unchecked_field "Also send to past affiliates" expect(page).to_not have_combo_box "Has bought" expect(page).to_not have_combo_box "Has not yet bought" expect(page).to have_combo_box "Affiliated products" expect(page).to have_unchecked_field "All products" expect(page).to_not have_field "Paid more than" expect(page).to_not have_field "Paid less than" expect(page).to have_input_labelled "Affiliate after", with: "" expect(page).to have_input_labelled "Affiliate before", with: "" expect(page).to_not have_select "From" choose "Abandoned cart" expect(page).to_not have_field "Also send to past customers" expect(page).to have_combo_box "Has products in abandoned cart" expect(page).to have_combo_box "Does not have products in abandoned cart" expect(page).to_not have_field "Paid more than" expect(page).to_not have_field "Paid less than" expect(page).to_not have_field "Purchased after" expect(page).to_not have_field "Purchased before" expect(page).to_not have_select "From" end it "allows selecting or unselecting all affiliated products with a single click" do visit workflows_path click_on "New workflow", match: :first choose "New affiliate" expect(page).to have_unchecked_field "All products" find(:label, "Affiliated products").click expect(page).to have_combo_box "Affiliated products", options: ["product 2 name", "product name"] send_keys(:escape) check "All products" within :fieldset, "Affiliated products" do ["product 2 name", "product name"].each do |option| expect(page).to have_button(option) end click_on "product name" send_keys(:escape) expect(page).to have_button("product 2 name") expect(page).to_not have_button("product name") expect(page).to have_unchecked_field("All products") end find(:label, "Affiliated products").click expect(page).to have_combo_box "Affiliated products", options: ["product name"] select_combo_box_option "product name", from: "Affiliated products" expect(page).to have_checked_field("All products") uncheck "All products" within :fieldset, "Affiliated products" do ["product 2 name", "product name"].each do |option| expect(page).to_not have_button(option) end end find(:label, "Affiliated products").click expect(page).to have_combo_box "Affiliated products", options: ["product 2 name", "product name"] end it "doesn't include archived products in the product dropdowns" do @product.update!(archived: true) # Archived and has sales @product2.update!(archived: true) # Archived and has no sales create(:product, name: "My product", user: seller) visit workflows_path click_on "New workflow", match: :first find(:label, "Has bought").click expect(page).to have_combo_box "Has bought", options: ["My product"] send_keys(:escape) find(:label, "Has not yet bought").click expect(page).to have_combo_box "Has not yet bought", options: ["My product"] choose "New affiliate" expect(page).to have_unchecked_field "All products" find(:label, "Affiliated products").click expect(page).to have_combo_box "Affiliated products", options: ["My product"] end it "allows creating a follower workflow" do visit workflows_path click_on "New workflow", match: :first choose "New subscriber" check "Also send to past email subscribers" fill_in "Name", with: "New subscriber workflow" select_combo_box_option @product.name, from: "Has bought" select_combo_box_option @product2.name, from: "Has not yet bought" fill_in "Subscribed before", with: "01/01/2023" click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") workflow = Workflow.last expect(workflow.name).to eq("New subscriber workflow") expect(workflow.workflow_type).to eq(Workflow::FOLLOWER_TYPE) expect(workflow.workflow_trigger).to be_nil expect(workflow.send_to_past_customers).to be(true) expect(workflow.seller).to eq(seller) expect(workflow.link).to be_nil expect(workflow.published_at).to be_nil expect(workflow.bought_products).to eq([@product.unique_permalink]) expect(workflow.not_bought_products).to eq([@product2.unique_permalink]) expect(workflow.bought_variants).to be_nil expect(workflow.not_bought_variants).to be_nil expect(workflow.created_after).to be_nil expect(workflow.created_before).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2023-01-01").end_of_day.as_json) expect(workflow.bought_from).to be_nil end it "allows creating a seller workflow for all products" do visit workflows_path click_on "New workflow", match: :first expect(page).to have_radio_button "Purchase", checked: true check "Also send to past customers" fill_in "Name", with: "Seller workflow" click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") workflow = Workflow.last expect(workflow.name).to eq("Seller workflow") expect(workflow.workflow_type).to eq(Workflow::SELLER_TYPE) expect(workflow.send_to_past_customers).to be(true) expect(workflow.workflow_trigger).to be_nil expect(workflow.seller).to eq(seller) expect(workflow.link).to be_nil expect(workflow.published_at).to be_nil expect(workflow.bought_products).to be_nil expect(workflow.not_bought_products).to be_nil expect(workflow.bought_variants).to be_nil expect(workflow.not_bought_variants).to be_nil end it "allows creating a seller workflow for multiple products" do visit workflows_path click_on "New workflow", match: :first expect(page).to have_radio_button "Purchase", checked: true fill_in "Name", with: "Seller workflow" select_combo_box_option @product.name, from: "Has bought" select_combo_box_option @product2.name, from: "Has bought" click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") workflow = Workflow.last expect(workflow.name).to eq("Seller workflow") expect(workflow.workflow_type).to eq(Workflow::SELLER_TYPE) expect(workflow.send_to_past_customers).to be(false) expect(workflow.workflow_trigger).to be_nil expect(workflow.seller).to eq(seller) expect(workflow.link).to be_nil expect(workflow.published_at).to be_nil expect(workflow.bought_products).to match_array([@product.unique_permalink, @product2.unique_permalink]) expect(workflow.not_bought_products).to be_nil expect(workflow.bought_variants).to be_nil expect(workflow.not_bought_variants).to be_nil end it "allows creating a product workflow" do variant_category = create(:variant_category, link: @product) create(:variant, variant_category:, name: "Version 1") create(:variant, variant_category:, name: "Version 2") visit workflows_path click_on "New workflow", match: :first expect(page).to have_radio_button "Purchase", checked: true check "Also send to past customers" fill_in "Name", with: "Product workflow" select_combo_box_option @product.name, from: "Has bought" select_combo_box_option @product2.name, from: "Has not yet bought" fill_in "Paid more than", with: "1" fill_in "Paid less than", with: "10" fill_in "Purchased after", with: "01/01/2023" select "Canada", from: "From" click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") workflow = Workflow.last expect(workflow.name).to eq("Product workflow") expect(workflow.workflow_type).to eq(Workflow::PRODUCT_TYPE) expect(workflow.send_to_past_customers).to be(true) expect(workflow.workflow_trigger).to be_nil expect(workflow.seller).to eq(seller) expect(workflow.link).to eq(@product) expect(workflow.published_at).to be_nil expect(workflow.bought_products).to eq([@product.unique_permalink]) expect(workflow.not_bought_products).to eq([@product2.unique_permalink]) expect(workflow.bought_variants).to be_nil expect(workflow.not_bought_variants).to be_nil expect(workflow.paid_more_than_cents).to eq(100) expect(workflow.paid_less_than_cents).to eq(1_000) expect(workflow.created_after).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2023-01-01").as_json) expect(workflow.created_before).to be_nil expect(workflow.bought_from).to eq("Canada") end it "allows creating a variant workflow" do variant_category = create(:variant_category, link: @product) _variant1 = create(:variant, variant_category:, name: "Version 1") variant2 = create(:variant, variant_category:, name: "Version 2") visit workflows_path click_on "New workflow", match: :first expect(page).to have_radio_button "Purchase", checked: true fill_in "Name", with: "Variant workflow" select_combo_box_option variant2.name, from: "Has bought" click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") workflow = Workflow.last expect(workflow.name).to eq("Variant workflow") expect(workflow.workflow_type).to eq(Workflow::VARIANT_TYPE) expect(workflow.workflow_trigger).to be_nil expect(workflow.seller).to eq(seller) expect(workflow.link).to eq(@product) expect(workflow.published_at).to be_nil expect(workflow.bought_products).to be_nil expect(workflow.not_bought_products).to be_nil expect(workflow.bought_variants).to eq([variant2.external_id]) expect(workflow.not_bought_variants).to be_nil expect(workflow.base_variant).to eq(variant2) end it "allows creating a variant workflow for physical product using sku" do product = create(:physical_product, user: seller) variant_category1 = create(:variant_category, link: product, title: "Brand") create(:variant, variant_category: variant_category1, name: "Nike") create(:variant, variant_category: variant_category1, name: "Adidas") variant_category2 = create(:variant_category, link: product, title: "Style") create(:variant, variant_category: variant_category2, name: "Running") create(:variant, variant_category: variant_category2, name: "Walking") Product::SkusUpdaterService.new(product:).perform visit workflows_path click_on "New workflow", match: :first expect(page).to have_radio_button "Purchase", checked: true fill_in "Name", with: "Variant workflow" select_combo_box_option "Adidas - Walking", from: "Has bought" click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") sku = Sku.find_by_name("Adidas - Walking") workflow = Workflow.last expect(workflow.name).to eq("Variant workflow") expect(workflow.workflow_type).to eq(Workflow::VARIANT_TYPE) expect(workflow.workflow_trigger).to be_nil expect(workflow.send_to_past_customers).to be(false) expect(workflow.seller).to eq(seller) expect(workflow.link).to eq(product) expect(workflow.published_at).to be_nil expect(workflow.bought_products).to be_nil expect(workflow.not_bought_products).to be_nil expect(workflow.bought_variants).to eq([sku.external_id]) expect(workflow.not_bought_variants).to be_nil expect(workflow.base_variant).to eq(sku) end it "allows creating a member cancelation workflow of product type" do visit workflows_path click_on "New workflow", match: :first choose "Member cancels" check "Also send to past members who canceled" fill_in "Name", with: "Member cancelation workflow" select_combo_box_option @product.name, from: "Is a member of" fill_in "Paid more than", with: "1" fill_in "Paid less than", with: "10" fill_in "Canceled after", with: "01/01/2023" select "Canada", from: "From" click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") workflow = Workflow.last expect(workflow.name).to eq("Member cancelation workflow") expect(workflow.workflow_type).to eq(Workflow::PRODUCT_TYPE) expect(workflow.workflow_trigger).to eq("member_cancellation") expect(workflow.send_to_past_customers).to be(true) expect(workflow.seller).to eq(seller) expect(workflow.link).to eq(@product) expect(workflow.published_at).to be_nil expect(workflow.bought_products).to eq([@product.unique_permalink]) expect(workflow.not_bought_products).to be_nil expect(workflow.bought_variants).to be_nil expect(workflow.not_bought_variants).to be_nil expect(workflow.paid_more_than_cents).to eq(100) expect(workflow.paid_less_than_cents).to eq(1_000) expect(workflow.created_after).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2023-01-01").as_json) expect(workflow.created_before).to be_nil expect(workflow.bought_from).to eq("Canada") end it "allows creating a member cancelation workflow of variant type" do variant_category = create(:variant_category, link: @product) _variant1 = create(:variant, variant_category:, name: "Version 1") variant2 = create(:variant, variant_category:, name: "Version 2") visit workflows_path click_on "New workflow", match: :first choose "Member cancels" fill_in "Name", with: "Member cancelation workflow" select_combo_box_option variant2.name, from: "Is a member of" fill_in "Paid more than", with: "1" fill_in "Paid less than", with: "10" fill_in "Canceled after", with: "01/01/2023" select "Canada", from: "From" click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") workflow = Workflow.last expect(workflow.name).to eq("Member cancelation workflow") expect(workflow.workflow_type).to eq(Workflow::VARIANT_TYPE) expect(workflow.workflow_trigger).to eq("member_cancellation") expect(workflow.send_to_past_customers).to be(false) expect(workflow.seller).to eq(seller) expect(workflow.link).to eq(@product) expect(workflow.published_at).to be_nil expect(workflow.bought_products).to be_nil expect(workflow.not_bought_products).to be_nil expect(workflow.bought_variants).to eq([variant2.external_id]) expect(workflow.base_variant).to eq(variant2) expect(workflow.not_bought_variants).to be_nil expect(workflow.paid_more_than_cents).to eq(100) expect(workflow.paid_less_than_cents).to eq(1_000) expect(workflow.created_after).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2023-01-01").as_json) expect(workflow.created_before).to be_nil expect(workflow.bought_from).to eq("Canada") end it "allows creating a new affiliate workflow" do visit workflows_path click_on "New workflow", match: :first choose "New affiliate" check "Also send to past affiliates" fill_in "Name", with: "New affiliate workflow" select_combo_box_option @product.name, from: "Affiliated products" fill_in "Affiliate after", with: "01/01/2023" fill_in "Affiliate before", with: "01/01/2024" click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") workflow = Workflow.last expect(workflow.name).to eq("New affiliate workflow") expect(workflow.workflow_type).to eq(Workflow::AFFILIATE_TYPE) expect(workflow.workflow_trigger).to be_nil expect(workflow.send_to_past_customers).to be(true) expect(workflow.seller).to eq(seller) expect(workflow.link).to be_nil expect(workflow.published_at).to be_nil expect(workflow.bought_products).to be_nil expect(workflow.not_bought_products).to be_nil expect(workflow.bought_variants).to be_nil expect(workflow.not_bought_variants).to be_nil expect(workflow.affiliate_products).to eq([@product.unique_permalink]) expect(workflow.created_after).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2023-01-01").as_json) expect(workflow.created_before).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2024-01-01").end_of_day.as_json) end it "allows creating an abandoned cart workflow with a ready-made installment" do product3 = create(:product, name: "Product 3", user: seller) variant_category = create(:variant_category, link: product3) create(:variant, variant_category:, name: "Version 1") product3_version2 = create(:variant, variant_category:, name: "Version 2") product4 = create(:product, name: "Product 4", user: seller) product5 = create(:product, name: "Product 5", user: seller) visit workflows_path click_on "New workflow", match: :first choose "Abandoned cart" fill_in "Name", with: "Abandoned cart workflow" select_combo_box_option @product.name, from: "Has products in abandoned cart" select_combo_box_option "Product 3 — Version 2", from: "Has products in abandoned cart" select_combo_box_option product4.name, from: "Has products in abandoned cart" select_combo_box_option product5.name, from: "Has products in abandoned cart" select_combo_box_option @product2.name, from: "Does not have products in abandoned cart" click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") workflow = Workflow.last expect(workflow.name).to eq("Abandoned cart workflow") expect(workflow.workflow_type).to eq(Workflow::ABANDONED_CART_TYPE) expect(workflow.workflow_trigger).to be_nil expect(workflow.seller).to eq(seller) expect(workflow.link).to be_nil expect(workflow.published_at).to be_nil expect(workflow.bought_products).to eq([@product.unique_permalink, product4.unique_permalink, product5.unique_permalink]) expect(workflow.not_bought_products).to eq([@product2.unique_permalink]) expect(workflow.bought_variants).to eq([product3_version2.external_id]) expect(workflow.not_bought_variants).to be_nil expect(workflow.created_after).to be_nil expect(workflow.created_before).to be_nil expect(workflow.bought_from).to be_nil installment = workflow.installments.alive.sole expect(installment.name).to eq("You left something in your cart") expect(installment.message).to eq(%Q(<p>When you're ready to buy, <a href="#{checkout_index_url(host: UrlService.domain_with_protocol)}" target="_blank" rel="noopener noreferrer nofollow">complete checking out</a>.</p><product-list-placeholder />)) expect(installment.installment_type).to eq(Installment::ABANDONED_CART_TYPE) expect(installment.installment_rule.time_period).to eq("hour") expect(installment.installment_rule.delayed_delivery_time).to eq(24.hour) expect(page).to have_current_path(workflow_emails_path(workflow.external_id)) within find_email_row("You left something in your cart") do expect(page).to have_field("Subject", with: "You left something in your cart") expect(page).to_not have_field("Duration") expect(page).to_not have_select("Period") expect(page).to_not have_button("Edit") expect(page).to_not have_button("Delete") within find("[aria-label='Email message']") do expect(page).to have_text("When you're ready to buy, complete checking out", normalize_ws: true) expect(page).to have_link("complete checking out", href: checkout_index_url(host: UrlService.domain_with_protocol)) find_abandoned_cart_item(@product.name).hover expect(page).to have_text("This cannot be deleted") within find_abandoned_cart_item(@product.name) do expect(page).to have_link(@product.name, href: @product.long_url) expect(page).to have_link(seller.name, href: seller.subdomain_with_protocol) end expect(page).to_not have_abandoned_cart_item(@product2.name) expect(page).to have_abandoned_cart_item(product3.name) expect(page).to have_abandoned_cart_item(product4.name) expect(page).to_not have_abandoned_cart_item(product5.name) expect(page).to have_link("Complete checkout", href: checkout_index_url(host: UrlService.domain_with_protocol)) end end within_section "Preview", section_element: :aside do within_section "You left something in your cart" do expect(page).to have_text("24 hours after cart abandonment") expect(page).to have_text("When you're ready to buy, complete checking out", normalize_ws: true) expect(page).to have_link("complete checking out", href: checkout_index_url(host: UrlService.domain_with_protocol)) find_abandoned_cart_item(@product.name).hover expect(page).to_not have_text("This cannot be deleted") within find_abandoned_cart_item(@product.name) do expect(page).to have_link(@product.name, href: @product.long_url)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/password_reset_spec.rb
spec/requests/password_reset_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Password Reset", type: :system, js: true) do include FillInUserProfileHelpers before(:each) do @user = create(:user) @original_encrypted_password = @user.encrypted_password @token = @user.send(:set_reset_password_token) end it "resets the password if it is not compromised" do visit edit_user_password_path(@user, reset_password_token: @token) vcr_turned_on do VCR.use_cassette("Password reset - with non compromised password") do with_real_pwned_password_check do new_password = SecureRandom.hex(15) fill_in("Enter a new password", with: new_password) fill_in("Enter same password to confirm", with: new_password) click_on("Reset") expect(page).to have_text("Your password has been reset") expect(@user.reload.encrypted_password).not_to eq(@original_encrypted_password) end end end end it "does not reset the password if it is compromised" do visit edit_user_password_path(@user, reset_password_token: @token) vcr_turned_on do VCR.use_cassette("Password reset - with compromised password") do with_real_pwned_password_check do fill_in("Enter a new password", with: "password") fill_in("Enter same password to confirm", with: "password") click_on("Reset") expect(page).to have_text("Password has previously appeared in a data breach") expect(@user.reload.encrypted_password).to eq(@original_encrypted_password) 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/requests/user_custom_domain_spec.rb
spec/requests/user_custom_domain_spec.rb
# frozen_string_literal: true require "spec_helper" describe "UserCustomDomainScenario", type: :system, js: true do include FillInUserProfileHelpers before do allow(Resolv::DNS).to receive_message_chain(:new, :getresources).and_return([double(name: "domains.gumroad.com")]) Link.__elasticsearch__.create_index!(force: true) @user = create(:user, username: "test") section = create(:seller_profile_products_section, seller: @user) create(:seller_profile, seller: @user, json_data: { tabs: [{ name: "", sections: [section.id] }] }) @custom_domain = CustomDomain.new @custom_domain.user = @user @custom_domain.domain = "test-custom-domain.gumroad.com" @custom_domain.save @product = create(:product, user: @user) @port = Capybara.current_session.server.port @product.__elasticsearch__.index_document Link.__elasticsearch__.refresh_index! end describe "Follow / Unfollow" do it "loads the user profile page and sends create follower request" do visit "http://#{@custom_domain.domain}:#{@port}" submit_follow_form(with: "follower@gumroad.com") expect(page).to have_alert(text: "Check your inbox to confirm your follow request.") end it "handles the follow confirmation request" do follower = create(:follower, user: @user) expect(follower.confirmed_at).to be(nil) visit "http://#{@custom_domain.domain}:#{@port}#{confirm_follow_path(follower.external_id)}" expect(page).to have_alert(text: "Thanks for the follow!") expect(follower.reload.confirmed_at).not_to be(nil) end it "handles the follow cancellation request" do follower = create(:active_follower, user: @user) visit "http://#{@custom_domain.domain}:#{@port}#{cancel_follow_path(follower.external_id)}" expect(page).to have_text("You have been unsubscribed.") expect(page).to have_text("You will no longer get posts from this creator.") expect(follower.reload).to be_unconfirmed expect(follower.reload).to be_deleted end end describe "product share_url" do it "contains link to individual product page with custom domain" do visit "http://#{@custom_domain.domain}:#{@port}/" find_product_card(@product).click expect(page).to have_current_path("http://#{@custom_domain.domain}:#{@port}/l/#{@product.unique_permalink}?layout=profile") end end describe "gumroad logo" do it "links to the homepage via Gumroad logo in the footer" do visit "http://#{@custom_domain.domain}:#{@port}/" expect(find("main > footer")).to have_link("Gumroad", href: "#{UrlService.root_domain_with_protocol}/") end end describe "Custom domain support in widgets" do let(:custom_domain_base_uri) { "http://#{@custom_domain.domain}:#{@port}" } let(:product_url) { "#{custom_domain_base_uri}/l/#{@product.unique_permalink}" } let(:js_nonce) { SecureRandom.base64(32).chomp } describe "Embed widget" do include EmbedHelpers after(:all) { cleanup_embed_artifacts } it "allows displaying and purchasing a product in Embed using its custom domain URL" do visit(create_embed_page(@product, url: product_url, gumroad_params: "&email=sam@test.com", outbound: false, custom_domain_base_uri:)) within_frame { click_on "Add to cart" } check_out(@product) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/collaborators_spec.rb
spec/requests/collaborators_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Collaborators", type: :system, js: true do describe "seller view" do let(:seller) { create(:user) } before { login_as seller } context "viewing collaborators" do context "when there are none" do it "displays a placeholder message" do visit collaborators_path expect(page).to have_selector("h1", text: "Collaborators") expect(page).to have_selector("h2", text: "No collaborators yet") expect(page).to have_selector("h4", text: "Share your revenue with the people who helped create your products.") end end context "when there are some" do let(:product_one) { create(:product, user: seller, name: "First product") } let(:product_two) { create(:product, user: seller, name: "Second product") } let(:product_three) { create(:product, user: seller, name: "Third product") } let(:product_four) { create(:product, user: seller, name: "Fourth product") } let(:product_five) { create(:product, user: seller, name: "Fifth product") } let!(:collaborator_one) do co = create(:collaborator, seller:) co.product_affiliates.create!(product: product_one, affiliate_basis_points: 50_00) co.product_affiliates.create!(product: product_two, affiliate_basis_points: 35_00) co end let!(:collaborator_two) do affiliate_user = create(:user, payment_address: nil) create(:collaborator, seller:, affiliate_user:) end let!(:collaborator_three) { create(:collaborator, seller:, products: [product_three,]) } let!(:collaborator_four) do create(:collaborator, :with_pending_invitation, seller:, products: [product_four, product_five]) end it "displays a list of collaborators" do visit collaborators_path [ { "Name" => collaborator_one.affiliate_user.username, "Products" => "2 products", "Cut" => "35% - 50%", "Status" => "Accepted" }, { "Name" => collaborator_two.affiliate_user.username, "Products" => "None", "Cut" => "30%", "Status" => "Accepted" }, { "Name" => collaborator_three.affiliate_user.username, "Products" => product_three.name, "Cut" => "30%", "Status" => "Accepted" }, { "Name" => collaborator_four.affiliate_user.username, "Products" => "2 products", "Cut" => "30%", "Status" => "Pending" }, ].each do |row| expect(page).to have_table_row(row) end end it "displays details about a collaborator" do create(:merchant_account, user: collaborator_one.affiliate_user) create(:ach_account, user: collaborator_one.affiliate_user, stripe_bank_account_id: "ba_bankaccountid") visit collaborators_path find(:table_row, { "Name" => collaborator_one.affiliate_user.username, "Products" => "2 products", "Cut" => "35% - 50%" }).click within_modal collaborator_one.affiliate_user.name do expect(page).to have_text(collaborator_one.affiliate_user.email) expect(page).to have_text(product_one.name) expect(page).to have_text(product_two.name) expect(page).to have_text("35%") expect(page).to have_text("50%") expect(page).to have_link("Edit") expect(page).to have_button("Remove") expect(page).not_to have_text("Collaborators won't receive their cut until they set up a payout account in their Gumroad settings.") end find(:table_row, { "Name" => collaborator_two.affiliate_user.username, "Products" => "None", "Cut" => "30%" }).click within_modal collaborator_two.affiliate_user.name do expect(page).to have_text(collaborator_two.affiliate_user.email) expect(page).to have_link("Edit") expect(page).to have_button("Remove") expect(page).to have_text("Collaborators won't receive their cut until they set up a payout account in their Gumroad settings.") end end end end context "adding a collaborator" do let!(:product1) { create(:product, user: seller, name: "First product") } let!(:product2) { create(:product, user: seller, name: "Second product") } let!(:product3) do create(:product, user: seller, name: "Third product").tap do |product| create(:product_affiliate, product:, affiliate: create(:user).global_affiliate) end end let!(:product4) do create(:product, user: seller, name: "Fourth product").tap do |product| create(:product_affiliate, product:, affiliate: create(:collaborator, seller:)) end end let!(:product5) { create(:product, user: seller, name: "Fifth product", purchase_disabled_at: Time.current) } let!(:collaborating_user) { create(:user) } it "adds a collaborator for all visible products" do expect do visit collaborators_path click_on "Add collaborator" fill_in "email", with: "#{collaborating_user.email} " # test trimming email uncheck "Show as co-creator", checked: true click_on "Add collaborator" expect(page).to have_alert(text: "Changes saved!") expect(page).to have_current_path "/collaborators" end.to change { seller.collaborators.count }.from(1).to(2) .and change { ProductAffiliate.count }.from(2).to(5) collaborator = seller.collaborators.last expect(collaborator.apply_to_all_products).to eq true expect(collaborator.affiliate_percentage).to eq 50 expect(collaborator.dont_show_as_co_creator).to eq true expect(collaborator.products).to match_array [product1, product2, product3] [product1, product2, product3].each do |product| expect(product.reload.is_collab).to eq(true) pa = collaborator.product_affiliates.find_by(product:) expect(pa.affiliate_percentage).to eq 50 end expect(page).to have_table_row( { "Name" => collaborator.affiliate_user.username, "Products" => "3 products", "Cut" => "50%", "Status" => "Pending" } ) end it "allows enabling different products with different cuts" do expect do visit "/collaborators/new" fill_in "email", with: collaborating_user.email uncheck "All products" within find(:table_row, { "Product" => product1.name }) do check product1.name fill_in "Percentage", with: 40 uncheck "Show as co-creator", checked: true end within find(:table_row, { "Product" => product3.name }) do check product3.name fill_in "Percentage", with: 10 end click_on "Add collaborator" expect(page).to have_alert(text: "Changes saved!") expect(page).to have_current_path "/collaborators" end.to change { seller.collaborators.count }.from(1).to(2) .and change { ProductAffiliate.count }.from(2).to(4) collaborator = seller.collaborators.last expect(collaborator.affiliate_user).to eq collaborating_user expect(collaborator.apply_to_all_products).to eq false expect(collaborator.affiliate_percentage).to eq 50 expect(collaborator.dont_show_as_co_creator).to eq false pa = collaborator.product_affiliates.find_by(product: product1) expect(pa.affiliate_percentage).to eq 40 expect(pa.dont_show_as_co_creator).to eq true pa = collaborator.product_affiliates.find_by(product: product3) expect(pa.affiliate_percentage).to eq 10 expect(pa.dont_show_as_co_creator).to eq false expect(collaborator.product_affiliates.exists?(product: product2)).to eq false end it "does not allow creating a collaborator with invalid parameters" do visit "/collaborators/new" # invalid email fill_in "email", with: "foo" click_on "Add collaborator" expect(page).to have_alert(text: "Please enter a valid email") # no user with that email fill_in "email", with: "foo@example.com" click_on "Add collaborator" expect(page).to have_alert(text: "The email address isn't associated with a Gumroad account.") # no products selected fill_in "email", with: collaborating_user.email [product1, product2, product3].each do |product| within find(:table_row, { "Product" => product.name }) do uncheck product.name end end click_on "Add collaborator" expect(page).to have_alert(text: "At least one product must be selected") # invalid default percent commission within find(:table_row, { "Product" => product1.name }) do check product1.name end within find(:table_row, { "Product" => "All products" }) do fill_in "Percentage", with: 75 end click_on "Add collaborator" within find(:table_row, { "Product" => "All products" }) do expect(find("fieldset.danger")).to have_field("Percentage") end expect(page).to have_alert(text: "Collaborator cut must be 50% or less") # invalid product percent commission uncheck "All products" within find(:table_row, { "Product" => product1.name }) do check product1.name fill_in "Percentage", with: 75 end click_on "Add collaborator" within find(:table_row, { "Product" => product1.name }) do expect(find("fieldset.danger")).to have_field("Percentage") end expect(page).to have_alert(text: "Collaborator cut must be 50% or less") within find(:table_row, { "Product" => product1.name }) do fill_in "Percentage", with: 40 expect(page).not_to have_selector("fieldset.danger") fill_in "Percentage", with: 0 end click_on "Add collaborator" within find(:table_row, { "Product" => product1.name }) do expect(find("fieldset.danger")).to have_field("Percentage") end expect(page).to have_alert(text: "Collaborator cut must be 50% or less") # missing default percent commission check "All products" within find(:table_row, { "Product" => "All products" }) do fill_in "Percentage", with: "" end click_on "Add collaborator" within find(:table_row, { "Product" => "All products" }) do expect(find("fieldset.danger")).to have_field("Percentage") end expect(page).to have_alert(text: "Collaborator cut must be 50% or less") # missing product percent commission uncheck "All products" within find(:table_row, { "Product" => product1.name }) do check product1.name fill_in "Percentage", with: "" expect(page).to have_field("Percentage", placeholder: "50") # shows the default value as a placeholder end click_on "Add collaborator" within find(:table_row, { "Product" => product1.name }) do expect(page).to have_field("Percentage", placeholder: "50") # shows the default value as a placeholder expect(find("fieldset.danger")).to have_field("Percentage") end expect(page).to have_alert(text: "Collaborator cut must be 50% or less") end it "does not allow adding a collaborator for ineligible products but does for unpublished products" do invisible_product = create(:product, user: seller, name: "Deleted product", deleted_at: 1.day.ago) visit "/collaborators/new" expect(page).not_to have_content invisible_product.name expect(page).not_to have_content product4.name expect(page).not_to have_content product5.name check "Show unpublished and ineligible products" expect(page).to have_content product4.name expect(page).to have_content product5.name within find(:table_row, { "Product" => product4.name }) do expect(page).to have_unchecked_field(product4.name, disabled: true) end within find(:table_row, { "Product" => product5.name }) do expect(page).to have_checked_field(product5.name) end fill_in "email", with: collaborating_user.email uncheck "All products" within find(:table_row, { "Product" => product2.name }) do check product2.name end within find(:table_row, { "Product" => product3.name }) do check product3.name end within find(:table_row, { "Product" => product4.name }) do expect(page).to have_unchecked_field(product4.name, disabled: true) expect(page).to have_content "Already has a collaborator" end within find(:table_row, { "Product" => product5.name }) do check product5.name end expect do click_on "Add collaborator" expect(page).to have_alert(text: "Changes saved!") expect(page).to have_current_path "/collaborators" end.to change { seller.collaborators.count }.from(1).to(2) .and change { ProductAffiliate.count }.from(2).to(5) collaborator = seller.collaborators.last expect(collaborator.products).to match_array [product2, product3, product5] visit collaborators_path within :table_row, { "Name" => collaborator.affiliate_user.display_name } do click_on "Edit" end expect(page).to have_checked_field("Show unpublished and ineligible products") within find(:table_row, { "Product" => product5.name }) do expect(page).to have_checked_field(product5.name) end end it "disables affiliates when adding a collaborator to a product with affiliates" do affiliate = create(:direct_affiliate, seller:) affiliated_products = (1..12).map { |i| create(:product, user: seller, name: "Number #{i} affiliate product") } affiliate.products = affiliated_products visit "/collaborators/new" expect do fill_in "email", with: collaborating_user.email affiliated_products.each do |product| within find(:table_row, { "Product" => product.name }) do expect(page).to have_content "Selecting this product will remove all its affiliates." end end click_on "Add collaborator" expect(page).to have_modal("Remove affiliates?") within_modal("Remove affiliates?") do expect(page).to have_text("Affiliates will be removed from the following products:") affiliated_products.first(10).each do |product| expect(page).to have_text(product.name) end affiliated_products.last(2).each do |product| expect(page).not_to have_text(product.name) end expect(page).to have_text("and 2 others.") click_on "No, cancel" end expect(page).not_to have_modal("Remove affiliates?") click_on "Add collaborator" expect(page).to have_modal("Remove affiliates?") within_modal("Remove affiliates?") do click_on "Yes, continue" end expect(page).to have_alert(text: "Changes saved!") expect(page).to have_current_path "/collaborators" collaborator = seller.collaborators.last expect(collaborator.products).to match_array([product1, product2, product3] + affiliated_products) end.to change { seller.collaborators.count }.from(1).to(2) .and change { affiliate.reload.products.count }.from(12).to(0) end it "does not allow adding a collaborator if creator is using a Brazilian Stripe Connect account" do brazilian_stripe_account = create(:merchant_account_stripe_connect, user: seller, country: "BR") seller.update!(check_merchant_account_is_linked: true) expect(seller.merchant_account(StripeChargeProcessor.charge_processor_id)).to eq brazilian_stripe_account visit collaborators_path link = find_link("Add collaborator", inert: true) link.hover expect(link).to have_tooltip(text: "Collaborators with Brazilian Stripe accounts are not supported.") visit "/collaborators/new" button = find_button("Add collaborator", disabled: true) button.hover expect(button).to have_tooltip(text: "Collaborators with Brazilian Stripe accounts are not supported.") end end it "allows deleting a collaborator" do collaborators = create_list(:collaborator, 2, seller:) product = create(:product, user: seller, is_collab: true) create(:product_affiliate, affiliate: collaborators.first, product:) visit collaborators_path within find(:table_row, { "Name" => collaborators.first.affiliate_user.username }) do click_on "Delete" end expect(page).to have_alert(text: "The collaborator was removed successfully.") expect(collaborators.first.reload.deleted_at).to be_present expect(product.reload.is_collab).to eq false expect(page).to_not have_table_row({ "Name" => collaborators.first.affiliate_user.username }) find(:table_row, { "Name" => collaborators.second.affiliate_user.username }).click within_modal collaborators.second.affiliate_user.username do click_on "Remove" end wait_for_ajax expect(page).to have_alert(text: "The collaborator was removed successfully.") expect(collaborators.second.reload.deleted_at).to be_present expect(page).to_not have_table_row({ "Name" => collaborators.second.affiliate_user.username }) end context "editing a collaborator" do let!(:product1) { create(:product, user: seller, name: "First product") } let!(:product2) { create(:product, user: seller, name: "Second product") } let!(:product3) { create(:product, user: seller, name: "Third product") } let!(:product4) { create(:product, user: seller, name: "Fourth product").tap { |product| create(:direct_affiliate, products: [product]) } } let!(:ineligible_product) { create(:product, user: seller, name: "Ineligible product").tap { |product| create(:collaborator, products: [product]) } } let!(:collaborator) { create(:collaborator, seller:, apply_to_all_products: true, affiliate_basis_points: 40_00, products: [product1, product2], dont_show_as_co_creator: true) } before do collaborator.product_affiliates.first.update!(dont_show_as_co_creator: true) end it "allows editing a collaborator" do expect do visit collaborators_path within :table_row, { "Name" => collaborator.affiliate_user.display_name } do click_on "Edit" end expect(page).to have_text collaborator.affiliate_user.display_name # edit default commission within find(:table_row, { "Product" => "All products" }) do expect(page).to have_checked_field("All products") fill_in "Percentage", with: 30 end # disable product 1 within find(:table_row, { "Product" => product1.name }) do uncheck product1.name end # enable individual cuts uncheck "All products" # show as co-creator & edit commission for product 2 within find(:table_row, { "Product" => product2.name }) do check product2.name check "Show as co-creator", checked: false fill_in "Percentage", with: 25 end # enable products 3 + 4 within find(:table_row, { "Product" => product3.name }) do check product3.name end within find(:table_row, { "Product" => product4.name }) do expect(page).to have_content "Selecting this product will remove all its affiliates." check product4.name fill_in "Percentage", with: 45 end check "Show unpublished and ineligible products" # cannot select ineligible product within find(:table_row, { "Product" => ineligible_product.name }) do have_unchecked_field(ineligible_product.name, disabled: true) expect(page).to have_content "Already has a collaborator" end click_on "Save changes" expect(page).to have_modal("Remove affiliates?") within_modal("Remove affiliates?") do expect(page).to have_text("Affiliates will be removed from the following products:") expect(page).to have_text(product4.name) click_on "Close" end expect(page).not_to have_modal("Remove affiliates?") click_on "Save changes" expect(page).to have_modal("Remove affiliates?") within_modal("Remove affiliates?") do click_on "Yes, continue" end expect(page).to have_alert(text: "Changes saved!") expect(page).to have_current_path "/collaborators" end.to change { collaborator.products.count }.from(2).to(3) .and change { product1.reload.is_collab }.from(true).to(false) .and change { product4.direct_affiliates.count }.from(1).to(0) collaborator.reload expect(collaborator.affiliate_basis_points).to eq 30_00 expect(collaborator.products).to match_array [product2, product3, product4] expect(collaborator.apply_to_all_products).to eq false product_2_collab = collaborator.product_affiliates.find_by(product: product2) expect(product_2_collab.dont_show_as_co_creator).to eq false expect(product_2_collab.affiliate_basis_points).to eq 25_00 expect(collaborator.product_affiliates.find_by(product: product3).affiliate_basis_points).to eq 30_00 expect(collaborator.product_affiliates.find_by(product: product4).affiliate_basis_points).to eq 45_00 end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/mobile_api_spec.rb
spec/requests/mobile_api_spec.rb
# frozen_string_literal: true describe "Mobile API Request Specs" do before do @product = create(:product) end describe "product download urls" do before do base_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/43a5363194e74e9ee75b6203eaea6705/original/chapter1.mp4" @product.product_files << @product.product_files << create(:product_file, url: base_url) purchase = create(:purchase_with_balance, link: @product) @url_redirect = purchase.url_redirect @url_redirect.mark_as_seen @url_redirect.increment!(:uses, 1) query = "AWSAccessKeyId=AKIAIKFZLOLAPOKIC6EA&Expires=1386261022&Signature=FxVDOkutrgrGFLWXISp0JroWFLo%3D&" query += "response-content-disposition=attachment" @download_url = "#{base_url}?#{query}" allow_any_instance_of(UrlRedirect).to receive(:signed_download_url_for_s3_key_and_filename) .with("attachments/43a5363194e74e9ee75b6203eaea6705/original/chapter1.mp4", "chapter1.mp4", { is_video: true }) .and_return(@download_url) end it "redirects to download URL" do 10.times do get @url_redirect.product_json_data[:file_data].last[:download_url] expect(response.code.to_i).to eq 302 expect(response.location).to eq @download_url end end end describe "external link url" do before do @url_redirect = create(:url_redirect, link: @product, purchase: nil) end it "adds external_link_url for external link files" do @product.product_files << create(:product_file, url: "http://www.gumroad.com", filetype: "link") expect(@url_redirect.product_json_data[:file_data].last.key?(:external_link_url)).to eq(true) expect(@url_redirect.product_json_data[:file_data].last[:external_link_url]).to eq("http://www.gumroad.com") end it "does not add external_link_url for non external link files" do @product.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4") expect(@url_redirect.product_json_data[:file_data].last.key?(:external_link_url)).to eq(false) end end it "serves stream urls that are usable" do @product.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4", is_transcoded_for_hls: true) @transcoded_video = create(:transcoded_video, link: @product, streamable: @product.product_files.last, original_video_key: @product.product_files.last.s3_key, transcoded_video_key: "attachments/2_1/original/chapter2/hls/index.m3u8", is_hls: true, state: "completed") url_redirect = create(:url_redirect, link: @product, purchase: nil) url_redirect.mark_as_seen url_redirect.increment!(:uses, 1) s3_new = double("s3_new") s3_bucket = double("s3_bucket") s3_object = double("s3_object") 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) 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(s3_object).to receive(:get).and_return(double(body: double(read: hls))) 10.times do get url_redirect.product_json_data[:file_data].last[:streaming_url] + "?mobile_token=#{Api::Mobile::BaseController::MOBILE_TOKEN}" expect(response.code.to_i).to eq 200 end end it "sets the url redirect attributes" do url_redirect = create(:url_redirect, link: @product) expect(url_redirect.product_json_data).to include( url_redirect_external_id: url_redirect.external_id, url_redirect_token: url_redirect.token ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/login_spec.rb
spec/requests/login_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Login Feature Scenario", js: true, type: :system do let(:user) { create(:user) } before do ignore_js_error(/Error retrieving login status, fetch cancelled./) end describe "login", type: :system do it "logs in a user" do visit login_path expect(page).to_not have_alert expect(page).to have_link "Gumroad", href: UrlService.root_domain_with_protocol fill_in "Email", with: user.email fill_in "Password", with: user.password click_on "Login" expect(page).to have_selector("iframe[title*=recaptcha]", visible: false) wait_for_ajax expect(page).to have_content("Dashboard") end it "shows an error when login fails" do visit login_path expect(page).to_not have_alert fill_in "Email", with: user.email fill_in "Password", with: "someotherpassword" click_on "Login" wait_for_ajax expect(page).to have_alert(text: "Please try another password. The one you entered was incorrect.") expect(page).to have_button("Login") end end describe "OAuth login", type: :system do before do @oauth_application = create(:oauth_application) @oauth_authorize_url = oauth_authorization_path(client_id: @oauth_application.uid, redirect_uri: @oauth_application.redirect_uri, scope: "edit_products") visit @oauth_authorize_url end it "sets the application name and 'next' query string in sign up link" do expect(page.has_content?("Connect #{@oauth_application.name} to Gumroad")).to be(true) expect(page).to have_link("Sign up", href: signup_path(next: @oauth_authorize_url)) end it "navigates to OAuth authorization page" do fill_in "Email", with: user.email fill_in "Password", with: user.password click_on "Login" wait_for_ajax expect(page.has_content?("Authorize #{@oauth_application.name} to use your account?")).to be(true) end end describe "Social login" do let(:user) { create(:user) } before do OmniAuth.config.test_mode = true end it "supports logging in with Facebook" do OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new(JSON.parse(File.read("#{Rails.root}/spec/support/fixtures/facebook_omniauth.json"))) user.update!(facebook_uid: OmniAuth.config.mock_auth[:facebook][:uid]) visit signup_path expect do click_button "Facebook" expect(page).to have_content("We're here to help you get paid for your work.") end.not_to change(User, :count) end it "supports logging in with Google" do OmniAuth.config.mock_auth[:google_oauth2] = OmniAuth::AuthHash.new(JSON.parse(File.read("#{Rails.root}/spec/support/fixtures/google_omniauth.json"))) user.update!(google_uid: OmniAuth.config.mock_auth[:google_oauth2][:uid]) visit signup_path expect do click_button "Google" expect(page).to have_content("We're here to help you get paid for your work.") end.not_to change(User, :count) end it "supports logging in with X" do OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new(JSON.parse(File.read("#{Rails.root}/spec/support/fixtures/twitter_omniauth.json"))) user.update!(twitter_user_id: OmniAuth.config.mock_auth[:twitter][:extra][:raw_info][:id]) visit signup_path expect do click_button "X" expect(page).to have_content("We're here to help you get paid for your work.") end.not_to change(User, :count) end it "supports logging in with Stripe" do OmniAuth.config.mock_auth[:stripe_connect] = OmniAuth::AuthHash.new(JSON.parse(File.read("#{Rails.root}/spec/support/fixtures/stripe_connect_omniauth.json"))) create(:merchant_account_stripe_connect, user:, charge_processor_merchant_id: OmniAuth.config.mock_auth[:stripe_connect][:uid]) visit signup_path expect do click_button "Stripe" expect(page).to have_content("We're here to help you get paid for your work.") end.not_to change(User, :count) end end describe "Prefill team invitation email" do let(:team_invitation) { create(:team_invitation) } it "prefills the email" do visit login_path(next: accept_settings_team_invitation_path(team_invitation.external_id, email: team_invitation.email)) expect(find_field("Email").value).to eq(team_invitation.email) end end describe "reset password" do it "sends a reset password email" do visit login_path click_on "Forgot your password?" fill_in "Email to send reset instructions to", with: user.email click_on "Send" wait_for_ajax expect(page).to have_alert(text: "Password reset sent! Please make sure to check your spam folder.") expect(user.reload.reset_password_sent_at).to be_present end it "shows an error for a nonexistent account" do visit login_path click_on "Forgot your password?" fill_in "Email to send reset instructions to", with: "notauser@example.com" click_on "Send" wait_for_ajax expect(page).to have_alert(text: "An account does not exist with that email.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/dashboard_nav_mobile_spec.rb
spec/requests/dashboard_nav_mobile_spec.rb
# frozen_string_literal: true require "spec_helper" describe("Dashboard - Nav - Mobile", :js, :mobile_view, type: :system) do let(:user) { create(:named_seller) } before do login_as user end it "auto closes the menu when navigating to a different page" do visit dashboard_path click_on "Toggle navigation" expect(page).to have_link("Products") expect(page).to have_link("Analytics") click_on "Products" expect(page).to_not have_link("Products") expect(page).to_not have_link("Analytics") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/dashboard_spec.rb
spec/requests/dashboard_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Dashboard", js: true, type: :system do let(:seller) { create(:named_seller) } before do login_as seller end describe "dashboard stats" do before do create(:product, user: seller) allow_any_instance_of(UserBalanceStatsService).to receive(:fetch).and_return( { overview: { balance: 10_000, last_seven_days_sales_total: 5_000, last_28_days_sales_total: 15_000, sales_cents_total: 50_000 }, next_payout_period_data: { should_be_shown_currencies_always: false, minimum_payout_amount_cents: 1_000, is_user_payable: false, status: :not_payable }, processing_payout_periods_data: [] } ) end it "displays correct values and headings for stats" do visit dashboard_path within "main" do expect(page).to have_text("Balance $100", normalize_ws: true) expect(page).to have_text("Last 7 days $50", normalize_ws: true) expect(page).to have_text("Last 28 days $150", normalize_ws: true) expect(page).to have_text("Total earnings $500", normalize_ws: true) end end it "displays currency symbol and headings when seller should be shown currencies always" do allow(seller).to receive(:should_be_shown_currencies_always?).and_return(true) visit dashboard_path within "main" do expect(page).to have_text("Balance $100 USD", normalize_ws: true) expect(page).to have_text("Last 7 days $50 USD", normalize_ws: true) expect(page).to have_text("Last 28 days $150 USD", normalize_ws: true) expect(page).to have_text("Total earnings $500 USD", normalize_ws: true) end end end describe "Greeter" do context "with switching account to user as admin for seller" do include_context "with switching account to user as admin for seller" it "renders the greeter placeholder" do visit dashboard_path expect(page).to have_text("We're here to help you get paid for your work") end end context "with switching account to user as marketing for seller" do include_context "with switching account to user as marketing for seller" it "renders the greeter placeholder" do visit dashboard_path expect(page).to have_text("We're here to help you get paid for your work") end end end describe "Getting started" do context "with switching account to user as admin for seller" do include_context "with switching account to user as admin for seller" it "renders the Getting started section" do visit dashboard_path expect(page).to have_text("Getting started") end end context "with switching account to user as marketing for seller" do include_context "with switching account to user as marketing for seller" it "doesn't render the Getting started section" do visit dashboard_path expect(page).not_to have_text("Getting started") end end end describe "Activity" do context "with no data" do context "with switching account to user as admin for seller" do include_context "with switching account to user as admin for seller" it "renders placeholder text with links" do visit dashboard_path expect(page).to have_text("Followers and sales will show up here as they come in. For now, create a product or customize your profile") end end context "with switching account to user as marketing for seller" do include_context "with switching account to user as marketing for seller" it "renders placeholder text with links only" do visit dashboard_path expect(page).to have_text("Followers and sales will show up here as they come in.") expect(page).not_to have_text("For now, create a profile or customize your profile") end end end end describe "Stripe verification message" do it "displays the verification error message from Stripe" do create(:merchant_account, user: seller) create(:user_compliance_info_request, user: seller, field_needed: UserComplianceInfoFields::Individual::STRIPE_IDENTITY_DOCUMENT_ID, verification_error: { code: "verification_document_name_missing" }) visit dashboard_path expect(page).to have_text("The uploaded document is missing the name. Please upload another document that contains the name.") end end describe "tax form download notice" do before do freeze_time seller.update!(created_at: 1.year.ago) end context "when tax_center feature is disabled" do before do Feature.deactivate_user(:tax_center, seller) end it "displays a 1099 form ready notice with a link to download if eligible" do download_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/23b2d41ac63a40b5afa1a99bf38a0982/original/test.pdf" allow_any_instance_of(User).to receive(:eligible_for_1099?).and_return(true) allow_any_instance_of(User).to receive(:tax_form_1099_download_url).and_return(download_url) visit dashboard_path expect(page).to have_text("Your 1099 tax form for #{Time.current.prev_year.year} is ready!") expect(page).to have_link("Click here to download", href: dashboard_download_tax_form_path) end it "does not display a 1099 form ready notice if not eligible" do allow_any_instance_of(User).to receive(:eligible_for_1099?).and_return(false) visit dashboard_path expect(page).not_to have_text("Your 1099 tax form for #{Time.current.prev_year.year} is ready!") expect(page).not_to have_link("Click here to download", href: dashboard_download_tax_form_path) end end context "when tax_center feature is enabled" do before do Feature.activate_user(:tax_center, seller) end it "displays notice with link to tax center when user has tax form for previous year" do create(:user_tax_form, user: seller, tax_year: Time.current.prev_year.year, tax_form_type: "us_1099_k") visit dashboard_path expect(page).to have_text("Your 1099 tax form for #{Time.current.prev_year.year} is ready!") expect(page).to have_link("Click here to download", href: tax_center_path(year: Time.current.prev_year.year)) end it "does not display notice when user has no tax form for previous year" do visit dashboard_path expect(page).not_to have_text("Your 1099 tax form for") expect(page).not_to have_link("Click here to download") end end end describe "download tax forms button" do download_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/23b2d41ac63a40b5afa1a99bf38a0982/original/test.pdf" before do freeze_time seller.update!(created_at: 1.year.ago) allow(seller).to receive(:eligible_for_1099?).and_return(true) allow(seller).to receive(:tax_form_1099_download_url).and_return(download_url) end it "displays button when there are tax forms" do visit dashboard_path expect(page).to have_button("Tax forms") end it "opens a popover with a checkbox for each year with a tax form" do visit dashboard_path click_button("Tax forms") expect(page).to have_text("Download tax forms") expect(page).to have_text("Select the tax years you want to download.") expect(page).to have_unchecked_field(Time.current.year.to_s) expect(page).to have_unchecked_field(Time.current.prev_year.year.to_s) end it "allows selecting all years and deselecting all years" do visit dashboard_path click_button("Tax forms") click_button("Select all") expect(page).to have_checked_field(Time.current.year.to_s) expect(page).to have_checked_field(Time.current.prev_year.year.to_s) click_button("Deselect all") expect(page).to have_unchecked_field(Time.current.year.to_s) expect(page).to have_unchecked_field(Time.current.prev_year.year.to_s) end it "downloads selected tax forms" do visit dashboard_path click_button("Tax forms") check(Time.current.prev_year.year.to_s) new_window = window_opened_by { click_button("Download") } within_window new_window do expect(current_url).to eq(download_url) end end it "does not display button if there are no tax forms" do allow(seller).to receive(:eligible_for_1099?).and_return(false) visit dashboard_path expect(page).not_to have_button("Tax forms") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/cors_headers_spec.rb
spec/requests/cors_headers_spec.rb
# frozen_string_literal: true require "spec_helper" describe "CORS support" do let(:application_domain) { "gumroad.com" } let(:origin_domain) { "example.com" } describe "Request to API domain" do let(:api_domain) { "api.gumroad.com" } before do stub_const("VALID_API_REQUEST_HOSTS", [api_domain]) end it "returns a response with CORS headers" do post oauth_token_path, headers: { "HTTP_ORIGIN": origin_domain, "HTTP_HOST": api_domain } expect(response.headers["Access-Control-Allow-Origin"]).to eq "*" expect(response.headers["Access-Control-Allow-Methods"]).to eq "GET, POST, PUT, DELETE" expect(response.headers["Access-Control-Max-Age"]).to eq "7200" end end describe "Request to /users/session_info from VALID_CORS_ORIGINS" do it "returns a response with CORS headers" do origin = "#{PROTOCOL}://#{VALID_CORS_ORIGINS[0]}" get user_session_info_path, headers: { "HTTP_ORIGIN": origin, "HTTP_HOST": DOMAIN } expect(response.headers["Access-Control-Allow-Origin"]).to eq origin expect(response.headers["Access-Control-Allow-Methods"]).to eq "GET" expect(response.headers["Access-Control-Max-Age"]).to eq "7200" end end context "when the request is made to a CORS disabled domain" do before do post oauth_token_path, headers: { "HTTP_ORIGIN": origin_domain, "HTTP_HOST": application_domain } end it "returns a response without CORS headers" do expect(response.headers["Access-Control-Allow-Origin"]).to be_nil expect(response.headers["Access-Control-Allow-Methods"]).to be_nil expect(response.headers["Access-Control-Max-Age"]).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/requests/communities_spec.rb
spec/requests/communities_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Communities", :js, type: :system do let(:seller) { create(:user, name: "Bob") } before do Feature.activate_user(:communities, seller) end def find_message(content) content_element = find("[aria-label='Message content']", text: content, match: :first) content_element.ancestor("[aria-label='Chat message']", match: :first) end def have_message(content) have_selector("[aria-label='Message content']", text: content, match: :first) end context "when the logged in seller has an active community" do let(:product) { create(:product, name: "Mastering Rails", user: seller, community_chat_enabled: true) } let!(:community) { create(:community, resource: product, seller:) } before do login_as(seller) end it "shows the community and allows the seller to send, edit, and delete own messages" do visit community_path wait_for_ajax expect(page).to have_current_path(community_path(seller.external_id, community.external_id)) within "[aria-label='Sidebar']" do within "[aria-label='Community switcher area']" do expect(page).to have_text("My community") end within "[aria-label='Community list']" do expect(page).to have_link("Mastering Rails", href: community_path(seller.external_id, community.external_id)) expect(find_link("Mastering Rails")["aria-selected"]).to eq("true") end end within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("Mastering Rails") end within "[aria-label='Chat messages']" do expect(page).to have_text("Welcome to Mastering Rails") expect(page).to have_text("This is the start of this community chat.") end fill_in "Type a message", with: "Hello, world!" click_button "Send message" wait_for_ajax message = community.community_chat_messages.sole expect(message.content).to eq("Hello, world!") expect(message.user).to eq(seller) within "[aria-label='Chat messages']" do expect(page).to have_message("Hello, world!") message_element = find_message("Hello, world!") message_element.hover within message_element do expect(page).to have_text(seller.display_name) expect(page).to have_text("CREATOR") expect(page).to have_button("Edit message") expect(page).to have_button("Delete message") click_button "Edit message" fill_in "Edit message", with: "This is wonderful!" sleep 0.5 # wait for the state to update click_on "Save" wait_for_ajax end expect(page).to have_message("This is wonderful!") expect(page).not_to have_message("Hello, world!") expect(message.reload.content).to eq("This is wonderful!") within message_element do click_button "Delete message" within_modal "Delete message" do expect(page).to have_text("Are you sure you want to delete this message? This cannot be undone.") click_on "Delete" end wait_for_ajax end expect(page).not_to have_message("This is wonderful!") expect(message.reload).to be_deleted expect(community.community_chat_messages.alive).to be_empty end end end it "allows seller to delete messages from other community members" do customer = create(:user, name: "John Customer") customer_message = create(:community_chat_message, community:, user: customer, content: "Hello, world!") visit community_path customer_message_element = find_message("Hello, world!") customer_message_element.hover within customer_message_element do expect(page).to have_text("John Customer") expect(page).not_to have_text("CREATOR") expect(page).not_to have_button("Edit message") expect(page).to have_button("Delete message") click_button "Delete message" within_modal "Delete message" do expect(page).to have_text("Are you sure you want to delete this message? This cannot be undone.") click_on "Delete" end end wait_for_ajax expect(page).not_to have_message("Hello, world!") expect(customer_message.reload).to be_deleted expect(community.community_chat_messages.alive).to be_empty end it "allows seller to manage community notification settings" do visit community_path expect(seller.community_notification_settings.find_by(seller:)).to be_nil within "[aria-label='Community switcher area']" do select_disclosure "Switch creator" click_on "Notifications" end within_modal "Notifications" do expect(page).to have_text(%Q(Receive email recaps of what's happening in "Bob" community.)) expect(page).to have_unchecked_field("Community recap") expect(page).not_to have_radio_button("Daily") expect(page).not_to have_radio_button("Weekly") check "Community recap" expect(page).to have_radio_button("Daily", checked: false) expect(page).to have_radio_button("Weekly", checked: true) click_on "Save" end wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.community_notification_settings.find_by(seller:).recap_frequency).to eq("weekly") within "[aria-label='Community switcher area']" do select_disclosure "Switch creator" click_on "Notifications" end within_modal "Notifications" do expect(page).to have_checked_field("Community recap") expect(page).to have_radio_button("Daily", checked: false) expect(page).to have_radio_button("Weekly", checked: true) choose "Daily" click_on "Save" end wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.community_notification_settings.find_by(seller:).recap_frequency).to eq("daily") within "[aria-label='Community switcher area']" do select_disclosure "Switch creator" click_on "Notifications" end within_modal "Notifications" do expect(page).to have_checked_field("Community recap") expect(page).to have_radio_button("Daily", checked: true) expect(page).to have_radio_button("Weekly", checked: false) uncheck "Community recap" expect(page).not_to have_radio_button("Daily") expect(page).not_to have_radio_button("Weekly") click_on "Save" end wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.community_notification_settings.find_by(seller:).recap_frequency).to be_nil end it "allows seller to switch between own communities" do product2 = create(:product, name: "Scaling web apps", user: seller, community_chat_enabled: true) community2 = create(:community, resource: product2, seller:) create(:community_chat_message, community: community2, user: seller, content: "Are you ready to scale your web app?") visit community_path wait_for_ajax within "[aria-label='Sidebar']" do within "[aria-label='Community list']" do expect(page).to have_link("Mastering Rails", href: community_path(seller.external_id, community.external_id)) expect(page).to have_link("Scaling web apps", href: community_path(seller.external_id, community2.external_id)) expect(find_link("Mastering Rails")["aria-selected"]).to eq("true") expect(find_link("Scaling web apps")["aria-selected"]).to eq("false") end end within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("Mastering Rails") end within "[aria-label='Chat messages']" do expect(page).to have_text("Welcome to Mastering Rails") end end within "[aria-label='Sidebar']" do click_link "Scaling web apps" wait_for_ajax within "[aria-label='Community list']" do expect(find_link("Mastering Rails")["aria-selected"]).to eq("false") expect(find_link("Scaling web apps")["aria-selected"]).to eq("true") end end within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("Scaling web apps") end within "[aria-label='Chat messages']" do expect(page).to have_message("Are you ready to scale your web app?") end fill_in "Type a message", with: "Wow, this is amazing!" click_button "Send message" wait_for_ajax message = community2.community_chat_messages.last expect(message.content).to eq("Wow, this is amazing!") expect(message.user).to eq(seller) within "[aria-label='Chat messages']" do message_element = find_message("Wow, this is amazing!") message_element.hover within message_element do expect(page).to have_text("Bob") expect(page).to have_text("CREATOR") expect(page).to have_button("Edit message") expect(page).to have_button("Delete message") end end end within "[aria-label='Sidebar']" do click_link "Mastering Rails" wait_for_ajax within "[aria-label='Community list']" do expect(find_link("Mastering Rails")["aria-selected"]).to eq("true") expect(find_link("Scaling web apps")["aria-selected"]).to eq("false") end end within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("Mastering Rails") end within "[aria-label='Chat messages']" do expect(page).not_to have_message("Are you ready to scale your web app?") expect(page).not_to have_message("Wow, this is amazing!") expect(page).to have_text("Welcome to Mastering Rails") end end end end context "when a customer accesses the community" do let(:product) { create(:product, name: "Mastering Rails", user: seller, community_chat_enabled: true) } let!(:community) { create(:community, resource: product, seller:) } let(:buyer) { create(:user, name: "John Buyer") } let!(:purchase) { create(:purchase, seller:, purchaser: buyer, link: product) } let!(:seller_message) { create(:community_chat_message, community:, user: seller, content: "Hello from seller!") } let!(:another_customer_message) { create(:community_chat_message, community:, user: create(:user, name: "Jane"), content: "Hello from Jane!") } before do login_as(buyer) end it "shows the community and allows the buyer to send, edit, and delete own messages" do visit community_path wait_for_ajax within "[aria-label='Sidebar']" do within "[aria-label='Community switcher area']" do expect(page).to have_text("Bob") end within "[aria-label='Community list']" do expect(page).to have_link("Mastering Rails", href: community_path(seller.external_id, community.external_id)) expect(find_link("Mastering Rails")["aria-selected"]).to eq("true") end end within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("Mastering Rails") end within "[aria-label='Chat messages']" do expect(page).to have_text("Welcome to Mastering Rails") expect(page).to have_text("This is the start of this community chat.") expect(page).to have_message("Hello from seller!") expect(page).to have_message("Hello from Jane!") end fill_in "Type a message", with: "Hello from John!" click_button "Send message" wait_for_ajax message = community.community_chat_messages.last expect(message.content).to eq("Hello from John!") expect(message.user).to eq(buyer) within "[aria-label='Chat messages']" do expect(page).to have_message("Hello from John!") message_element = find_message("Hello from John!") message_element.hover within message_element do expect(page).to have_text("John Buyer") expect(page).not_to have_text("CREATOR") expect(page).to have_button("Edit message") expect(page).to have_button("Delete message") click_button "Edit message" fill_in "Edit message", with: "This is wonderful!" sleep 0.5 # wait for the state to update click_on "Save" wait_for_ajax end expect(page).to have_message("This is wonderful!") expect(page).not_to have_message("Hello from John!") expect(message.reload.content).to eq("This is wonderful!") within message_element do click_button "Delete message" within_modal "Delete message" do expect(page).to have_text("Are you sure you want to delete this message? This cannot be undone.") click_on "Delete" end wait_for_ajax end expect(page).not_to have_message("This is wonderful!") expect(message.reload).to be_deleted expect(community.community_chat_messages.alive.count).to eq(2) message_from_another_customer = find_message("Hello from Jane!") message_from_another_customer.hover within message_from_another_customer do expect(page).to have_text("Jane") expect(page).not_to have_text("CREATOR") expect(page).not_to have_button("Edit message") expect(page).not_to have_button("Delete message") end message_from_seller = find_message("Hello from seller!") message_from_seller.hover within message_from_seller do expect(page).to have_text("Bob") expect(page).to have_text("CREATOR") expect(page).not_to have_button("Edit message") expect(page).not_to have_button("Delete message") end end end end it "allows buyer to manage community notification settings" do visit community_path expect(buyer.community_notification_settings.find_by(seller:)).to be_nil within "[aria-label='Community switcher area']" do select_disclosure "Switch creator" click_on "Notifications" end within_modal "Notifications" do expect(page).to have_text(%Q(Receive email recaps of what's happening in "Bob" community.)) expect(page).to have_unchecked_field("Community recap") expect(page).not_to have_radio_button("Daily") expect(page).not_to have_radio_button("Weekly") check "Community recap" expect(page).to have_radio_button("Daily", checked: false) expect(page).to have_radio_button("Weekly", checked: true) click_on "Save" end wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(buyer.reload.community_notification_settings.find_by(seller:).recap_frequency).to eq("weekly") within "[aria-label='Community switcher area']" do select_disclosure "Switch creator" click_on "Notifications" end within_modal "Notifications" do expect(page).to have_checked_field("Community recap") expect(page).to have_radio_button("Daily", checked: false) expect(page).to have_radio_button("Weekly", checked: true) choose "Daily" click_on "Save" end wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(buyer.reload.community_notification_settings.find_by(seller:).recap_frequency).to eq("daily") within "[aria-label='Community switcher area']" do select_disclosure "Switch creator" click_on "Notifications" end within_modal "Notifications" do expect(page).to have_checked_field("Community recap") expect(page).to have_radio_button("Daily", checked: true) expect(page).to have_radio_button("Weekly", checked: false) uncheck "Community recap" expect(page).not_to have_radio_button("Daily") expect(page).not_to have_radio_button("Weekly") click_on "Save" end wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(buyer.reload.community_notification_settings.find_by(seller:).recap_frequency).to be_nil end it "allows buyer to switch between communities from the same seller" do product2 = create(:product, name: "Scaling web apps", user: seller, community_chat_enabled: true) community2 = create(:community, resource: product2, seller:) create(:purchase, seller:, purchaser: buyer, link: product2) create(:community_chat_message, community: community2, user: seller, content: "Are you ready to scale your web app?") visit community_path wait_for_ajax expect(page).to have_current_path(community_path(seller.external_id, community.external_id)) within "[aria-label='Sidebar']" do within "[aria-label='Community switcher area']" do expect(page).to have_text("Bob") end within "[aria-label='Community list']" do expect(page).to have_link("Mastering Rails", href: community_path(seller.external_id, community.external_id)) expect(page).to have_link("Scaling web apps", href: community_path(seller.external_id, community2.external_id)) community1_link_element = find_link("Mastering Rails") expect(community1_link_element["aria-selected"]).to eq("true") within community1_link_element do # Wait for the unread message count to disappear as IntersectionObserver marks message as read expect(page).to_not have_selector("[aria-label='Unread message count']", wait: 10) end community2_link_element = find_link("Scaling web apps") # Wait for the unread count to be rendered by the React component expect(page).to have_selector("[aria-label='Unread message count']", text: "1", wait: 10) expect(community2_link_element["aria-selected"]).to eq("false") end end within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("Mastering Rails") end within "[aria-label='Chat messages']" do expect(page).to have_text("Welcome to Mastering Rails") expect(page).to have_message("Hello from seller!") expect(page).to have_message("Hello from Jane!") end end within "[aria-label='Sidebar']" do click_link "Scaling web apps" wait_for_ajax within "[aria-label='Community list']" do expect(find_link("Mastering Rails")["aria-selected"]).to eq("false") expect(find_link("Scaling web apps")["aria-selected"]).to eq("true") end end expect(page).to have_current_path(community_path(seller.external_id, community2.external_id)) within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("Scaling web apps") end within "[aria-label='Chat messages']" do expect(page).to have_message("Are you ready to scale your web app?") expect(page).not_to have_message("Hello from Jane!") expect(page).not_to have_message("Hello from seller!") end fill_in "Type a message", with: "Wow, this is amazing!" click_button "Send message" wait_for_ajax message = community2.community_chat_messages.last expect(message.content).to eq("Wow, this is amazing!") expect(message.user).to eq(buyer) within "[aria-label='Chat messages']" do message_element = find_message("Wow, this is amazing!") message_element.hover within message_element do expect(page).to have_text("John Buyer") expect(page).not_to have_text("CREATOR") expect(page).to have_button("Edit message") expect(page).to have_button("Delete message") end end end within "[aria-label='Sidebar']" do click_link "Mastering Rails" wait_for_ajax within "[aria-label='Community list']" do expect(find_link("Mastering Rails")["aria-selected"]).to eq("true") expect(find_link("Scaling web apps")["aria-selected"]).to eq("false") end end within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("Mastering Rails") end within "[aria-label='Chat messages']" do expect(page).not_to have_message("Are you ready to scale your web app?") expect(page).not_to have_message("Wow, this is amazing!") expect(page).to have_text("Welcome to Mastering Rails") expect(page).to have_message("Hello from seller!") expect(page).to have_message("Hello from Jane!") end end end it "allows buyer to switch between communities from different sellers" do other_seller = create(:user, name: "Alice") Feature.activate_user(:communities, other_seller) other_product = create(:product, name: "The ultimate guide to design systems", user: other_seller, community_chat_enabled: true) other_community = create(:community, resource: other_product, seller: other_seller) create(:purchase, seller: other_seller, purchaser: buyer, link: other_product) create(:community_chat_message, community: other_community, user: other_seller, content: "Get excited!") visit community_path wait_for_ajax expect(page).to have_current_path(community_path(seller.external_id, community.external_id)) within "[aria-label='Sidebar']" do within "[aria-label='Community switcher area']" do expect(page).to have_text("Bob") end within "[aria-label='Community list']" do expect(page).to have_link("Mastering Rails", href: community_path(seller.external_id, community.external_id)) expect(page).not_to have_link("The ultimate guide to design systems") expect(find_link("Mastering Rails")["aria-selected"]).to eq("true") # Wait for the unread message count to disappear as IntersectionObserver marks message as read expect(page).to_not have_selector("[aria-label='Unread message count']", wait: 10) end end within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("Mastering Rails") end within "[aria-label='Chat messages']" do expect(page).to have_text("Welcome to Mastering Rails") expect(page).to have_message("Hello from seller!") expect(page).to have_message("Hello from Jane!") expect(page).not_to have_message("Get excited!") end end within "[aria-label='Sidebar']" do select_disclosure "Switch creator" click_on "Alice" wait_for_ajax within "[aria-label='Community switcher area']" do expect(page).to have_text("Alice") end expect(page).to have_current_path(community_path(other_seller.external_id, other_community.external_id)) refresh within "[aria-label='Community list']" do expect(page).to have_link("The ultimate guide to design systems", href: community_path(other_seller.external_id, other_community.external_id)) expect(page).not_to have_link("Mastering Rails") expect(find_link("The ultimate guide to design systems")["aria-selected"]).to eq("true") # Wait for the unread message count to disappear as IntersectionObserver marks message as read expect(page).not_to have_selector("[aria-label='Unread message count']", wait: 10) end end within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("The ultimate guide to design systems") end within "[aria-label='Chat messages']" do expect(page).to have_message("Get excited!") expect(page).not_to have_message("Hello from Jane!") expect(page).not_to have_message("Hello from seller!") end fill_in "Type a message", with: "This is great!" click_button "Send message" wait_for_ajax message = other_community.community_chat_messages.last expect(message.content).to eq("This is great!") expect(message.user).to eq(buyer) within "[aria-label='Chat messages']" do message_element = find_message("This is great!") message_element.hover within message_element do expect(page).to have_text("John Buyer") expect(page).not_to have_text("CREATOR") expect(page).to have_button("Edit message") expect(page).to have_button("Delete message") end end end within "[aria-label='Sidebar']" do select_disclosure "Switch creator" click_on "Bob" wait_for_ajax within "[aria-label='Community switcher area']" do expect(page).to have_text("Bob") end expect(page).to have_current_path(community_path(seller.external_id, community.external_id)) refresh within "[aria-label='Community list']" do expect(find_link("Mastering Rails")["aria-selected"]).to eq("true") expect(page).not_to have_link("The ultimate guide to design systems") end end within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("Mastering Rails") end within "[aria-label='Chat messages']" do expect(page).not_to have_message("Get excited!") expect(page).not_to have_message("This is great!") expect(page).to have_text("Welcome to Mastering Rails") expect(page).to have_message("Hello from seller!") expect(page).to have_message("Hello from Jane!") end end end it "allows accessing a community directly via URL" do visit community_path(seller.external_id, community.external_id) wait_for_ajax within "[aria-label='Sidebar']" do within "[aria-label='Community switcher area']" do expect(page).to have_text("Bob") end within "[aria-label='Community list']" do expect(page).to have_link("Mastering Rails", href: community_path(seller.external_id, community.external_id)) expect(find_link("Mastering Rails")["aria-selected"]).to eq("true") end end within "[aria-label='Chat window']" do within "[aria-label='Community chat header']" do expect(page).to have_text("Mastering Rails") end within "[aria-label='Chat messages']" do expect(page).to have_text("Welcome to Mastering Rails") expect(page).to have_message("Hello from seller!") expect(page).to have_message("Hello from Jane!") end end end it "does not allow accessing a community directly via URL if user cannot access it" do purchase.destroy! visit community_path(seller.external_id, community.external_id) expect(page).to have_alert(text: "You are not allowed to perform this action.") expect(page).to have_current_path(dashboard_path) end it "opens notifications modal when accessing community URL with notifications parameter" do visit community_path(seller.external_id, community.external_id, notifications: "true") wait_for_ajax within "[aria-label='Sidebar']" do within "[aria-label='Community switcher area']" do expect(page).to have_text("Bob") end end within_modal "Notifications" do expect(page).to have_text(%Q(Receive email recaps of what's happening in "Bob" community.)) expect(page).to have_unchecked_field("Community recap") expect(page).not_to have_radio_button("Daily") expect(page).not_to have_radio_button("Weekly") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/video_streaming_spec.rb
spec/requests/video_streaming_spec.rb
# frozen_string_literal: true require("spec_helper") describe "Video stream scenario", type: :system, js: true do before do @url_redirect = create(:streamable_url_redirect) @product = @url_redirect.referenced_link login_as(@url_redirect.purchase.purchaser) Link.import(refresh: true) end describe "Watch button" do it "shows Watch button for a file which has not been watched" do allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to have_link("Watch") end it "shows watch again button for a file which has been watched completely" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 12) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to have_link("Watch again") end it "is absent for product files with non-watchable urls" do @product.product_files.delete_all create(:non_streamable_video, :analyze, link: @product) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to_not have_link("Watch") end end describe "consumption progress pie" do it "does not show progress pie if not started watching" do allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to_not have_selector("[role='progressbar']") end it "shows progress pie if video has been watched partly" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 5) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to have_selector("[role='progressbar']") end it "shows completed progress pie if the complete video has been watched" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 12) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to have_selector("[role='progressbar'][aria-valuenow='100']") end end describe "streaming a file" do before do allow_any_instance_of(UrlRedirect).to receive(:html5_video_url_and_guid_for_product_file).and_return([@product.product_files.first.url, "DONT_MATCH_THIS_GUID"]) end it "shows the player for a streamable file" do visit("/d/#{@url_redirect.token}/") new_window = window_opened_by { click_on("Watch") } within_window new_window do expect(page).to have_selector(".jwplayer") expect(page).to have_selector("[aria-label^='Video Player']") click_on "Play" expect(page).to have_selector(".jw-text-duration", text: "00:12", visible: :all) end end it "resumes from previous location if media_location exists" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 6) visit("/s/#{@url_redirect.token}/#{@product.product_files.first.external_id}/") expect(page).to have_selector(".jw-text-duration", text: "00:12", visible: :all) click_on "Play" # need to start playback if directly going to the url as chrome blocks autoplay # video should start directly from 00:06 (0..5).each do |i| expect(page).to_not have_selector(".jw-text-elapsed", text: "00:0#{i}", visible: :all) end expect(page).to have_selector(".jw-text-elapsed", text: "00:06", visible: :all) expect(page).to have_selector(".jw-text-elapsed", text: "00:07", visible: :all) # to test if it continues playing end it "resumes from start if video has been watched completely" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 12) visit("/s/#{@url_redirect.token}/#{@product.product_files.first.external_id}/") expect(page).to have_selector(".jw-text-duration", text: "00:12", visible: :all) click_on "Play" # need to start playback if directly going to the url as chrome blocks autoplay expect(page).to have_selector(".jw-text-elapsed", text: "00:00", visible: :all) expect(page).to have_selector(".jw-text-elapsed", text: "00:01", visible: :all) # to test if it continues playing end context "triggers the correct consumption events" do it "creates consumption events on viewing the page and starting the stream" do expect do visit("/d/#{@url_redirect.token}/") end.to change(ConsumptionEvent, :count).by(1) view_event = ConsumptionEvent.last expect(view_event.event_type).to eq ConsumptionEvent::EVENT_TYPE_VIEW expect(view_event.link_id).to eq @product.id expect(view_event.product_file_id).to be_nil expect(view_event.url_redirect_id).to eq @url_redirect.id expect do new_window = window_opened_by { click_on("Watch") } within_window new_window do expect(page).to have_selector(".jwplayer") expect(page).to have_selector("[aria-label^='Video Player']") find(".jw-icon-playback", visible: :all).hover # the controls disappear otherwise, and click is flaky for visible:false expect(page).to have_selector(".jw-text-elapsed", text: "00:01", visible: :all) # let playback start find(".jw-icon-playback", visible: :all).click # Pause end # Wait until js has made async calls for tracking listen consumptions. wait_for_ajax end.to change(ConsumptionEvent, :count).by(1) watch_event = ConsumptionEvent.last expect(watch_event.event_type).to eq ConsumptionEvent::EVENT_TYPE_WATCH expect(watch_event.link_id).to eq @product.id expect(watch_event.product_file_id).to eq @product.product_files.first.id expect(watch_event.url_redirect_id).to eq @url_redirect.id end it "does not record media_location if purchase is nil" do streamable_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/ScreenRecording.mov" installment = create(:installment, call_to_action_text: "CTA", call_to_action_url: "https://www.gum.co", seller: @product.user) installment_product_file = create(:product_file, :analyze, installment:, url: streamable_url) installment_product_file.save!(validate: false) no_purchase_url_redirect = installment.generate_url_redirect_for_follower visit("/d/#{no_purchase_url_redirect.token}/") new_window = window_opened_by { click_on "Watch" } within_window new_window do expect(page).to have_selector(".jwplayer") expect(page).to have_selector("[aria-label^='Video Player']") find(".jw-icon-playback", visible: :all).hover expect(page).to have_selector(".jw-text-elapsed", text: "00:01", visible: :all) find(".jw-icon-playback", visible: :all).click end wait_for_ajax expect(MediaLocation.count).to eq 0 end it "updates watch progress location on watching the stream" do visit("/d/#{@url_redirect.token}/") new_window = window_opened_by { click_on "Watch" } within_window new_window do expect(page).to have_selector(".jwplayer") expect(page).to have_selector("[aria-label^='Video Player']") find(".jw-icon-playback", visible: :all).hover # the controls disappear otherwise, and click is flaky for visible:false expect(page).to have_selector(".jw-text-elapsed", text: "00:04", visible: :all) # wait for 4 seconds of playback find(".jw-icon-playback", visible: :all).click # Pause end # Wait until js has made async calls for tracking listen consumptions. wait_for_ajax expect(MediaLocation.count).to eq 1 media_location = MediaLocation.last expect(media_location.product_id).to eq @product.id expect(media_location.product_file_id).to eq @product.product_files.first.id expect(media_location.url_redirect_id).to eq @url_redirect.id expect(media_location.location).to be < 2 expect(media_location.unit).to eq MediaLocation::Unit::SECONDS end it "updates watch progress on completion of stream with the backend duration" do @product.product_files.first.update!(duration: 1000) create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 10) visit("/d/#{@url_redirect.token}/") new_window = window_opened_by { click_on("Watch") } within_window new_window do expect(page).to have_selector(".jwplayer") expect(page).to have_selector("[aria-label^='Video Player']") within ".jw-display-icon-container" do expect(page).to have_selector("[aria-label='Replay']") end wait_for_ajax end expect(MediaLocation.count).to eq 1 media_location = MediaLocation.last expect(media_location.product_id).to eq @product.id expect(media_location.product_file_id).to eq @product.product_files.first.id expect(media_location.url_redirect_id).to eq @url_redirect.id expect(media_location.location).to eq(1000) expect(media_location.unit).to eq MediaLocation::Unit::SECONDS end end describe "transcode on purchase" do before do @product_file = create(:streamable_video) @product = @product_file.link @url_redirect = @product.url_redirects.create login_as @product_file.link.user @product.enable_transcode_videos_on_purchase! allow_any_instance_of(UrlRedirect).to receive(:html5_video_url_and_guid_for_product_file).and_return([@product_file.url, "123"]) end context "when no purchases are made" do it "shows transcode on purchase notice" do visit url_redirect_stream_page_for_product_file_path(@url_redirect.token, @product.product_files.first.external_id) expect(page).to have_content("Your video will be transcoded on first sale.") expect(page).to have_content("Until then, you may experience some viewing issues. You'll get an email once it's done.") end end context "when a purchase is made" do before do purchase = create(:purchase_in_progress, link: @product) purchase.mark_successful! end it "shows video being transcoded notice" do visit url_redirect_stream_page_for_product_file_path(@url_redirect.token, @product.product_files.first.external_id) expect(@product.transcode_videos_on_purchase?).to eq false expect(page).to have_content("Your video is being transcoded.") expect(page).to have_content("Until then, you and your future customers may experience some viewing issues. You'll get an email once it's done.") 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/requests/tax_center_spec.rb
spec/requests/tax_center_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Tax Center", js: true, type: :system do let(:seller_created_at) { Date.new(4.years.ago.year, 6, 15) } let(:seller) { create(:user, created_at: seller_created_at) } before do Feature.activate_user(:tax_center, seller) login_as seller end it "renders with correct data" do year_1 = seller_created_at.year + 1 year_2 = seller_created_at.year + 2 create(:user_tax_form, user: seller, tax_year: year_1, tax_form_type: "us_1099_k") create(:user_tax_form, user: seller, tax_year: year_2, tax_form_type: "us_1099_k") product = create(:product, user: seller, price_cents: 1000) create(:purchase, :with_custom_fee, link: product, created_at: Date.new(year_1, 3, 15), fee_cents: 100, tax_cents: 15) create(:purchase, :with_custom_fee, link: product, created_at: Date.new(year_2, 6, 10), fee_cents: 50) visit tax_center_path expect(page).to have_select("Tax year", selected: (Time.current.year - 1).to_s) expect(page).to have_text("Let's get your tax info ready") expect(page).to have_text("Your 1099-K will appear here once it's available") expect(page).not_to have_table("Tax documents") select year_1.to_s, from: "Tax year" wait_for_ajax expect(page).to_not have_text("Let's get your tax info ready") expect(page).to have_table("Tax documents", with_rows: [ { "Document" => "1099-K", "Type" => "IRS form", "Gross" => "$10.00", "Fees" => "-$1.00", "Taxes" => "-$0.15", "Affiliate commission" => "-$0.00", "Net" => "$8.85" } ]) select year_2.to_s, from: "Tax year" wait_for_ajax expect(page).to have_select("Tax year", selected: year_2.to_s) expect(page).to have_table("Tax documents", with_rows: [ { "Document" => "1099-K", "Type" => "IRS form", "Gross" => "$10.00", "Fees" => "-$0.50", "Taxes" => "-$0.00", "Affiliate commission" => "-$0.00", "Net" => "$9.50" } ]) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/two_factor_authentication_spec.rb
spec/requests/two_factor_authentication_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Two-Factor Authentication", js: true, type: :system do include FillInUserProfileHelpers let(:user) { create(:named_user, skip_enabling_two_factor_authentication: false) } def login_to_app visit login_path submit_login_form end def submit_login_form fill_in "Email", with: user.email fill_in "Password", with: user.password click_on "Login" wait_for_ajax end it "redirects to two_factor_authentication_path on login" do expect do login_to_app expect(page).to have_content "Two-Factor Authentication" expect(page).to have_content "To protect your account, we have sent an Authentication Token to #{user.email}. Please enter it here to continue." expect(page.current_url).to eq two_factor_authentication_url(next: dashboard_path, host: Capybara.app_host) end.to have_enqueued_mail(TwoFactorAuthenticationMailer, :authentication_token).once.with(user.id) end describe "Submit authentication token" do context "when correct token is entered" do it "navigates to login_path_for(user) on successful two factor authentication and remembers 2FA status" do recreate_model_index(Purchase) login_to_app expect(page).to have_content "Two-Factor Authentication" expect(page).to have_link "Gumroad", href: UrlService.root_domain_with_protocol fill_in "Token", with: user.otp_code click_on "Login" wait_for_ajax expect(page.current_url).to eq dashboard_url(host: Capybara.app_host) fill_in_profile first("nav[aria-label='Main'] details summary").click click_on "Logout" login_to_app # It doesn't ask for 2FA again expect(page).to have_text("Dashboard") end end context "when incorrect token is entered" do it "shows an error message" do login_to_app expect(page).to have_content "Two-Factor Authentication" fill_in "Token", with: "abcd" click_on "Login" wait_for_ajax expect(page).to have_content("Invalid token, please try again.") end end end describe "Resend authentication token" do it "resends the authentication token" do expect do login_to_app expect(page).to have_content "Two-Factor Authentication" click_on "Resend Authentication Token" wait_for_ajax end.to have_enqueued_mail(TwoFactorAuthenticationMailer, :authentication_token).twice.with(user.id) end end describe "Two factor auth verification link" do it "navigates to logged in path" do login_to_app expect(page).to have_content "Two-Factor Authentication" # Fill the data before opening a new window to make sure the page is fully loaded before switching to the new page. fill_in "Token", with: "invalid" new_window = open_new_window within_window new_window do visit verify_two_factor_authentication_path(token: user.otp_code, user_id: user.encrypted_external_id, format: :html) expect(page.current_url).to eq dashboard_url(host: Capybara.app_host) end # Once 2FA is verified through link, it should redirect to logged in page without checking token click_on "Login" wait_for_ajax expect(page.current_url).to eq dashboard_url(host: Capybara.app_host) end it "navigates to login page when the user is not logged in before" do expect do two_factor_verify_link = verify_two_factor_authentication_path(token: user.otp_code, user_id: user.encrypted_external_id, format: :html) visit two_factor_verify_link expect(page.current_url).to eq login_url(host: Capybara.app_host, next: two_factor_verify_link) submit_login_form # It directly navigates to logged in page since 2FA is verified through the link between the redirects. expect(page).to have_text("Dashboard") expect(page.current_url).to eq dashboard_url(host: Capybara.app_host) end.not_to have_enqueued_mail(TwoFactorAuthenticationMailer, :authentication_token).with(user.id) end it "allows to login with a valid 2FA token when an expired login link is clicked" do two_factor_verify_link = verify_two_factor_authentication_path(token: "invalid", user_id: user.encrypted_external_id, format: :html) visit two_factor_verify_link expect(page.current_url).to eq login_url(host: Capybara.app_host, next: two_factor_verify_link) submit_login_form expect(page).to have_content "Two-Factor Authentication" fill_in "Token", with: user.otp_code click_on "Login" wait_for_ajax expect(page.current_url).to eq dashboard_url(host: Capybara.app_host) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/two_factor_authentication_request_spec.rb
spec/requests/two_factor_authentication_request_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Two-Factor Authentication endpoint", type: :request do let(:user) { create(:user) } before do allow_any_instance_of(ActionDispatch::Request).to receive(:host).and_return(VALID_REQUEST_HOSTS.first) allow_any_instance_of(TwoFactorAuthenticationController).to receive(:user_for_two_factor_authentication).and_return(user) end it "is successful with correct params" do post "/two-factor.json?user_id=#{user.encrypted_external_id}", params: { token: user.otp_code }.to_json, headers: { "CONTENT_TYPE" => "application/json" } expect(response).to have_http_status(:ok) end # This is important to make sure rate limiting works as expected. We send the user_id in the query string # (see app/javascript/data/login.ts) because we rate limit on user_id, and Rack::Attack does not parse JSON request bodies. # If Rails ever starts prioritising body params over query string params, users would be able to brute force OTP codes by # sending a random user_id (for rate limiting) in the query and the correct one (for the controller to parse) in the body. it "prioritises user_id in the query string over POST body" do post "/two-factor.json?user_id=invalid-id", params: { token: user.otp_code, user_id: user.encrypted_external_id }.to_json, headers: { "CONTENT_TYPE" => "application/json" } expect(response).to have_http_status(:not_found) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/reading_spec.rb
spec/requests/reading_spec.rb
# frozen_string_literal: true require("spec_helper") describe "Reading Scenario", type: :system, js: true do before do @url_redirect = create(:readable_url_redirect) @product = @url_redirect.referenced_link login_as(@url_redirect.purchase.purchaser) Link.import(refresh: true) end describe "read button" do describe "for a link with a product file" do it "is present when url is a pdf" do allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") Link.import(refresh: true) visit("/library") find_product_card(@product).click expect(page).to have_link("Read") end context "for a product file with a pdf url" do it "shows read button for a file which has not been read" do allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to have_link("Read") end it "shows read again button for a file which has been read completely" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 6) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to have_link("Read again") end end it "is absent for product files with non-pdf urls" do @product.product_files.delete_all create(:non_readable_document, :analyze, link: @product) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to_not have_link("Read") end end end describe "consumption progress pie" do it "does not show progress pie if not started reading" do allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to_not have_selector("[role='progressbar']") end it "shows progress pie if reading in progress" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 1) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to have_selector("[role='progressbar']") end it "shows completed progress pie if reading is done" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 6) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to have_selector("[role='progressbar'][aria-valuenow='100']") end end describe "readable document" do it "shows the proper layout for a PDF" do file = @product.product_files.first allow_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(file.url) visit("/read/#{@url_redirect.token}/#{file.external_id}") expect(page).to have_text("One moment while we prepare your reading experience") expect(page).to have_text("Building a billion-dollar company.") end end describe "resuming from previous location" do it "starts from first page if no media_location is present" do expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(@product.product_files.first.url) visit("/read/#{@url_redirect.token}/#{@product.product_files.first.external_id}") expect(page).to have_content("1 of 6") end it "uses cookie if media_location only available in cookie" do visit("/read/fake_url_redirect_id/fake_read_id") cookie_id = CGI.escape(@product.product_files.first.external_id) browser = Capybara.current_session.driver.browser browser.manage.delete_cookie(cookie_id) browser.manage.add_cookie(name: cookie_id, value: { location: 3, timestamp: Time.current }.to_json) expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(@product.product_files.first.url) visit("/read/#{@url_redirect.token}/#{@product.product_files.first.external_id}") expect(page).to have_content("3 of 6") end it "uses backend if media_location only available in backend" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 2) expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(@product.product_files.first.url) visit("/read/#{@url_redirect.token}/#{@product.product_files.first.external_id}") expect(page).to have_content("2 of 6") end context "media_location available in both backend and cookie" do it "uses backend location if backend media_location is latest one" do timestamp = Time.current visit("/read/fake_url_redirect_id/fake_read_id") create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, consumed_at: timestamp + 1.second, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 2) cookie_id = CGI.escape(@url_redirect.external_id) browser = Capybara.current_session.driver.browser browser.manage.delete_cookie(cookie_id) browser.manage.add_cookie(name: cookie_id, value: { location: 3, timestamp: }.to_json) expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(@product.product_files.first.url) visit("/read/#{@url_redirect.token}/#{@product.product_files.first.external_id}") expect(page).to have_content("2 of 6") end it "uses cookie location if cookie media_location is latest one" do timestamp = Time.current visit("/read/fake_url_redirect_id/fake_read_id") create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, consumed_at: timestamp, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 2) cookie_id = CGI.escape(@product.product_files.first.external_id) browser = Capybara.current_session.driver.browser browser.manage.delete_cookie(cookie_id) browser.manage.add_cookie(name: cookie_id, value: { location: 3, timestamp: timestamp + 1.second }.to_json) expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(@product.product_files.first.url) visit("/read/#{@url_redirect.token}/#{@product.product_files.first.external_id}") expect(page).to have_content("3 of 6") end end it "resumes from start if reading was complete as per media_location in backend" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 6) expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(@product.product_files.first.url) visit("/read/#{@url_redirect.token}/#{@product.product_files.first.external_id}") expect(page).to have_content("1 of 6") end it "resumes from start if reading was complete as per media_location in cookie" do visit("/read/fake_url_redirect_id/fake_read_id") cookie_id = CGI.escape(@url_redirect.external_id) browser = Capybara.current_session.driver.browser browser.manage.delete_cookie(cookie_id) browser.manage.add_cookie(name: cookie_id, value: { location: 6, timestamp: Time.current }.to_json) expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(@product.product_files.first.url) visit("/read/#{@url_redirect.token}/#{@product.product_files.first.external_id}") expect(page).to have_content("1 of 6") end end describe "readable document consumption analytics", type: :system, js: true do it "does not record media_location if purchase is nil" do readable_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/billion-dollar-company-chapter-0.pdf" installment = create(:installment, call_to_action_text: "CTA", call_to_action_url: "https://www.gum.co", seller: @product.user) installment_product_file = create(:product_file, :analyze, installment:, url: readable_url) no_purchase_url_redirect = installment.generate_url_redirect_for_follower expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(readable_url) visit("/read/#{no_purchase_url_redirect.token}/#{installment_product_file.external_id}") expect(page).to have_content("1 of 6") wait_for_ajax expect(MediaLocation.count).to eq 0 end it "records the proper consumption analytics for the pdf file" do file = @product.product_files.first expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(file.url) visit("/read/#{@url_redirect.token}/#{file.external_id}") expect(page).to have_content("1 of 6") # Wait until js has made async calls for tracking read consumptions. wait_for_ajax expect(ConsumptionEvent.count).to eq 1 read_event = ConsumptionEvent.first expect(read_event.event_type).to eq ConsumptionEvent::EVENT_TYPE_READ expect(read_event.link_id).to eq @product.id expect(read_event.product_file_id).to eq file.id expect(read_event.url_redirect_id).to eq @url_redirect.id expect(read_event.ip_address).to eq "127.0.0.1" expect(MediaLocation.count).to eq 1 media_location = MediaLocation.last expect(media_location.product_id).to eq @product.id expect(media_location.product_file_id).to eq file.id expect(media_location.url_redirect_id).to eq @url_redirect.id expect(media_location.location).to eq 1 expect(media_location.unit).to eq MediaLocation::Unit::PAGE_NUMBER end end describe "redirect" do it "redirects to library if no token" do visit("/read") expect(page).to have_section("Library", section_element: :header) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/balance_pages_spec.rb
spec/requests/balance_pages_spec.rb
# frozen_string_literal: true require "spec_helper" require "ostruct" require "shared_examples/authorize_called" describe "Balance Pages Scenario", js: true, type: :system do include CollabProductHelper include StripeMerchantAccountHelper let(:seller) { create(:named_seller) } let(:get_label_value) do -> (text) do find("h4", text:).find(:xpath, "..").find(":last-child").text end end include_context "with switching account to user as admin for seller" describe "index page", type: :system do it "shows empty notice if creator hasn't reached balance" do visit balance_path expect(page).to have_content "Let's get you paid." end describe "affiliate commission" do let(:seller) { create(:affiliate_user, username: "momoney", user_risk_state: "compliant") } before do @affiliate_user = create(:affiliate_user) @product = create :product, user: seller, price_cents: 10_00 @direct_affiliate = create :direct_affiliate, affiliate_user: @affiliate_user, seller:, affiliate_basis_points: 3000, products: [@product] @affiliate_product = create :product, price_cents: 150_00 @seller_affiliate = create :direct_affiliate, affiliate_user: seller, seller: @affiliate_product.user, affiliate_basis_points: 4000, products: [@affiliate_product] end it "displays credits and fees in separate rows" do @purchase = create(:purchase_in_progress, seller:, link: @product, affiliate: @direct_affiliate) @affiliate_purchase = create(:purchase_in_progress, link: @affiliate_product, affiliate: @seller_affiliate) [@purchase, @affiliate_purchase].each do |purchase| purchase.process! purchase.update_balance_and_mark_successful! end affiliate_commission_received = seller.affiliate_credits.sum("amount_cents") affiliate_commission_paid = seller.sales.sum("affiliate_credit_cents") index_model_records(Purchase) visit balance_path expect(get_label_value["Affiliate or collaborator fees received"]).to eq format_money(affiliate_commission_received) expect(get_label_value["Affiliate or collaborator fees paid"]).to eq format_money_negative(affiliate_commission_paid) end it "reflects refunds of affiliate and own sales separately" do 3.times.map { create(:purchase_in_progress, seller:, link: @product, affiliate: @direct_affiliate) }.each do |purchase| purchase.process! purchase.update_balance_and_mark_successful! end 2.times.map { create(:purchase_in_progress, link: @affiliate_product, affiliate: @seller_affiliate) }.each do |purchase| purchase.process! purchase.update_balance_and_mark_successful! end affiliate_commission_received = seller.affiliate_credits.sum("amount_cents") affiliate_commission_paid = seller.sales.sum("affiliate_credit_cents") visit balance_path expect(get_label_value["Affiliate or collaborator fees received"]).to eq format_money(affiliate_commission_received) expect(get_label_value["Affiliate or collaborator fees paid"]).to eq format_money_negative(affiliate_commission_paid) @purchase = seller.sales.last @affiliate_purchase = seller.affiliate_credits.last.purchase [@purchase, @affiliate_purchase].each do |purchase| purchase.refund_purchase!(FlowOfFunds.build_simple_flow_of_funds(Currency::USD, purchase.total_transaction_cents), seller.id) end visit balance_path commission_received_refund = @affiliate_purchase.affiliate_credit_cents commission_paid_refund = @purchase.affiliate_credit_cents expect(get_label_value["Affiliate or collaborator fees received"]).to eq format_money(affiliate_commission_received - commission_received_refund) expect(get_label_value["Affiliate or collaborator fees paid"]).to eq format_money_negative(affiliate_commission_paid - commission_paid_refund) end end describe "current payout" do let!(:now) { Time.current } let(:seller) { create :user, user_risk_state: "compliant" } it "show processing payment for current payout" do product = create :product, user: seller, name: "Petting Capybaras For Fun And Profit" purchase = create :purchase, price_cents: 1000, seller:, link: product, card_type: CardType::PAYPAL, purchase_state: "in_progress" purchase.update_balance_and_mark_successful! payment, _ = Payouts.create_payment(now, PayoutProcessorType::PAYPAL, seller) payment.update(correlation_id: "12345") payment.txn_id = 123 data = { should_be_shown_currencies_always: true, displayable_payout_period_range: "Activity up to #{humanize_date(now)}", payout_date_formatted: humanize_date(now), payout_currency: "USD", payout_cents: 1000, payout_displayed_amount: "$10.00 USD", is_processing: true, arrival_date: 3.days.from_now.strftime("%B #{3.days.from_now.day.ordinalize}, %Y"), status: "processing", payment_external_id: "12345", sales_cents: 1000, refunds_cents: 0, chargebacks_cents: 0, credits_cents: 0, loan_repayment_cents: 0, fees_cents: 0, taxes_cents: 0, discover_fees_cents: 0, direct_fees_cents: 0, discover_sales_count: 0, direct_sales_count: 0, affiliate_credits_cents: 0, affiliate_fees_cents: 0, paypal_payout_cents: 0, stripe_connect_payout_cents: 0, payout_method_type: "none", payout_note: nil, type: Payouts::PAYOUT_TYPE_STANDARD, has_stripe_connect: false } allow_any_instance_of(UserBalanceStatsService).to receive(:payout_period_data).and_return(data) visit balance_path within_section "Payout initiated on #{humanize_date now}", match: :first do expect(page).to have_content("Sales\n$10.00 USD") end end it "shows processing payments for all bank account types" do UpdatePayoutMethod.bank_account_types.each do |bank_account_type, params| bank_account = create(bank_account_type.underscore, user: seller) data = { should_be_shown_currencies_always: true, displayable_payout_period_range: "Activity up to May 6th, 2022", payout_date_formatted: "May 14th, 2022", payout_currency: bank_account.currency, payout_cents: 3293600, payout_displayed_amount: "$90.70 USD", is_processing: true, arrival_date: 3.days.from_now.strftime("%B #{3.days.from_now.day.ordinalize}, %Y"), status: "processing", payment_external_id: "l5C1XQfr2TG3WXcGY7YrUg==", sales_cents: 10000, refunds_cents: 0, chargebacks_cents: 0, credits_cents: 0, loan_repayment_cents: 0, fees_cents: 930, taxes_cents: 0, discover_fees_cents: 0, direct_fees_cents: 0, discover_sales_count: 0, direct_sales_count: 0, affiliate_credits_cents: 0, affiliate_fees_cents: 0, paypal_payout_cents: 0, stripe_connect_payout_cents: 0, account_number: "1112121234", bank_account_type: bank_account.bank_account_type, bank_number: "9876", routing_number: "100", payout_method_type: "bank", payout_note: "Payout on November 7, 2024 was skipped because a bank account wasn't added at the time.", type: Payouts::PAYOUT_TYPE_STANDARD, has_stripe_connect: false }.merge(params[:permitted_params].index_with { |_p| "000" }) allow_any_instance_of(UserBalanceStatsService).to receive(:payout_period_data).and_return(data) create(:payment, user: seller) visit balance_path expect(page).to have_text("Account: 1112121234") expect(page).to have_text("Payout initiated on May 14th, 2022") expect(page).to have_text("Expected deposit on #{3.days.from_now.strftime("%B #{3.days.from_now.day.ordinalize}, %Y")}") expect(page).not_to have_text("Payout on November 7, 2024 was skipped because a bank account wasn't added at the time.") end end it "shows processing payments for creator-owned Stripe Connect payouts" do merchant_account = create(:merchant_account_stripe_connect, user: seller) create(:payment, user: seller) data = { should_be_shown_currencies_always: true, displayable_payout_period_range: "Activity up to May 6th, 2022", payout_date_formatted: "May 14th, 2022", payout_currency: "USD", payout_cents: 3293600, payout_displayed_amount: "$90.70 USD", is_processing: true, arrival_date: nil, status: "processing", payment_external_id: "l5C1XQfr2TG3WXcGY7YrUg==", sales_cents: 10000, refunds_cents: 0, chargebacks_cents: 0, credits_cents: 0, loan_repayment_cents: 0, fees_cents: 930, taxes_cents: 0, discover_fees_cents: 0, direct_fees_cents: 0, discover_sales_count: 0, direct_sales_count: 0, affiliate_credits_cents: 0, affiliate_fees_cents: 0, paypal_payout_cents: 0, stripe_connect_payout_cents: 0, stripe_connect_account_id: merchant_account.charge_processor_merchant_id, payout_method_type: "stripe_connect", payout_note: nil, type: Payouts::PAYOUT_TYPE_STANDARD, has_stripe_connect: true } allow_any_instance_of(UserBalanceStatsService).to receive(:payout_period_data).and_return(data) visit balance_path expect(page).to have_text("Stripe account: #{merchant_account.charge_processor_merchant_id}") expect(page).not_to have_text("Expected deposit on") end it "shows completed payments for creator-owned Stripe Connect payouts" do merchant_account = create(:merchant_account_stripe_connect, user: seller) create(:payment_completed, user: seller) top_period_data = { status: "not_payable", should_be_shown_currencies_always: true, minimum_payout_amount_cents: 1000, } data = { should_be_shown_currencies_always: true, displayable_payout_period_range: "Activity up to May 6th, 2022", payout_date_formatted: "May 14th, 2022", payout_currency: "USD", payout_cents: 3293600, payout_displayed_amount: "$90.70 USD", arrival_date: nil, status: "completed", is_processing: false, payment_external_id: "l5C1XQfr2TG3WXcGY7YrUg==", sales_cents: 10000, refunds_cents: 0, chargebacks_cents: 0, credits_cents: 0, loan_repayment_cents: 0, fees_cents: 930, taxes_cents: 0, discover_fees_cents: 0, direct_fees_cents: 0, discover_sales_count: 0, direct_sales_count: 0, affiliate_credits_cents: 0, affiliate_fees_cents: 0, paypal_payout_cents: 0, stripe_connect_payout_cents: 0, stripe_connect_account_id: merchant_account.charge_processor_merchant_id, payout_method_type: "stripe_connect", type: Payouts::PAYOUT_TYPE_STANDARD, has_stripe_connect: true } allow_any_instance_of(UserBalanceStatsService).to receive(:payout_period_data).and_return(top_period_data) allow_any_instance_of(PayoutsPresenter).to receive(:payout_period_data).and_return(data) visit balance_path expect(page).to have_text("Stripe account: #{merchant_account.charge_processor_merchant_id}") expect(page).not_to have_text("Expected deposit on") end describe "instant payouts" do let(:seller) { create(:compliant_user, unpaid_balance_cents: 10_01) } let!(:merchant_account) { create(:merchant_account_stripe_connect, user: seller) } let(:stripe_connect_account_id) { merchant_account.charge_processor_merchant_id } before do create(:ach_account, user: seller, stripe_bank_account_id: stripe_connect_account_id) create(:user_compliance_info, user: seller) end context "when there is a processing instant payout" do let!(:instant_payout) do create(:payment, user: seller, processor: PayoutProcessorType::STRIPE, state: "processing", stripe_connect_account_id:, payout_period_end_date: 1.month.ago, json_data: { payout_type: Payouts::PAYOUT_TYPE_INSTANT }) end it "only renders the instant payout" do visit balance_path expect(page).to have_text("Payout initiated on #{humanize_date(instant_payout.created_at)}\nInstant\nActivity") expect(page).to_not have_text("Next payout") end context "when there is also a processing standard payout" do let!(:standard_payout) do create(:payment, user: seller, processor: PayoutProcessorType::STRIPE, state: "processing", stripe_connect_account_id:) end it "renders both instant and standard payouts as processing, and no next payout" do visit balance_path expect(page).to have_text("Payout initiated on #{humanize_date(instant_payout.created_at)}\nInstant\nActivity") expect(page).to have_text("Payout initiated on #{humanize_date(standard_payout.created_at)}\nActivity") expect(page).not_to have_text("Next payout") end end end end context "when current payment is not processing" do let(:seller) { create(:user, user_risk_state: "compliant") } let(:product) { create(:product, user: seller, price_cents: 20_00) } let(:merchant_account) { create(:merchant_account_stripe_connect, user: seller) } before do (0..13).each do |days_count| travel_to(Date.parse("2013-08-14") - days_count.days) do create(:purchase_with_balance, link: product) end end seller.add_payout_note(content: "Payout on November 7, 2024 was skipped because a bank account wasn't added at the time.") end context "when payouts status is payable" do it "renders the date in heading" do travel_to(Date.parse("2013-08-14")) do visit balance_path expect(page).not_to have_content "Your payouts have been paused." expect(page).to have_text("Payout on November 7, 2024 was skipped because a bank account wasn't added at the time.") expect(page).to have_section("Next payout: August 16th, 2013") end end it "shows the creator-owned Stripe Connect account when it is the destination of the 'Next Payout'" do data = { should_be_shown_currencies_always: true, displayable_payout_period_range: "Activity up to May 6th, 2022", payout_date_formatted: "May 14th, 2022", payout_currency: "USD", payout_cents: 3293600, payout_displayed_amount: "$90.70 USD", arrival_date: nil, status: "payable", payment_external_id: "l5C1XQfr2TG3WXcGY7YrUg==", sales_cents: 10000, refunds_cents: 0, chargebacks_cents: 0, credits_cents: 0, loan_repayment_cents: 0, fees_cents: 930, taxes_cents: 0, discover_fees_cents: 0, direct_fees_cents: 0, discover_sales_count: 0, direct_sales_count: 0, affiliate_credits_cents: 0, affiliate_fees_cents: 0, paypal_payout_cents: 0, stripe_connect_payout_cents: 0, stripe_connect_account_id: merchant_account.charge_processor_merchant_id, payout_method_type: "stripe_connect", payout_note: nil, type: Payouts::PAYOUT_TYPE_STANDARD, has_stripe_connect: true } allow_any_instance_of(UserBalanceStatsService).to receive(:payout_period_data).and_return(data) visit balance_path expect(page).to have_content("For Stripe Connect users, all future payouts will be deposited directly to your Stripe account") end end context "when payouts have been manually paused by admin" do before do seller.update!(payouts_paused_internally: true) end it "renders notice and paused in the heading" do travel_to(Date.parse("2013-08-14")) do visit balance_path expect(page).to have_status(text: "Your payouts have been paused by Gumroad admin.") expect(page).to have_section("Next payout: paused") expect(page).not_to have_text("Payout on November 7, 2024 was skipped because a bank account wasn't added at the time.") end end it "includes the reason provided by admin in the notice" do seller.comments.create!( author_id: User.last.id, content: "Chargeback rate is too high.", comment_type: Comment::COMMENT_TYPE_PAYOUTS_PAUSED ) travel_to(Date.parse("2013-08-14")) do visit balance_path expect(page).to have_status(text: "Your payouts have been paused by Gumroad admin. Reason for pause: Chargeback rate is too high.") expect(page).to have_section("Next payout: paused") expect(page).not_to have_text("Payout on November 7, 2024 was skipped because a bank account wasn't added at the time.") end end end context "when payouts have been automatically paused by the system" do before do seller.update!(payouts_paused_internally: true, payouts_paused_by: User::PAYOUT_PAUSE_SOURCE_SYSTEM) end it "renders notice and paused in the heading" do travel_to(Date.parse("2013-08-14")) do visit balance_path expect(page).to have_status(text: "Your payouts have been automatically paused for a security review and will be resumed once the review completes.") expect(page).to have_section("Next payout: paused") expect(page).not_to have_text("Payout on November 7, 2024 was skipped because a bank account wasn't added at the time.") end end end context "when payouts have been paused by Stripe" do before do seller.update!(payouts_paused_internally: true, payouts_paused_by: User::PAYOUT_PAUSE_SOURCE_STRIPE) end it "renders notice and paused in the heading" do travel_to(Date.parse("2013-08-14")) do visit balance_path expect(page).to have_status(text: "Your payouts are currently paused by our payment processor. Please check your Payment Settings for any verification requirements.") expect(page).to have_section("Next payout: paused") expect(page).not_to have_text("Payout on November 7, 2024 was skipped because a bank account wasn't added at the time.") end end end context "when payouts have been paused by the seller" do before do seller.update!(payouts_paused_by_user: true) end it "renders notice and paused in the heading" do travel_to(Date.parse("2013-08-14")) do visit balance_path expect(page).to have_status(text: "You have paused your payouts. Please go to Payment Settings to resume payouts.") expect(page).to have_section("Next payout: paused") expect(page).not_to have_text("Payout on November 7, 2024 was skipped because a bank account wasn't added at the time.") end end end describe "payout-skipped notes" do context "when the payout was skipped because the account was under review" do before do seller.update!(user_risk_state: "not_reviewed") Payouts.is_user_payable(seller, Date.yesterday, add_comment: true, from_admin: false) seller.mark_compliant!(author_name: "iffy") end it "shows the payout-skipped notice" do visit balance_path expect(page).to have_text("Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because the account was under review.") end end context "when the payout was skipped because the account was not compliant" do before do seller.flag_for_tos_violation!(author_name: "iffy", bulk: true) seller.suspend_for_tos_violation!(author_name: "iffy", bulk: true) Payouts.is_user_payable(seller, Date.yesterday, add_comment: true, from_admin: false) seller.mark_compliant!(author_name: "iffy") end it "shows the payout-skipped notice" do visit balance_path expect(page).to have_text("Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because the account was not compliant.") end end context "when the payout was skipped because the payouts were paused by the admin" do before do seller.update!(payouts_paused_internally: true) Payouts.is_user_payable(seller, Date.yesterday, add_comment: true, from_admin: false) seller.update!(payouts_paused_internally: false) end it "shows the payout-skipped notice" do visit balance_path expect(page).to have_text("Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because payouts on the account were paused by the admin.") end end context "when the payout was skipped because the payouts were paused by the system" do before do seller.update!(payouts_paused_internally: true, payouts_paused_by: User::PAYOUT_PAUSE_SOURCE_SYSTEM) Payouts.is_user_payable(seller, Date.yesterday, add_comment: true, from_admin: false) seller.update!(payouts_paused_internally: false, payouts_paused_by: nil) end it "shows the payout-skipped notice" do visit balance_path expect(page).to have_text("Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because payouts on the account were paused by the system.") end end context "when the payout was skipped because the payouts were paused by Stripe" do before do seller.update!(payouts_paused_internally: true, payouts_paused_by: User::PAYOUT_PAUSE_SOURCE_STRIPE) Payouts.is_user_payable(seller, Date.yesterday, add_comment: true, from_admin: false) seller.update!(payouts_paused_internally: false, payouts_paused_by: nil) end it "shows the payout-skipped notice" do visit balance_path expect(page).to have_text("Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because payouts on the account were paused by the payout processor.") end end context "when the payout was skipped because the payouts were paused by the seller" do before do seller.update!(payouts_paused_by_user: true) Payouts.is_user_payable(seller, Date.yesterday, add_comment: true, from_admin: false) seller.update!(payouts_paused_by_user: false) end it "shows the payout-skipped notice" do visit balance_path expect(page).to have_text("Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because payouts on the account were paused by the user.") end end context "when the payout was skipped because the payout amount was less than the threshold" do before do allow_any_instance_of(User).to receive(:unpaid_balance_cents_up_to_date).and_return(5_00) Payouts.is_user_payable(seller, Date.yesterday, add_comment: true, from_admin: false) end it "shows the payout-skipped notice" do visit balance_path expect(page).to have_text("Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because the account balance $5 USD was less than the minimum payout amount of $10 USD.") end end context "when the payout was skipped because a payout was already in processing" do before do payment = create(:payment, user: seller) Payouts.is_user_payable(seller, Date.yesterday, add_comment: true, from_admin: false) payment.mark_failed! end it "shows the payout-skipped notice" do visit balance_path expect(page).to have_text("Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because there was already a payout in processing.") end end context "when the payout was skipped because there was no bank account on record" do before do Payouts.is_user_payable(seller, Date.yesterday, add_comment: true, from_admin: false) end it "shows the payout-skipped notice" do visit balance_path expect(page).to have_text("Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because a bank account wasn't added at the time.") end end context "when the payout was skipped because bank account info is not correctly updated" do before do create(:ach_account, user: seller) Payouts.is_user_payable(seller, Date.yesterday, add_comment: true, from_admin: false) end it "shows the payout-skipped notice" do visit balance_path expect(page).to have_text("Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because the payout bank account was not correctly set up.") end end context "when the payout was skipped because payout amount was less than the local currency threshold" do before do create(:user_compliance_info, user: seller, country: "South Korea") create(:korea_bank_account, user: seller, stripe_connect_account_id: "sc_id", stripe_bank_account_id: "ba_id") create(:merchant_account, user: seller) allow_any_instance_of(User).to receive(:unpaid_balance_cents_up_to_date).and_return(15_00) Payouts.is_user_payable(seller, Date.yesterday, add_comment: true, from_admin: false) end it "shows the payout-skipped notice" do visit balance_path expect(page).to have_text("Payout on #{Time.current.to_fs(:formatted_date_full_month)} was skipped because the account balance $15 USD was less than the minimum payout amount of $34.74 USD.") end end end end it "shows currency conversion message when payout currency is not USD" do seller = create(:user, user_risk_state: "compliant") create(:ach_account, user: seller) data = { should_be_shown_currencies_always: true, displayable_payout_period_range: "Activity up to May 6th, 2022", payout_date_formatted: "May 14th, 2022", payout_currency: "EUR", payout_cents: 10000, payout_displayed_amount: "€100.00 EUR", is_processing: false, arrival_date: nil, status: "payable", payment_external_id: "l5C1XQfr2TG3WXcGY7YrUg==", sales_cents: 11000, refunds_cents: 0, chargebacks_cents: 0, credits_cents: 0, loan_repayment_cents: 0, fees_cents: 930, taxes_cents: 0, discover_fees_cents: 0, direct_fees_cents: 0, discover_sales_count: 0, direct_sales_count: 0, affiliate_credits_cents: 0, affiliate_fees_cents: 0, paypal_payout_cents: 0, stripe_connect_payout_cents: 0, account_number: "1112121234", bank_account_type: "ACH", bank_number: "9876", routing_number: "100", payout_method_type: "bank", payout_note: nil, type: Payouts::PAYOUT_TYPE_STANDARD, has_stripe_connect: false } allow_any_instance_of(UserBalanceStatsService).to receive(:payout_period_data).and_return(data) visit balance_path expect(page).to have_text("Will be converted to EUR and sent to:") end it "shows expected deposit date and non-USD amount for processing payments" do seller = create(:user, user_risk_state: "compliant") create(:ach_account, user: seller) data = { should_be_shown_currencies_always: true, displayable_payout_period_range: "Activity up to #{2.days.ago.strftime('%B %-d, %Y')}", payout_date_formatted: Date.today.strftime("%B %-d, %Y"), payout_currency: "EUR", payout_cents: 10000, payout_displayed_amount: "€100.00 EUR", is_processing: true, arrival_date: 3.days.from_now.strftime("%B #{3.days.from_now.day.ordinalize}, %Y"), status: "processing", payment_external_id: "l5C1XQfr2TG3WXcGY7YrUg==", sales_cents: 11000, refunds_cents: 0, chargebacks_cents: 0, credits_cents: 0, loan_repayment_cents: 0, fees_cents: 930, taxes_cents: 0, direct_fees_cents: 0, discover_fees_cents: 0, discover_sales_count: 0, direct_sales_count: 0, affiliate_credits_cents: 0, affiliate_fees_cents: 0, paypal_payout_cents: 0, stripe_connect_payout_cents: 0, account_number: "1112121234", bank_account_type: "ACH", bank_number: "9876", routing_number: "100", payout_method_type: "bank", payout_note: nil, type: "standard", has_stripe_connect: false, minimum_payout_amount_cents: 1000, is_payable: true } allow_any_instance_of(UserBalanceStatsService).to receive(:payout_period_data).and_return(data) visit balance_path expect(page).to have_text("Expected deposit on") expect(page).to have_text("€100.00 EUR") end end describe "instant payout" do context "when user has a balance and is eligible for instant payouts" do before do create(:tos_agreement, user: seller) create(:user_compliance_info, user: seller) create_list(:payment_completed, 4, user: seller) create(:bank, routing_number: "110000000", name: "Bank of America") create(:ach_account_stripe_succeed, user: seller, routing_number: "110000000", stripe_connect_account_id: "acct_12345", stripe_external_account_id: "ba_12345", stripe_fingerprint: "fingerprint", ) create(:merchant_account, user: seller, charge_processor_merchant_id: "acct_12345") Credit.create_for_credit!(user: seller, amount_cents: 1000, crediting_user: seller) allow_any_instance_of(User).to receive(:compliant?).and_return(true) allow_any_instance_of(User).to receive(:eligible_for_instant_payouts?).and_return(true) allow_any_instance_of(BankAccount).to receive(:supports_instant_payouts?).and_return(true)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/authentication_spec.rb
spec/requests/authentication_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Authentication Scenario", type: :system, js: true) do include FillInUserProfileHelpers before(:each) do create(:user) end describe("when user is not logged in") do it "prevents signing up with a compromised password" do visit("/signup") expect do vcr_turned_on do VCR.use_cassette("Signup-with a compromised password") do with_real_pwned_password_check do fill_in("Email", with: "user@test.com") fill_in("Password", with: "password") click_on("Create account") expect(page).to_not have_content("Dashboard") expect(page).to have_alert(text: "Password has previously appeared in a data breach as per haveibeenpwned.com and should never be used. Please choose something harder to guess.") end end end end.not_to change { User.count } end it "signs me up for the no-cost account" do visit("/signup") expect do with_real_pwned_password_check do fill_in("Email", with: "user@test.com") fill_in("Password", with: SecureRandom.hex(24)) click_on("Create account") expect(page).to have_content("Dashboard") end end.to change { User.count }.by(1) end it "logs in with a non-compromised password" do visit("/") vcr_turned_on do VCR.use_cassette("Login-with non compromised password") do with_real_pwned_password_check do user = create(:user) fill_in("Email", with: user.email) fill_in("Password", with: user.password) click_on("Login") expect(page).to have_selector("h1", text: "Dashboard") expect(page).to_not have_alert end end end end it "logs in with a compromised password and displays a warning" do visit("/") vcr_turned_on do VCR.use_cassette("Login-with a compromised password") do with_real_pwned_password_check do user = create(:user_with_compromised_password, username: nil) fill_in("Email", with: user.email) fill_in("Password", with: user.password) click_on("Login") expect(page).to have_selector("h1", text: "Dashboard") expect(page).to have_alert(text: "Your password has previously appeared in a data breach as per haveibeenpwned.com and should never be used. We strongly recommend you change your password everywhere you have used it.") end end end end end describe("when user is logged in") do before(:each) do @user = create(:user) login_as(@user) visit "/dashboard" fill_in_profile end it("logs me out") do expect(page).to have_disclosure @user.reload.display_name toggle_disclosure @user.display_name click_on "Logout" expect(page).to(have_content("Log in")) end end describe("when user is logged in and has a social provider") do before do with_real_pwned_password_check do login_as(create(:user_with_compromised_password, provider: :facebook)) end end it("doesn't show the old password field") do visit settings_password_path expect(page).to_not have_field("Old password") expect(page).to_not have_field("New password") expect(page).to have_field("Add password") end it "doesn't check whether the password is compromised or not" do expect(Pwned::Password).to_not receive(:new) visit("/dashboard") expect(page).to have_selector("h1", text: "Dashboard") expect(page).to_not have_alert end end describe "when a deleted user logs in" do it "does not undelete their account" do user = create(:user, deleted_at: 2.days.ago) visit("/") expect(page).to_not(have_selector("h1", text: "Welcome back to Gumroad.")) fill_in("Email", with: user.email) fill_in("Password", with: user.password) click_on("Login") expect(page).to_not have_selector("h1", text: "Welcome back to Gumroad.") expect(user.reload.deleted?).to be(true) end end describe "when a suspended for TOS user logs in" do let(:product) { create(:product, user:) } let(:admin_user) { create(:user) } let(:user) { create(:named_user) } before do user.flag_for_tos_violation(author_id: admin_user.id, product_id: product.id) user.suspend_for_tos_violation(author_id: admin_user.id) end it "renders to the products page" do visit login_path fill_in("Email", with: user.email) fill_in("Password", with: user.password) click_on("Login") wait_for_ajax expect(page).to have_link("Products") end end describe "Doorkeeper : resource_owner_from_credentials" do before do @owner = create(:user) @app = create(:oauth_application, owner: @owner) visit "/" stub_const("DOMAIN", URI.split(current_url)[2..3].join(":")) end it "provides an access token when using a users unconfirmed email" do client = OAuth2::Client.new(@app.uid, @app.secret, site: "http://" + DOMAIN) user = create(:user, username: nil, unconfirmed_email: "maxwell@gumroad.com") access_token = client.password.get_token("maxwell@gumroad.com", user.password) expect(access_token.token).not_to be_blank end it "provides an access token for a user's email and his/her password" do client = OAuth2::Client.new(@app.uid, @app.secret, site: "http://" + DOMAIN) user = create(:user, username: nil) access_token = client.password.get_token(user.email, user.password) expect(access_token.token).not_to be_blank end it "does not give an access token if the users credentials are invalid" do client = OAuth2::Client.new(@app.uid, @app.secret, site: "http://" + DOMAIN) user = create(:user, username: nil) expect { client.password.get_token(user.email, user.password + "invalid") }.to raise_error(OAuth2::Error) end it "provides an access token for a user's username and his/her password" do client = OAuth2::Client.new(@app.uid, @app.secret, site: "http://" + DOMAIN) user = create(:user, username: "maxwelle") access_token = client.password.get_token("maxwelle", user.password) expect(access_token.token).not_to be_blank end it "does not return an access token if the password is blank and a user does not exist" do client = OAuth2::Client.new(@app.uid, @app.secret, site: "http://" + DOMAIN) link = create(:product, user: create(:user)) create(:product_file, link_id: link.id, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/ScreenRecording.mov") create(:purchase_with_balance, link:, email: "user@testing.com") expect { client.password.get_token("user@testing.com", "") }.to raise_error(OAuth2::Error) end it "does not return an access token if the email is blank and a user does not exist" do client = OAuth2::Client.new(@app.uid, @app.secret, site: "http://" + DOMAIN) link = create(:product, user: create(:user)) create(:product_file, link_id: link.id, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/ScreenRecording.mov") create(:purchase_with_balance, link:, email: "user@testing.com") expect { client.password.get_token("", "123456") }.to raise_error(OAuth2::Error) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/oauth_applications_pages_spec.rb
spec/requests/oauth_applications_pages_spec.rb
# frozen_string_literal: true require("spec_helper") describe "OauthApplicationsPages", type: :system, js: true do context "On /settings/advanced page" do let(:user) { create(:named_user) } before do login_as user visit settings_advanced_path end it "creates an OAuth application with correct parameters" do expect do within_section "Applications", section_element: :section do fill_in("Application name", with: "test") fill_in("Redirect URI", with: "http://l.h:9292/callback") page.attach_file(file_fixture("test.jpg")) do click_on "Upload icon" end expect(page).to have_button("Upload icon") expect(page).to have_selector("img[src*='s3_utility/cdn_url_for_blob?key=#{ActiveStorage::Blob.last.key}']") click_button("Create application") end expect(page).to have_current_path(/\/oauth\/applications\/.*\/edit/) end.to change { OauthApplication.count }.by(1) OauthApplication.last.tap do |app| expect(app.name).to eq "test" expect(app.redirect_uri).to eq "http://l.h:9292/callback" expect(app.affiliate_basis_points).to eq nil expect(app.file.filename.to_s).to eq "test.jpg" expect(app.owner).to eq user end end it "does not allow adding an icon of invalid type" do within_section "Applications", section_element: :section do page.attach_file(file_fixture("disguised_html_script.png")) do click_on "Upload icon" end end expect(page).to have_alert(text: "Invalid file type.") end it "allows adding valid icon after trying an invalid one" do within_section "Applications", section_element: :section do page.attach_file(file_fixture("disguised_html_script.png")) do click_on "Upload icon" end end expect(page).to have_alert(text: "Invalid file type.") expect do within_section "Applications", section_element: :section do fill_in("Application name", with: "test") fill_in("Redirect URI", with: "http://l.h:9292/callback") page.attach_file(file_fixture("test.jpg")) do click_on "Upload icon" end expect(page).to have_button("Upload icon") expect(page).to have_selector("img[src*='s3_utility/cdn_url_for_blob?key=#{ActiveStorage::Blob.last.key}']") click_button("Create application") end expect(page).to have_current_path(/\/oauth\/applications\/.*\/edit/) end.to change { OauthApplication.count }.by(1) end end it "allows seller to generate an access token for their application without breaking '/settings/authorized_applications'" do logout application = create(:oauth_application_valid) login_as(application.owner) visit("/oauth/applications/#{application.external_id}/edit") click_on "Generate access token" wait_for_ajax visit settings_authorized_applications_path expect(page).to have_content("You've authorized the following applications to use your Gumroad account.") end it "generates tokens that do not have the mobile_api scope" do logout application = create(:oauth_application_valid) login_as(application.owner) visit("/oauth/applications/#{application.external_id}/edit") click_on "Generate access token" wait_for_ajax expect(page).to have_field("Access Token", with: application.access_tokens.last.token) expect(application.access_grants.count).to eq 1 expect(application.access_tokens.count).to eq 1 expect(application.access_tokens.last.scopes.to_a).to eq %w[edit_products view_sales mark_sales_as_shipped edit_sales revenue_share ifttt view_profile view_payouts] end it "doesn't list the application if there are no grants for it" do logout application = create(:oauth_application_valid) login_as(application.owner) allow(Doorkeeper::AccessGrant).to receive(:order).and_return(Doorkeeper::AccessGrant.where(id: 0)) visit settings_authorized_applications_path expect(page).to_not have_content(application.name) end it "correctly displays access grants and allows user to revoke access of authorized applications" do logout user = create(:user) login_as(user) app_names = [] 5.times do application = create(:oauth_application_valid) app_names << application.name Doorkeeper::AccessGrant.create!(application_id: application.id, resource_owner_id: user.id, redirect_uri: application.redirect_uri, expires_in: 1.day.from_now, scopes: Doorkeeper.configuration.public_scopes.join(" ")) Doorkeeper::AccessToken.create!(application_id: application.id, resource_owner_id: user.id) end visit settings_authorized_applications_path expect(page).to have_content("You've authorized the following applications to use your Gumroad account.") app_names.each { |app_name| expect(page).to(have_content(app_name)) } within_row app_names.first do click_on "Revoke access" end within_modal "Revoke access" do expect(page).to have_text("Are you sure you want to revoke access to #{app_names.first}?") click_on "Yes, revoke access" end expect(page).to have_current_path(settings_authorized_applications_path) expect(page).to(have_alert(text: "Authorized application revoked")) expect(page).not_to(have_content(app_names.first)) app_names.drop(1).each { |app_name| expect(page).to(have_content(app_name)) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/commissions_spec.rb
spec/requests/commissions_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Commissions", type: :system, js: true do let(:seller) { create(:user, :eligible_for_service_products) } let(:commission1) { create(:product, user: seller, name: "Commission 1", native_type: Link::NATIVE_TYPE_COMMISSION, price_cents: 200) } let(:commission2) { create(:product, user: seller, name: "Commission 2", native_type: Link::NATIVE_TYPE_COMMISSION, price_cents: 1000) } let(:product) { create(:product, user: seller, name: "Product", price_cents: 100) } before do create(:offer_code, user: seller, code: "commission", amount_cents: 500, products: [commission2]) end it "shows notices explaining the commission" do visit commission1.long_url expect(page).to have_status(text: "Secure your order with a 50% deposit today; the remaining balance will be charged upon completion.") click_on "I want this!" expect(page).to have_text("Payment today US$1", normalize_ws: true) expect(page).to have_text("Payment after completion US$1", normalize_ws: true) visit "#{commission2.long_url}/commission" click_on "I want this!" expect(page).to have_text("Payment today US$3.50", normalize_ws: true) expect(page).to have_text("Payment after completion US$3.50", normalize_ws: true) visit product.long_url click_on "I want this!" expect(page).to have_text("Payment today US$4.50", normalize_ws: true) expect(page).to have_text("Payment after completion US$3.50", normalize_ws: true) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/help_center_spec.rb
spec/requests/help_center_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Help Center", type: :system, js: true do let(:seller) { create(:named_seller) } before do allow(GlobalConfig).to receive(:get).with("RECAPTCHA_LOGIN_SITE_KEY") allow(GlobalConfig).to receive(:get).with("ENTERPRISE_RECAPTCHA_API_KEY") allow(GlobalConfig).to receive(:get).with("HELPER_WIDGET_SECRET").and_return("test_secret") allow(GlobalConfig).to receive(:get).with("HELPER_WIDGET_HOST").and_return("https://helper.test") stub_request(:post, "https://helper.test/api/widget/session") .to_return( status: 200, body: { token: "mock_helper_token" }.to_json, headers: { "Content-Type" => "application/json" } ) stub_request(:post, "https://helper.test/api/chat/conversation") .to_return( status: 200, body: { conversationSlug: "test-conversation-123" }.to_json, headers: { "Content-Type" => "application/json" } ) stub_request(:post, "https://helper.test/api/chat/conversation/test-conversation-123/message") .to_return( status: 200, body: { success: true }.to_json, headers: { "Content-Type" => "application/json" } ) end describe "the user is unauthenticated" do it "shows the contact support button and support modal" do visit "/help" expect(page).to have_button("Contact support") expect(page).to have_link("Report a bug", href: "https://github.com/antiwork/gumroad/issues/new") click_on "Contact support" expect(page).to have_content("How can we help you today?") expect(page).to have_field("Your email address") expect(page).to have_field("Subject") expect(page).to have_field("Tell us about your issue or question...") end it "opens the new ticket modal when the new ticket parameter is present" do visit "/help?new_ticket=true" within_modal "How can we help you today?" do expect(page).to have_field("Your email address") expect(page).to have_field("Subject") expect(page).to have_field("Tell us about your issue or question...") end end it "successfully submits a support ticket form" do visit "/help" click_on "Contact support" fill_in "Your email address", with: "test@example.com" fill_in "Subject", with: "Need help with my account" fill_in "Tell us about your issue or question...", with: "I'm having trouble accessing my dashboard and need assistance." click_on "Send message" expect(page).to have_content("Your support ticket has been created successfully!") expect(page).not_to have_content("How can we help you today?") end end describe "the user is authenticated with Helper session" do before do sign_in seller end it "shows the new ticket button and report a bug link" do visit "/help" expect(page).to have_button("New ticket") expect(page).to have_link("Report a bug", href: "https://github.com/antiwork/gumroad/issues/new") end it "opens the new ticket modal when the new ticket parameter is present" do visit "/help?new_ticket=true" within_modal "How can we help you today?" do expect(page).not_to have_field("Your email address") expect(page).to have_field("Subject") expect(page).to have_field("Tell us about your issue or question...") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/affiliates_signup_form_spec.rb
spec/requests/affiliates_signup_form_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Affiliate Signup Form", type: :system, js: true do let(:seller) { create(:named_seller) } include_context "with switching account to user as admin for seller" context "when no published products are found" do it "displays the products not found message" do visit affiliates_path expect(page).to have_tab_button("Affiliate Signup Form", open: true) expect(page).to have_text("You need a published product to add affiliates.") end end context "when using the old form page" do it "redirects to the new affiliate signup form" do visit "/affiliate_requests/onboarding_form" expect(page).to have_current_path("/affiliates/onboarding") expect(page).to have_tab_button("Affiliate Signup Form", open: true) expect(page).to have_text("You need a published product to add affiliates.") end end context "when published products exist" do let!(:product_one) { create(:product, name: "Product 1", user: seller) } let!(:product_two) { create(:product, name: "Product 2", user: seller) } let!(:product_three) { create(:product, name: "Product 3", user: seller, purchase_disabled_at: DateTime.current) } let!(:product_four) { create(:product, name: "Product 4", user: seller) } let!(:archived_product) { create(:product, name: "Archived product", user: seller, archived: true) } let!(:not_enabled_archived_product) { create(:product, user: seller, name: "Not selected archived product", archived: true) } let!(:collab_product) { create(:product, :is_collab, name: "Collab product", user: seller) } let!(:self_service_collab_product) { create(:product, :is_collab, name: "Self service collab product", user: seller) } before do create(:self_service_affiliate_product, enabled: true, seller:, product: archived_product) create(:self_service_affiliate_product, enabled: false, seller:, product: self_service_collab_product) # enabled prior to conversion to a collab product end it "shows published, eligible products and allows enabling and disabling them" do visit "/affiliates/onboarding" # react route table_label = "Enable specific products" name_label = "Product" within_section "Affiliate link", section_element: :section do expect(page).to have_field("Your affiliate link", with: custom_domain_new_affiliate_request_url(host: seller.subdomain_with_protocol), readonly: true) expect(page).to_not have_alert(text: "You must enable and set up the commission for at least one product before sharing your affiliate link.") end within_table table_label do within(:table_row, { name_label => "Archived product" }) do uncheck "Enable product" end end within_section "Affiliate link", section_element: :section do expect(page).to have_field("Your affiliate link", with: custom_domain_new_affiliate_request_url(host: seller.subdomain_with_protocol), readonly: true, disabled: true) expect(page).to have_alert(text: "You must enable and set up the commission for at least one product before sharing your affiliate link.") end within_table table_label do within(:table_row, { name_label => "Archived product" }) do check "Enable product" end end within_table table_label do within(:table_row, { name_label => "Product 1" }) do expect(page).to have_field("Commission", disabled: true, with: nil) expect(page).to have_field("https://link.com", disabled: true, with: nil) check "Enable product" fill_in("Commission", with: "35") uncheck "Enable product" end within(:table_row, { name_label => "Product 2" }) do expect(page).to have_field("Commission", disabled: true, with: nil) expect(page).to have_field("https://link.com", disabled: true, with: nil) check "Enable product" fill_in("Commission", with: "20") end within(:table_row, { name_label => "Product 4" }) do expect(page).to have_field("Commission", disabled: true, with: nil) expect(page).to have_field("https://link.com", disabled: true, with: nil) check "Enable product" fill_in("Commission", with: "10") fill_in("https://link.com", with: "hello") end expect(page).to have_table_row({ name_label => archived_product.name }) expect(page).not_to have_table_row({ name_label => not_enabled_archived_product.name }) end # excludes ineligible products expect(page).not_to have_content collab_product.name expect(page).not_to have_content self_service_collab_product.name click_on "Save changes" expect(page).to have_alert(text: "There are some errors on the page. Please fix them and try again.") within_table table_label do within(:table_row, { name_label => "Product 4" }) do fill_in("https://link.com", with: "https://example.com") end end click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") # Reload the page and verify that the changes actually persisted visit "/affiliates/onboarding" # react route within_table table_label do within(:table_row, { name_label => "Product 2" }) do expect(page).to have_field("Commission", with: "20") expect(page).to have_field("https://link.com", with: nil) end within(:table_row, { name_label => "Product 4" }) do expect(page).to have_field("Commission", with: "10") expect(page).to have_field("https://link.com", with: "https://example.com") end within(:table_row, { name_label => "Product 1" }) do expect(page).to have_field("Commission", disabled: true, with: "35") expect(page).to have_field("https://link.com", disabled: true, with: nil) end end end it "allows disabling the global affiliate program" do visit "/affiliates/onboarding" within_section "Gumroad Affiliate Program", section_element: :section do expect(page).to have_text("Being part of Gumroad Affiliate Program enables other creators to share your products in exchange for a 10% commission.") find_field("Opt out of the Gumroad Affiliate Program", checked: false).check end click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.disable_global_affiliate).to eq(true) refresh find_field("Opt out of the Gumroad Affiliate Program", checked: true).uncheck click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.disable_global_affiliate).to eq(false) end end context "creating an affiliate from the onboarding form" do let!(:product) { create(:product, name: "Test Product", user: seller) } it "creates the first affiliate, initiating the form from the onboarding page" do affiliate_user = create(:named_user) expect do visit "/affiliates/onboarding" # react route wait_for_ajax click_on("Add affiliate") expect(page).to have_text("New Affiliate") fill_in("Email", with: affiliate_user.email) within :table_row, { "Product" => "Test Product" } do check "Enable product" fill_in("Commission", with: "10") fill_in("https://link.com", with: "http://google.com/") end click_on("Add affiliate") within(:table_row, { "Name" => affiliate_user.name, "Products" => product.name, "Commission" => "10%" }) do expect(page).to have_command("Edit") expect(page).to have_command("Delete") end end.to change { seller.direct_affiliates.count }.by(1) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/oauth_authorizations_spec.rb
spec/requests/oauth_authorizations_spec.rb
# frozen_string_literal: true require("spec_helper") describe Oauth::AuthorizationsController, type: :system do before :each do visit "/" stub_const("DOMAIN", "gumroad.com") stub_const("VALID_REQUEST_HOSTS", ["gumroad.com"]) @user = create(:named_user) @owner = create(:named_user) @app = create(:oauth_application, owner: @owner, redirect_uri: "http://" + DOMAIN + "/", confidential: false) @internal_app = create(:oauth_application, owner: @owner, redirect_uri: "http://" + DOMAIN + "/", confidential: false, scopes: Doorkeeper.configuration.scopes.to_a - Doorkeeper.configuration.default_scopes.to_a) login_as @user allow(Rails.env).to receive(:test?).and_return(false) end it "does not allow unauthorized apps to ask for mobile api (Production)" do expect(Rails.env).to receive(:production?).and_return(true).at_least(1).times visit "/oauth/authorize?response_type=code&client_id=#{@app.uid}&redirect_uri=#{Addressable::URI.escape(@app.redirect_uri)}&scope=mobile_api" expect(page).to have_content("The requested scope is invalid") expect(page).not_to have_content("Mobile API") end it "allows applications to access the mobile_api if they are allowed to (Production)" do stub_const("OauthApplication::MOBILE_API_OAUTH_APPLICATION_UID", @internal_app.uid) expect(Rails.env).to receive(:production?).and_return(true).at_least(1).times visit "/oauth/authorize?response_type=code&client_id=#{@internal_app.uid}&redirect_uri=#{Addressable::URI.escape(@internal_app.redirect_uri)}&scope=edit_products+mobile_api" expect(page).to have_content("Authorize #{@internal_app.name} to use your account?") expect(page).to have_content("Create new products and edit your existing products.") expect(page).to have_content("Mobile API") click_button "Authorize" expect(@internal_app.access_grants.count).to eq 1 expect(@internal_app.access_grants.last.scopes.to_s).to eq "edit_products mobile_api" end it "allows applications to access the mobile_api if they are allowed to (Staging)" do stub_const("OauthApplication::MOBILE_API_OAUTH_APPLICATION_UID", @internal_app.uid) expect(Rails.env).to receive(:staging?).and_return(true).at_least(1).times visit "/oauth/authorize?response_type=code&client_id=#{@internal_app.uid}&redirect_uri=#{Addressable::URI.escape(@internal_app.redirect_uri)}&scope=edit_products+mobile_api" expect(page).to have_content("Authorize #{@internal_app.name} to use your account?") expect(page).to have_content("Create new products and edit your existing products.") expect(page).to have_content("Mobile API") click_button "Authorize" expect(@internal_app.access_grants.count).to eq 1 expect(@internal_app.access_grants.last.scopes.to_s).to eq "edit_products mobile_api" end it "handles the situation where there is a nil oauth application in the pre_auth" do visit "/oauth/authorize?response_type=code&client_id=#{@app.uid + 'invalid'}&redirect_uri=#{Addressable::URI.escape(@app.redirect_uri)}&scope=mobile_api" expect(page).to have_content("Client authentication failed due to unknown client") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/main_navigation_spec.rb
spec/requests/main_navigation_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Main Navigation", type: :system, js: true do context "with logged in user" do let(:user) { create(:user, name: "Gum") } before do login_as user end it "renders all menu links" do visit library_path within "nav[aria-label='Main']" do expect(page).to have_link("Workflows") expect(page).to have_link("Sales") expect(page).to have_link("Products") expect(page).to have_link("Emails") expect(page).to have_link("Analytics") expect(page).to have_link("Payouts") expect(page).to have_link("Discover") expect(page).to have_link("Library") expect(page).to have_link("Settings") expect(page).to have_link("Collaborators") expect(page).not_to have_link("Community") toggle_disclosure("Gum") within "div[role='menu']" do expect(page).to_not have_text(user.display_name) expect(page).to have_menuitem("Profile") expect(page).to have_menuitem("Affiliates") expect(page).to have_menuitem("Logout") end end end context "Community link" do it "renders the Community link if the logged in seller has an active community" do Feature.activate_user(:communities, user) product = create(:product, user:, community_chat_enabled: true) create(:community, seller: user, resource: product) visit library_path within "nav[aria-label='Main']" do expect(page).to have_link("Community", href: community_path) end end it "renders the Community link if the logged in user has an access to a community" do seller = create(:user) Feature.activate_user(:communities, seller) product = create(:product, user: seller, community_chat_enabled: true) create(:community, resource: product, seller:) create(:purchase, seller:, link: product, purchaser: user) visit library_path within "nav[aria-label='Main']" do expect(page).to have_link("Community", href: community_path) end end it "renders the Community link if the logged in user is a seller but has no active communities" do Feature.activate_user(:communities, user) create(:product, user:) visit library_path within "nav[aria-label='Main']" do expect(page).not_to have_link("Community", href: community_path) end end end context "with team membership" do let(:seller) { create(:user, name: "Joe") } before do create(:team_membership, user:, seller:) end it "renders memberships" do visit library_path within "nav[aria-label='Main']" do toggle_disclosure("Gum") within "div[role='menu']" do expect(page).to have_text(user.display_name) expect(page).to have_text(seller.display_name) 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/requests/admin_nav_mobile_spec.rb
spec/requests/admin_nav_mobile_spec.rb
# frozen_string_literal: true require "spec_helper" describe("Admin - Nav - Mobile", :js, :mobile_view, type: :system) do let(:admin) { create(:admin_user) } before do login_as admin end it "auto closes the menu when navigating to a different page" do visit admin_suspend_users_path click_on "Toggle navigation" expect(page).to have_link("Suspend users") expect(page).to have_link("Block emails") click_on "Block emails" expect(page).to_not have_link("Suspend users") expect(page).to_not have_link("Block emails") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/download_page/rich_text_editor_spec.rb
spec/requests/download_page/rich_text_editor_spec.rb
# frozen_string_literal: true require("spec_helper") require "shared_examples/file_group_download_all" describe("Download Page – Rich Text Editor Content", type: :system, js: true) do def embed_files_for_product(product:, files:) product_rich_content = product.alive_rich_contents.first_or_initialize description = [] files.each do |file| description << { "type" => "fileEmbed", "attrs" => { "id" => file.external_id, "uid" => SecureRandom.uuid } } end product_rich_content.description = description product_rich_content.save! end let(:logged_in_user) { @buyer } before do @user = create(:user) @buyer = create(:user) login_as(logged_in_user) end context "digital product" do before do @product = create(:product, user: @user) @purchase = create(:purchase, link: @product, purchaser: @buyer) @url_redirect = create(:url_redirect, link: @product, purchase: @purchase) @video_file = create(:streamable_video, link: @product, display_name: "Video file", description: "Video description") @audio_file = create(:listenable_audio, :analyze, link: @product, display_name: "Audio file", description: "Audio description") @pdf_file = create(:readable_document, link: @product, display_name: "PDF file", size: 1.megabyte) files = [@video_file, @audio_file, @pdf_file] @product.product_files = files embed_files_for_product(product: @product, files:) end it "triggers app bridge messages for file embeds in iOS" do visit("/d/#{@url_redirect.token}?display=mobile_app") page.execute_script <<~JS window._messages = []; window.webkit = { messageHandlers: { jsMessage: { postMessage: (message) => { window._messages.push(message); } } } }; JS within(find_embed(name: "Video file")) do click_on "Download" expect(page.evaluate_script("window._messages")).to eq( [ { type: "click", payload: { resourceId: @video_file.external_id, isDownload: true, isPost: false, type: nil, isPlaying: nil, resumeAt: nil, contentLength: nil } }.as_json ] ) click_on "Watch" expect(page.evaluate_script("window._messages[1]")).to eq( { type: "click", payload: { resourceId: @video_file.external_id, isDownload: false, isPost: false, type: nil, isPlaying: nil, resumeAt: nil, contentLength: nil } }.as_json ) expect(page).not_to have_selector("[aria-label='Video Player']") end within(find_embed(name: "Audio file")) do click_on "Download" expect(page.evaluate_script("window._messages[2]")).to eq( { type: "click", payload: { resourceId: @audio_file.external_id, isDownload: true, isPost: false, type: nil, isPlaying: nil, resumeAt: nil, contentLength: nil } }.as_json ) click_on "Play" expect(page.evaluate_script("window._messages[3]")).to eq( { type: "click", payload: { resourceId: @audio_file.external_id, isDownload: false, isPost: false, type: "audio", isPlaying: "false", resumeAt: "0", contentLength: "46" } }.as_json ) expect(page).not_to have_button("Close") end within(find_embed(name: "PDF file")) do click_on "Download" expect(page.evaluate_script("window._messages[4]")).to eq( { type: "click", payload: { resourceId: @pdf_file.external_id, isDownload: true, isPost: false, type: nil, isPlaying: nil, resumeAt: nil, contentLength: nil } }.as_json ) click_on "Read" expect(page.evaluate_script("window._messages[5]")).to eq( { type: "click", payload: { resourceId: @pdf_file.external_id, isDownload: false, isPost: false, type: nil, isPlaying: nil, resumeAt: nil, contentLength: nil } }.as_json ) end expect(page.evaluate_script("window._messages.length")).to eq(6) end it "triggers app bridge messages for file embeds in Android" do visit("/d/#{@url_redirect.token}?display=mobile_app") page.execute_script <<~JS window._messages = []; window.CustomJavaScriptInterface = { onFileClickedEvent: (resourceId, isDownload) => window._messages.push({ resourceId, isDownload }) }; JS within(find_embed(name: "Video file")) do click_on "Download" expect(page.evaluate_script("window._messages")).to eq( [ { resourceId: @video_file.external_id, isDownload: true }.as_json ] ) click_on "Watch" expect(page.evaluate_script("window._messages[1]")).to eq( { resourceId: @video_file.external_id, isDownload: false }.as_json ) expect(page).not_to have_selector("[aria-label='Video Player']") end within(find_embed(name: "Audio file")) do click_on "Download" expect(page.evaluate_script("window._messages[2]")).to eq( { resourceId: @audio_file.external_id, isDownload: true }.as_json ) click_on "Play" expect(page.evaluate_script("window._messages[3]")).to eq( { resourceId: @audio_file.external_id, isDownload: false }.as_json ) expect(page).not_to have_button("Close") end within(find_embed(name: "PDF file")) do click_on "Download" expect(page.evaluate_script("window._messages[4]")).to eq( { resourceId: @pdf_file.external_id, isDownload: true }.as_json ) click_on "Read" expect(page.evaluate_script("window._messages[5]")).to eq( { resourceId: @pdf_file.external_id, isDownload: false }.as_json ) end expect(page.evaluate_script("window._messages.length")).to eq(6) end it "renders the customized download page for the purpose of embedding inside webview in the mobile apps" do visit("/d/#{@url_redirect.token}?display=mobile_app") within(find_embed(name: "Audio file")) do expect(page).to have_button("Play") expect(page).to have_text("MP3") expect(page).to have_text("0m 46s") expect(page).to have_text("Audio description") expect(page).to_not have_text("Processing...") expect(page).to_not have_button("Pause") expect(page).to_not have_text(" left") expect(page).to_not have_selector("meter") page.execute_script %Q( window.dispatchEvent(new CustomEvent("mobile_app_audio_player_info", { detail: { fileId: "#{@audio_file.external_id}", isPlaying: true, latestMediaLocation: "24" } })); ).squish expect(page).to have_button("Pause") expect(page).to have_text("0m 22s left") expect(page).to_not have_text("Processing...") expect(page).to have_selector("meter[value*='0.52']") end @audio_file.update!(duration: nil, description: nil) visit("/d/#{@url_redirect.token}?display=mobile_app") within(find_embed(name: "Audio file")) do expect(page).to have_button("Play", disabled: true) expect(page).to_not have_text("MP3") expect(page).to_not have_text("0m 46s") expect(page).to_not have_text("Audio description") expect(page).to have_text("Processing...") @audio_file.update!(duration: 46) expect(page).to have_text("0m 46s", wait: 10) expect(page).to have_text("MP3") expect(page).to_not have_text("Processing...") expect(page).to have_button("Play") end end it "allows sending a readable document to Kindle" do visit("/d/#{@url_redirect.token}") expect do expect do within(find_embed(name: "PDF file")) do expect(page).to have_text("PDF1.0 MB") click_on "Send to Kindle" fill_in "e7@kindle.com", with: "example@kindle.com" click_on "Send" end expect(page).to have_alert(text: "It's been sent to your Kindle.") end.to have_enqueued_mail(CustomerMailer, :send_to_kindle) end.to change(ConsumptionEvent, :count).by(1) event = ConsumptionEvent.last expect(event.event_type).to eq(ConsumptionEvent::EVENT_TYPE_READ) expect(event.purchase_id).to eq(@purchase.id) expect(event.link_id).to eq(@product.id) expect(event.product_file_id).to eq(@pdf_file.id) end it "shows file embeds if present" do visit("/d/#{@url_redirect.token}") within(find_embed(name: "Video file")) do expect(page).to have_link("Download") expect(page).to have_button("Watch") expect(page).to have_text("Video description") end within(find_embed(name: "Audio file")) do expect(page).to have_link("Download") expect(page).to have_button("Play") expect(page).to have_text("Audio description") end within(find_embed(name: "PDF file")) do expect(page).to have_link("Download") expect(page).to have_link("Read", href: url_redirect_read_for_product_file_path(@url_redirect.token, @pdf_file.external_id)) end end it "shows collapsed video thumbnails" do product_rich_content = @product.alive_rich_contents.first product_rich_content.update!( description: product_rich_content.description.map do |node| node["attrs"]["collapsed"] = true if node["attrs"]["id"] == @video_file.external_id node end ) visit("/d/#{@url_redirect.token}") within(find_embed(name: "Video file")) do expect(page).not_to have_selector("figure") expect(page).to have_button("Play") click_on "Play" expect(page).to have_selector("[aria-label='Video Player']") end end context "when the logged in user is seller and the embedded videos are not yet transcoded" do let(:logged_in_user) { @user } before do @purchase.update!(purchaser: @user) end it "shows video transcoding notice modal" do visit("/d/#{@url_redirect.token}") expect(page).to have_modal("Your video is being transcoded.") within_modal("Your video is being transcoded.") do expect(page).to have_text("Until then, you and your future customers may experience some viewing issues. You'll get an email once it's done.", normalize_ws: true) click_on "Close" end expect(page).to_not have_modal("Your video is being transcoded.") end end it "displays embedded code blocks and allows copying them" do product_rich_content = @product.alive_rich_contents.first product_rich_content.update!( description: product_rich_content.description.concat( [ { "type" => "codeBlock", "attrs" => { "language" => nil }, "content" => [{ "type" => "text", "text" => "const hello = \"world\";" }] }, { "type" => "codeBlock", "attrs" => { "language" => "ruby" }, "content" => [{ "type" => "text", "text" => "puts 'Hello, world!'" }] }, { "type" => "codeBlock", "attrs" => { "language" => "typescript" }, "content" => [{ "type" => "text", "text" => "let greeting: string = 'Hello, world!';" }] } ] ) ) visit("/d/#{@url_redirect.token}") expect(page).to have_text("const hello = \"world\";") expect(page).to have_text("puts 'Hello, world!'") expect(page).to have_text("let greeting: string = 'Hello, world!';") find("pre", text: "const hello = \"world\";").hover within find("pre", text: "const hello = \"world\";") do click_on "Copy" expect(page).to have_text("Copied!") end find("pre", text: "puts 'Hello, world!'").hover within find("pre", text: "puts 'Hello, world!'") do click_on "Copy" expect(page).to have_text("Copied!") end find("pre", text: "let greeting: string = 'Hello, world!';").hover within find("pre", text: "let greeting: string = 'Hello, world!';") do click_on "Copy" expect(page).to have_text("Copied!") end end context "when video file is marked as stream only" do before do @video_file.update!(stream_only: true) end it "doesn't allow the video files to be downloaded" do visit("/d/#{@url_redirect.token}") within(find_embed(name: "Video file")) do expect(page).to_not have_link("Download") expect(page).to have_button("Watch") end within(find_embed(name: "Audio file")) do expect(page).to have_link("Download") expect(page).to have_button("Play") end within(find_embed(name: "PDF file")) do expect(page).to have_link("Download") expect(page).to have_link("Read", href: url_redirect_read_for_product_file_path(@url_redirect.token, @pdf_file.external_id)) end end end it "shows inline preview for video file embeds" do subtitle_file = create(:subtitle_file, product_file: @video_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/6505430906858/ba3afa0e200b414caa6fe8b0be05ae20/original/sample.srt") subtitle_blob = ActiveStorage::Blob.create_and_upload!(io: Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "sample.srt"), "text/plain"), filename: "sample.srt") allow_any_instance_of(ProductFile).to receive(:signed_download_url_for_s3_key_and_filename).with(subtitle_file.s3_key, subtitle_file.s3_filename, is_video: true).and_return(subtitle_blob.url) @video_file.thumbnail.attach(io: File.open(Rails.root.join("spec", "support", "fixtures", "autumn-leaves-1280x720.jpeg")), filename: "autumn-leaves-1280x720.jpeg") video_blob = ActiveStorage::Blob.create_and_upload!(io: Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "ScreenRecording.mov"), "video/quicktime"), filename: "ScreenRecording.mov", key: "test/ScreenRecording.mov") allow_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(video_blob.url) allow_any_instance_of(UrlRedirect).to receive(:hls_playlist_or_smil_xml_path).and_return(video_blob.url) visit("/d/#{@url_redirect.token}") wait_for_ajax within(find_embed(name: "Video file")) do expect(page).to have_selector("img[src='#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{@video_file.thumbnail_variant.key}']") click_on "Watch" expect(page).to_not have_button("Watch") expect(page).to_not have_selector("img[src='#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{@video_file.thumbnail_variant.key}']") expect(page).to have_selector("[aria-label='Video Player']") expect(page).to have_button("Pause") expect(page).to have_button("Rewind 10 Seconds") expect(page).to have_button("Closed Captions") end end it "allow watching the video again if it encounters an error while fetching its media URLs" do allow_any_instance_of(UrlRedirectsController).to receive(:media_urls).and_raise(ActionController::BadRequest) visit("/d/#{@url_redirect.token}") within(find_embed(name: "Video file")) do click_on "Watch" end expect(page).to have_alert(text: "Sorry, something went wrong. Please try again.") within(find_embed(name: "Video file")) do expect(page).to have_button("Watch") expect(page).to_not have_selector("[aria-label='Video Player']") end end it "shows inline preview for embedded media via URL" do product_rich_content = @product.alive_rich_contents.first product_rich_content.update!(description: product_rich_content.description << { "type" => "mediaEmbed", "attrs" => { "url" => "https://www.youtube.com/watch?v=YE7VzlLtp-4", "html" => "<iframe src=\"//cdn.iframe.ly/api/iframe?url=https%3A%2F%2Fyoutu.be%2FYE7VzlLtp-4&key=31708e31359468f73bc5b03e9dcab7da\" style=\"top: 0; left: 0; width: 100%; height: 100%; position: absolute; border: 0;\" allowfullscreen scrolling=\"no\" allow=\"accelerometer *; clipboard-write *; encrypted-media *; gyroscope *; picture-in-picture *; web-share *;\"></iframe>", "title" => "Big Buck Bunny" } }) visit("/d/#{@url_redirect.token}") within find_embed(name: "Big Buck Bunny") do expect(page).to have_link("https://www.youtube.com/watch?v=YE7VzlLtp-4") expect(page).to_not have_button("Remove") expect(page).to_not have_link("Download") expect(find("iframe")[:src]).to include "iframe.ly/api/iframe?url=#{CGI.escape("https://youtu.be/YE7VzlLtp-4")}" end end context "when the product is a rental" do before do @url_redirect.update!(is_rental: true) end it "doesn't allow the video files to be downloaded" do visit("/d/#{@url_redirect.token}") within(find_embed(name: "Video file")) do expect(page).to_not have_link("Download") expect(page).to have_button("Watch") end within(find_embed(name: "Audio file")) do expect(page).to have_link("Download") expect(page).to have_button("Play") end within(find_embed(name: "PDF file")) do expect(page).to have_link("Download") expect(page).to have_link("Read", href: url_redirect_read_for_product_file_path(@url_redirect.token, @pdf_file.external_id)) end end end context "when an audio file embed exists" do before do allow_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(@audio_file.url) end it "allows playing the content in an audio player" do visit("/d/#{@url_redirect.token}") # It does not show consumption progress if not started listening expect(page).to_not have_selector("[role='progressbar']") expect(page).to have_button("Play") # It does not show the audio player by default expect(page).to_not have_button("Rewind15") click_on "Play" expect(page).to have_selector("[aria-label='Progress']", text: "00:01") expect(page).to have_button("Close") expect(page).to have_button("Rewind15") click_on "Pause" expect(page).to have_button("Play") expect(page).to_not have_button("Pause") # Skip and rewind progress_text = find("[aria-label='Progress']").text progress_seconds = progress_text[3..5].to_i click_on "Skip30" click_on "Rewind15" expect(page).to have_selector("[aria-label='Progress']", text: "00:#{(progress_seconds + 15).to_s.rjust(2, "0")}") click_on "Rewind15" expect(page).to have_selector("[aria-label='Progress']", text: progress_text) # Close audio player click_on "Close" expect(page).to_not have_button("Rewind15") end it "correctly updates consumption and playback progress" do media_location = create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @purchase.id, product_file_id: @audio_file.id, product_id: @product.id, location: 10) visit("/d/#{@url_redirect.token}") expect(page).to have_selector("[role='progressbar'][aria-valuenow='#{(1000.0 / 46).round(2)}']") click_on "Play" expect(page).to have_selector("[aria-label='Progress']", text: "00:10") expect(page).to have_selector("[aria-label='Progress']", text: "00:12") click_on "Pause" media_location.update!(location: 46) visit("/d/#{@url_redirect.token}") expect(page).to have_selector("[role='progressbar'][aria-valuenow='100']") # Resumes listening from the beginning click_on "Play again" expect(page).to have_selector("[aria-label='Progress']", text: "00:00") expect(page).to have_selector("[aria-label='Progress']", text: "00:01") end end context "when product has rich content" do before do product_rich_content = @product.alive_rich_contents.first product_rich_content.update!(description: product_rich_content.description << { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Product-level content" }] }) end context "when accessing the download page for a purchased variant" do before do category = create(:variant_category, link: @product, title: "Versions") version = create(:variant, variant_category: category, name: "Version 1") create(:rich_content, entity: version, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is Version 1 content", "type" => "text" }] }]) @purchase = create(:purchase, link: @product, purchaser: @buyer) @purchase.variant_attributes = [version] @url_redirect = create(:url_redirect, link: @product, purchase: @purchase) end it "shows the variant-level rich content" do visit("/d/#{@url_redirect.token}") expect(page).to have_text("#{@product.name} - Version 1") expect(page).to have_text("This is Version 1 content") expect(page).to_not have_text("Product-level content") end end context "when accessing the download page for a purchased variant belonging to a product having 'Use the same content for all versions' checkbox checked" do before do @product.update!(has_same_rich_content_for_all_variants: true) category = create(:variant_category, link: @product, title: "Versions") version1 = create(:variant, variant_category: category, name: "Version 1") create(:variant, variant_category: category, name: "Version 2") @purchase = create(:purchase, link: @product, purchaser: @buyer) @purchase.variant_attributes = [version1] @url_redirect = create(:url_redirect, link: @product, purchase: @purchase) end it "shows the product-level rich content" do visit("/d/#{@url_redirect.token}") expect(page).to have_text("#{@product.name} - Version 1") expect(page).to have_embed(name: @video_file.display_name) expect(page).to have_embed(name: @audio_file.display_name) expect(page).to have_embed(name: @pdf_file.display_name) expect(page).to have_text("Product-level content") end end it "shows the product-level content when accessing the download page for a purchased product having no variants" do visit("/d/#{@url_redirect.token}") expect(page).to have_text("#{@product.name}") expect(page).to have_embed(name: @video_file.display_name) expect(page).to have_embed(name: @audio_file.display_name) expect(page).to have_embed(name: @pdf_file.display_name) expect(page).to have_text("Product-level content") expect(page).to have_disclosure_button("Open in app") end end it "supports pages" do # When there's just one untitled page, it doesn't show table of contents expect(@product.alive_rich_contents.count).to eq(1) product_rich_content = @product.alive_rich_contents.first product_rich_content.update!(description: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Page 1 content" }] }]) visit("/d/#{@url_redirect.token}") expect(page).to_not have_tablist("Table of Contents") expect(page).to_not have_button("Next") expect(page).to have_text("Page 1 content") # When there are multiple pages, it shows table of contents product_rich_content.update!(title: "Page 1", position: 0) create(:rich_content, entity: @product, title: "Page 2", position: 1, description: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Page 2 content" }] }]) refresh expect(page).to have_tablist("Table of Contents") expect(page).to have_tab_button("Page 1", open: true) expect(page).to have_text("Page 1 content") expect(page).to have_tab_button("Page 2", open: false) expect(page).to have_button("Previous", disabled: true) expect(page).to have_button("Next", disabled: false) select_tab("Page 2") expect(page).to have_tab_button("Page 2", open: true) expect(page).to have_text("Page 2 content") expect(page).to have_button("Previous", disabled: false) expect(page).to have_button("Next", disabled: true) click_on "Previous" expect(page).to have_tab_button("Page 1", open: true) expect(page).to have_text("Page 1 content") expect(page).to have_button("Previous", disabled: true) expect(page).to have_button("Next", disabled: false) click_on "Next" expect(page).to have_tab_button("Page 2", open: true) expect(page).to have_text("Page 2 content") expect(page).to have_button("Previous", disabled: false) expect(page).to have_button("Next", disabled: true) end it "replaces the `__sale_info__` placeholder query parameter in links and buttons with the appropriate query parameters" do product_rich_content = @product.alive_rich_contents.first product_rich_content.update!(description: [ { "type" => "paragraph", "content" => [{ "text" => "Link 1", "type" => "text", "marks" => [{ "type" => "link", "attrs" => { "rel" => "noopener noreferrer nofollow", "href" => "https://example.com?__sale_info__", "class" => nil, "target" => "_blank" } }] }] }, { "type" => "paragraph", "content" => [{ "text" => "Link 2 with custom query parameters", "type" => "text", "marks" => [{ "type" => "link", "attrs" => { "rel" => "noopener noreferrer nofollow", "href" => "https://example.com/?test=123&__sale_info__", "class" => nil, "target" => "_blank" } }] }] }, { "type" => "paragraph", "content" => [{ "type" => "tiptap-link", "attrs" => { "href" => "https://example.com/?test=123&__sale_info__" }, "content" => [{ "text" => "Link 3", "type" => "text" }] }] }, { "type" => "button", "attrs" => { "href" => "https://example.com/?test=123&__sale_info__" }, "content" => [{ "text" => "Button with custom query parameters", "type" => "text" }] }, ]) visit("/d/#{@url_redirect.token}") sale_info_query_params = "sale_id=#{CGI.escape(@purchase.external_id)}&product_id=#{CGI.escape(@product.external_id)}&product_permalink=#{CGI.escape(@product.unique_permalink)}" expect(find_link("Link 1", href: "https://example.com/?#{sale_info_query_params}", target: "_blank")[:rel]).to eq("noopener noreferrer nofollow") expect(find_link("Link 2 with custom query parameters", href: "https://example.com/?test=123&#{sale_info_query_params}", target: "_blank")[:rel]).to eq("noopener noreferrer nofollow") expect(find_link("Link 3", href: "https://example.com/?test=123&#{sale_info_query_params}", target: "_blank")[:rel]).to eq("noopener noreferrer nofollow") expect(find_link("Button with custom query parameters", href: "https://example.com/?test=123&#{sale_info_query_params}", target: "_blank")[:rel]).to eq("noopener noreferrer nofollow") end it "shows license key within the content and not outside of the content" do product_rich_content = @product.alive_rich_contents.first product_rich_content.update!(title: "Page 1", description: [ { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Lorem ipsum" }] }, { "type" => "licenseKey" }, { "type" => "fileEmbed", "attrs" => { "id" => @video_file.external_id, "uid" => SecureRandom.uuid } } ]) create(:rich_content, entity: @product, title: "Page 2", description: [{ "type" => "paragraph", "content" => [{ "type" => "fileEmbed", "attrs" => { "id" => @audio_file.external_id, "uid" => SecureRandom.uuid } }] }]) @product.update!(is_licensed: true, is_multiseat_license: true) @purchase.update!(is_multiseat_license: true) create(:license, link: @product, purchase: @purchase) visit("/d/#{@url_redirect.token}") within find("[aria-label='Product content']") do expect(page).to have_text("Lorem ipsum") within find_embed(name: @purchase.license_key) do expect(page).to have_text("License key") expect(page).to have_text("1 Seat") expect(page).to have_button("Copy") end end expect(page).to have_text(@purchase.license_key, count: 1) expect(page).to have_tab_button("Page 1", open: true) within find(:tab_button, "Page 1") do expect(page).to have_selector("[aria-label='Page has license key']") end expect(page).to have_tab_button("Page 2", open: false) within find(:tab_button, "Page 2") do expect(page).to have_selector("[aria-label='Page has audio files']") end end describe "posts" do before do rich_content = @product.rich_contents.alive.first rich_content.update!(description: rich_content.description.unshift({ "type" => "posts" })) logout end it "correctly displays non-subscription purchase posts for published posts" do previous_post = create(:installment, link: @product, published_at: 50.days.ago, name: "my old thing") valid_post = create(:installment, link: @product, published_at: Time.current, name: "my new thing") unpublished_post = create(:installment, link: @product, name: "an unpublished thing") deleted_post = create(:installment, link: @product, published_at: Time.current, name: "my deleted thing", deleted_at: Time.current) create(:creator_contacting_customers_email_info_sent, purchase: @purchase, installment: valid_post) create(:creator_contacting_customers_email_info_sent, purchase: @purchase, installment: deleted_post) visit @url_redirect.download_page_url within find_embed(name: "Posts") do expect(page).to have_link(valid_post.displayed_name) expect(page).to_not have_link(unpublished_post.displayed_name) expect(page).to_not have_link(previous_post.displayed_name) end end it "displays cancelled membership posts" do @product = create(:subscription_product, user: @user) create(:rich_content, entity: @product, description: [{ "type" => "posts" }]) subscription_1 = create(:subscription, link_id: @product.id, user_id: @user.id) purchase_1 = create(:purchase, link: @product, is_original_subscription_purchase: true, subscription: subscription_1, purchaser: @user, email: @user.email) post_1 = create(:installment, link: @product, published_at: 3.days.ago) @url_redirect = create(:url_redirect, purchase: purchase_1, installment: post_1) create(:creator_contacting_customers_email_info_sent, purchase: purchase_1, installment: post_1)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/download_page/audio_files_spec.rb
spec/requests/download_page/audio_files_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Download Page Audio files", type: :system, js: true) do before do @url_redirect = create(:listenable_url_redirect) @product = @url_redirect.referenced_link login_as(@url_redirect.purchase.purchaser) Link.import(refresh: true) end describe "Play button" do it "shows Play button" do allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to have_button("Play") end it "hides Play button on click and shows Close button" do allow_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(@product.product_files.first.url) visit("/d/#{@url_redirect.token}") expect(page).to have_button("Play") click_button("Play") expect(page).to have_button("Close") end it "shows Play again button for a file which has been listened to completely" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 46) allow_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).and_return(@product.product_files.first.url) visit("/d/#{@url_redirect.token}") expect(page).to have_button("Play again") end it "is absent for product files with non-listenable urls" do @product.product_files.delete_all create(:non_listenable_audio, :analyze, link: @product) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to_not have_button("Play") end end describe "consumption progress pie" do it "does not show progress pie if not started listening" do allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to_not have_selector("[role='progressbar']") end it "shows progress pie if listening in progress" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 10) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to have_selector("[role='progressbar'][aria-valuenow='#{(1000.0 / 46).round(2)}']") end it "shows completed progress pie if listening is done" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 46) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to have_selector("[role='progressbar'][aria-valuenow='100']") end end describe "listening to a file" do before do url = @product.product_files.first.url allow_any_instance_of(UrlRedirect).to receive(:signed_location_for_file).and_return(url) end it "shows the audio player on clicking Play" do visit("/d/#{@url_redirect.token}") expect(page).to_not have_selector("[aria-label='Rewind15']") click_button("Play") expect(page).to have_selector("[aria-label='Rewind15']") end it "closes audio player on clicking Close" do visit("/d/#{@url_redirect.token}") expect(page).to_not have_selector("[aria-label='Rewind15']") click_button("Play") expect(page).to have_selector("[aria-label='Rewind15']") click_button("Close") expect(page).to_not have_selector("[aria-label='Rewind15']") end it "resumes from previous location if media_location exists" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 23) visit("/d/#{@url_redirect.token}") click_button("Play") expect(page).to have_selector("[aria-label='Progress']", text: "00:23") expect(page).to have_selector("[aria-label='Progress']", text: "00:25") end it "resumes from start if listening was complete" do create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 46) visit("/d/#{@url_redirect.token}") click_button("Play") expect(page).to have_selector("[aria-label='Progress']", text: "00:00") expect(page).to have_selector("[aria-label='Progress']", text: "00:01") end it "pauses the player on clicking the pause icon" do visit("/d/#{@url_redirect.token}") click_button("Play") expect(page).to have_selector("[aria-label='Progress']", text: "00:01") find_and_click("[aria-label='Pause']") expect(page).to have_selector("[aria-label='Play']") expect(page).to_not have_selector("[aria-label='Pause']") end it "rewind button rewinds the playback by 15 seconds" do visit("/d/#{@url_redirect.token}") click_button("Play") expect(page).to have_selector("[aria-label='Progress']", text: "00:01") find_and_click("[aria-label='Pause']") progress_text = find("[aria-label='Progress']").text progress_seconds = progress_text[3..5].to_i find_and_click("[aria-label='Skip30']") find_and_click("[aria-label='Rewind15']") expect(page).to have_selector("[aria-label='Progress']", text: "00:#{(progress_seconds + 15).to_s.rjust(2, "0")}") find_and_click("[aria-label='Rewind15']") expect(page).to have_selector("[aria-label='Progress']", text: progress_text) end it "skip button forwards playback by 30 seconds" do visit("/d/#{@url_redirect.token}") click_button("Play") expect(page).to have_selector("[aria-label='Progress']", text: "00:01") find_and_click("[aria-label='Pause']") progress_text = find("[aria-label='Progress']").text progress_seconds = progress_text[3..5].to_i find_and_click("[aria-label='Skip30']") expect(page).to have_selector("[aria-label='Progress']", text: "00:#{(progress_seconds + 30).to_s.rjust(2, "0")}") end context "multiple audio players" do before do @listenable2 = create(:listenable_audio, :analyze, link: @product) @listenable3 = create(:listenable_audio, :analyze, link: @product) allow_any_instance_of(UrlRedirect).to receive(:signed_location_for_file).and_return(@product.product_files.first.url) end it "pauses other audio players on play" do visit("/d/#{@url_redirect.token}") page.all("[aria-label='Play Button']")[0].click expect(page).to have_selector("[aria-label='Progress']", text: "00:01") page.all("[aria-label='Play Button']")[1].click progress_text_0 = page.all("[aria-label='Progress']")[0].text progress_seconds_0 = progress_text_0[3..5].to_i expect(page).to have_selector("[aria-label='Play']") expect(page).to have_selector("[aria-label='Pause']") expect(page).to have_selector("[aria-label='Progress']", text: "00:#{(progress_seconds_0 + 1).to_s.rjust(2, "0")}") page.all("[aria-label='Play Button']")[2].click progress_text_1 = page.all("[aria-label='Progress']")[1].text progress_seconds_1 = progress_text_1[3..5].to_i expect(page).to have_selector("[aria-label='Play']", count: 2) expect(page).to have_selector("[aria-label='Pause']") expect(page).to have_selector("[aria-label='Progress']", text: "00:#{(progress_seconds_1 + 1).to_s.rjust(2, "0")}") expect(page).to have_selector("[aria-label='Progress']", text: progress_text_1) expect(page).to have_selector("[aria-label='Progress']", text: progress_text_0) end end context "triggers the correct consumption events" do it "creates consumption events on viewing the page and playing an audio file" do expect do visit("/d/#{@url_redirect.token}") end.to change(ConsumptionEvent, :count).by(1) download_event = ConsumptionEvent.last expect(download_event.event_type).to eq ConsumptionEvent::EVENT_TYPE_VIEW expect(download_event.link_id).to eq @product.id expect(download_event.product_file_id).to be_nil expect(download_event.url_redirect_id).to eq @url_redirect.id expect(download_event.ip_address).to eq "127.0.0.1" expect do click_button("Play") expect(page).to have_selector("[aria-label='Progress']", text: "00:01") find_and_click("[aria-label='Pause']") end.to change(ConsumptionEvent, :count).by(1) listen_event = ConsumptionEvent.last expect(listen_event.event_type).to eq ConsumptionEvent::EVENT_TYPE_LISTEN expect(listen_event.link_id).to eq @product.id expect(listen_event.product_file_id).to eq @product.product_files.first.id expect(listen_event.url_redirect_id).to eq @url_redirect.id expect(listen_event.ip_address).to eq "127.0.0.1" end it "does not record media_location if purchase is nil" do listenable_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/magic.mp3" installment = create(:installment, call_to_action_text: "CTA", call_to_action_url: "https://www.gum.co", seller: @product.user) create(:product_file, :analyze, installment:, url: listenable_url) no_purchase_url_redirect = installment.generate_url_redirect_for_follower visit("/d/#{no_purchase_url_redirect.token}") click_button("Play") expect(page).to have_selector("[aria-label='Progress']", text: "00:01") find_and_click("[aria-label='Pause']") wait_for_ajax expect(MediaLocation.count).to eq 0 end it "creates listen progress location on continuing playback audio file" do visit("/d/#{@url_redirect.token}") click_button("Play") expect(page).to have_selector("[aria-label='Progress']", text: "00:05") find_and_click("[aria-label='Pause']") wait_for_ajax media_location = MediaLocation.last expect(media_location.product_id).to eq @product.id expect(media_location.product_file_id).to eq @product.product_files.first.id expect(media_location.url_redirect_id).to eq @url_redirect.id expect(media_location.location).to be < 3 expect(media_location.unit).to eq MediaLocation::Unit::SECONDS end it "updates watch progress on completion of stream with the backend duration" do @product.product_files.first.update!(duration: 1000) create(:media_location, url_redirect_id: @url_redirect.id, purchase_id: @url_redirect.purchase.id, product_file_id: @product.product_files.first.id, product_id: @product.id, location: 45) visit("/d/#{@url_redirect.token}") click_button("Play") expect(page).to have_selector("[aria-label='Play']") wait_for_ajax sleep 5 expect(MediaLocation.count).to eq 1 media_location = MediaLocation.last expect(media_location.product_id).to eq @product.id expect(media_location.product_file_id).to eq @product.product_files.first.id expect(media_location.url_redirect_id).to eq @url_redirect.id expect(media_location.location).to eq(1000) expect(media_location.unit).to eq MediaLocation::Unit::SECONDS end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/download_page/download_page_spec.rb
spec/requests/download_page/download_page_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Download Page", type: :system, js: true) do describe "open in app" do before do @product = create(:product, user: create(:user)) create(:product_file, link_id: @product.id, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test.pdf").analyze create(:product_file, link_id: @product.id, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test.pdf").analyze end it "allows the user to create an account and show instructions to get the app" do purchase = create(:purchase_with_balance, link: @product, email: "user@testing.com") url_redirect = purchase.url_redirect visit("/d/#{url_redirect.token}") select_disclosure "Open in app" do expect(page).to have_text("Download from the App Store") end vcr_turned_on do VCR.use_cassette("Open in app-create account with not compromised password") do with_real_pwned_password_check do fill_in("Your password", with: SecureRandom.hex(24)) click_on("Create") end end end end it "displays warning while creating an account with a compromised password" do purchase = create(:purchase_with_balance, link: @product, email: "user@testing.com") url_redirect = purchase.url_redirect visit("/d/#{url_redirect.token}") vcr_turned_on do VCR.use_cassette("Open in app-create account with compromised password") do with_real_pwned_password_check do fill_in("Your password", with: "password") click_on("Create") expect(page).to have_text("Password has previously appeared in a data breach as per haveibeenpwned.com and should never be used. Please choose something harder to guess.") end end end end it "shows the instructions to get the app immediately if logged in" do user = create(:user) login_as(user) purchase = create(:purchase_with_balance, link: @product, email: user.email, purchaser_id: user.id) url_redirect = purchase.url_redirect visit("/d/#{url_redirect.token}") select_disclosure "Open in app" do expect(page).to have_text("Download from the App Store") expect(page).to(have_link("App Store")) expect(page).to(have_link("Play Store")) end end end describe "discord integration" do let(:user_id) { "user-0" } let(:integration) { create(:discord_integration) } let(:product) { create(:product, active_integrations: [integration]) } let(:purchase) { create(:purchase, link: product) } let(:url_redirect) { create(:url_redirect, purchase:) } describe "Join Discord" do it "shows the join discord button if integration is present on purchased product" do visit("/d/#{url_redirect.token}") expect(page).to have_button "Join Discord" end it "does not show the join discord button if integration is not present on purchased product" do product.product_integrations.first.mark_deleted! visit("/d/#{url_redirect.token}") expect(page).to_not have_button "Join Discord" end it "adds customer to discord if oauth successful", billy: true do # TODO: Use the below commented out line instead, after removing the :custom_domain_download feature flag (curtiseinsmann) proxy.stub("https://www.discord.com:443/api/oauth2/authorize").and_return(redirect_to: oauth_redirect_integrations_discord_index_url(code: "test_code", host: UrlService.domain_with_protocol)) # proxy.stub("https://www.discord.com:443/api/oauth2/authorize").and_return(redirect_to: oauth_redirect_integrations_discord_index_url(code: "test_code", host: product.user.subdomain_with_protocol)) WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL). to_return(status: 200, body: { access_token: "test_access_token" }.to_json, headers: { content_type: "application/json" }) WebMock.stub_request(:get, "#{Discordrb::API.api_base}/users/@me"). with(headers: { "Authorization" => "Bearer test_access_token" }). to_return(status: 200, body: { username: "gumbot", id: user_id }.to_json, headers: { content_type: "application/json" }) WebMock.stub_request(:put, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(status: 201) visit("/d/#{url_redirect.token}") expect do click_button "Join Discord" expect_alert_message "You've been added to the Discord server #Gaming!" expect(page).to have_button "Leave Discord" expect(page).to_not have_button "Join Discord" end.to change { PurchaseIntegration.count }.by(1) purchase_discord_integration = PurchaseIntegration.last expect(purchase_discord_integration.discord_user_id).to eq(user_id) expect(purchase_discord_integration.integration).to eq(integration) expect(purchase_discord_integration.purchase).to eq(purchase) end it "shows error if oauth fails while adding customer to discord", billy: true do # TODO: Use the below commented out line instead, after removing the :custom_domain_download feature flag (curtiseinsmann) proxy.stub("https://www.discord.com:443/api/oauth2/authorize").and_return(redirect_to: oauth_redirect_integrations_discord_index_url(error: "error_message", host: UrlService.domain_with_protocol)) # proxy.stub("https://www.discord.com:443/api/oauth2/authorize").and_return(redirect_to: oauth_redirect_integrations_discord_index_url(error: "error_message", host: product.user.subdomain_with_protocol)) visit("/d/#{url_redirect.token}") expect do click_button "Join Discord" expect_alert_message "Could not join the Discord server, please try again." expect(page).to have_button "Join Discord" expect(page).to_not have_button "Leave Discord" end.to change { PurchaseIntegration.count }.by(0) end it "shows error if adding customer to discord fails", billy: true do # TODO: Use the below commented out line instead, after removing the :custom_domain_download feature flag (curtiseinsmann) proxy.stub("https://www.discord.com:443/api/oauth2/authorize").and_return(redirect_to: oauth_redirect_integrations_discord_index_url(code: "test_code", host: UrlService.domain_with_protocol)) # proxy.stub("https://www.discord.com:443/api/oauth2/authorize").and_return(redirect_to: oauth_redirect_integrations_discord_index_url(code: "test_code", host: product.user.subdomain_with_protocol)) WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL). to_return(status: 200, body: { access_token: "test_access_token" }.to_json, headers: { content_type: "application/json" }) WebMock.stub_request(:get, "#{Discordrb::API.api_base}/users/@me"). with(headers: { "Authorization" => "Bearer test_access_token" }). to_return(status: 200, body: { username: "gumbot", id: user_id }.to_json, headers: { content_type: "application/json" }) WebMock.stub_request(:put, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(status: 403) visit("/d/#{url_redirect.token}") expect do click_button "Join Discord" expect_alert_message "Could not join the Discord server, please try again." expect(page).to have_button "Join Discord" expect(page).to_not have_button "Leave Discord" end.to change { PurchaseIntegration.count }.by(0) end end describe "Leave Discord" do let!(:purchase_integration) { create(:purchase_integration, integration:, purchase:, discord_user_id: user_id) } it "shows the leave discord button if integration is activated" do visit("/d/#{url_redirect.token}") expect(page).to have_button "Leave Discord" end it "does not show the leave discord button if integration is not active" do purchase_integration.mark_deleted! visit("/d/#{url_redirect.token}") expect(page).to_not have_button "Leave Discord" end it "removes customer from discord" do WebMock.stub_request(:delete, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(status: 204) visit("/d/#{url_redirect.token}") expect do click_button "Leave Discord" expect_alert_message "You've left the Discord server #Gaming." expect(page).to_not have_button "Leave Discord" expect(page).to have_button "Join Discord" end.to change { purchase.live_purchase_integrations.count }.by(-1) end it "shows error if removing customer from Discord fails" do WebMock.stub_request(:delete, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(status: 200) visit("/d/#{url_redirect.token}") expect do click_button "Leave Discord" expect_alert_message "Could not leave the Discord server." expect(page).to have_button "Leave Discord" expect(page).to_not have_button "Join Discord" end.to change { purchase.live_purchase_integrations.count }.by(0) end end end describe "add to library, if it was made anonymously but the user is currently logged in" do before do @user = create(:user) login_as(@user) product = create(:product, user: create(:user)) create(:product_file, link_id: product.id, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test.pdf").analyze create(:product_file, link_id: product.id, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test.pdf").analyze @purchase = create(:purchase_with_balance, link: product, email: @user.email, purchaser_id: nil) url_redirect = @purchase.url_redirect visit("/d/#{url_redirect.token}") end it "adds purchase to library" do expect(page).to have_button("Add to library") click_button("Add to library") wait_for_ajax expect(@purchase.reload.purchaser).to eq @user end end describe "Community button" do let(:seller) { create(:user) } let(:user) { create(:user) } let(:product) { create(:product, user: seller) } let!(:community) { create(:community, resource: product, seller:) } let(:purchase) { create(:purchase_with_balance, seller:, link: product, purchaser: user) } let(:url_redirect) { purchase.url_redirect } before do Feature.activate_user(:communities, seller) login_as(user) end it "does not render the Community button if the product has no active community" do visit("/d/#{url_redirect.token}") expect(page).not_to have_text("Community") end it "renders the Community button if the product has an active community" do product.update!(community_chat_enabled: true) visit("/d/#{url_redirect.token}") expect(page).to have_link("Community", href: community_path(seller.external_id, community.external_id)) end end describe "installments" do before do allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000) @user = create(:user, name: "John Doe") @post = create(:installment, name: "Thank you!", link: nil, seller: @user) @post.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4") @url_redirect = create(:installment_url_redirect, installment: @post) product_files_archive = @post.product_files_archives.create product_files_archive.product_files = @post.product_files product_files_archive.save! product_files_archive.mark_in_progress! product_files_archive.mark_ready! end it "renders the download page properly" do # Regular streamable files can be both watched and downloaded visit("/d/#{@url_redirect.token}") expect(page).to have_text("Thank you!") expect(page).to have_text("By John Doe") expect(page).to have_text("chapter2") expect(page).to have_link("Watch") expect(page).to have_link("Download", exact: true) expect(page).to have_disclosure("Download all") # Stream-only files can only be watched and not downloaded @post.product_files.first.update!(stream_only: true) visit("/d/#{@url_redirect.token}") expect(page).to have_text("chapter2") expect(page).to have_link("Watch") expect(page).not_to have_link("Download", exact: true) expect(page).not_to have_disclosure("Download all") end end describe "physical" do before do allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000) @product = create(:physical_product) @purchase = create(:physical_purchase, link: @product) @url_redirect = create(:url_redirect, purchase: @purchase) end it "correctly renders the download page for a physical product with no files" do visit "/d/#{@url_redirect.token}" expect(page).not_to have_selector("[role=tree][aria-label=Files]") expect(page).not_to have_button("Download all") end end describe "membership" do before do @purchase = create(:membership_purchase) @url_redirect = create(:url_redirect, purchase: @purchase) @manage_membership_url = Rails.application.routes.url_helpers.manage_subscription_url(@purchase.subscription.external_id, host: "#{PROTOCOL}://#{DOMAIN}") end it "displays a link to manage membership if active" do visit "/d/#{@url_redirect.token}" select_disclosure "Membership" do button = find("a.button[href='#{@manage_membership_url}']") expect(button).to have_text "Manage" end end context "for inactive membership" do before { @purchase.subscription.update!(cancelled_at: 1.minute.ago) } it "displays a link to restart membership if inactive" do visit "/d/#{@url_redirect.token}" select_disclosure "Membership" do button = find("a.button[href='#{@manage_membership_url}']") expect(button).to have_text "Restart" end end context "when subscriber should lose access after cancellation" do before { @purchase.link.update!(block_access_after_membership_cancellation: true) } it "redirects to the inactive membership page" do visit "/d/#{@url_redirect.token}" expect(page).to have_current_path(url_redirect_membership_inactive_page_path(@url_redirect.token)) end it "includes a Manage Membership link if the subscription is restartable" do allow_any_instance_of(Subscription).to receive(:alive_or_restartable?).and_return(true) visit "/d/#{@url_redirect.token}" button = find("a.button[href='#{@manage_membership_url}']") expect(button).to have_text "Manage membership" end it "includes a Resubscribe link if the subscription is not restartable" do allow_any_instance_of(Subscription).to receive(:alive_or_restartable?).and_return(false) visit "/d/#{@url_redirect.token}" button = find("a.button[href='#{@purchase.link.long_url}']") expect(button).to have_text "Resubscribe" end end end end describe "installment plans" do let(:purchase_with_installment_plan) { create(:installment_plan_purchase) } let(:subscription) { purchase_with_installment_plan.subscription } let(:url_redirect) { create(:url_redirect, purchase: purchase_with_installment_plan) } let(:manage_installment_plan_path) { manage_subscription_path(subscription.external_id) } context "active" do it "displays a link to manage installment plan" do visit "/d/#{url_redirect.token}" select_disclosure "Installment plan" do expect(page).to have_link("Manage", href: /#{Regexp.quote(manage_installment_plan_path)}/) end end end context "paid in full" do before do product = subscription.link subscription.update_columns(charge_occurrence_count: product.installment_plan.number_of_installments) (product.installment_plan.number_of_installments - 1).times do create(:purchase, link: product, subscription: subscription, purchaser: subscription.user) end end it "shows a message that it has been paid in full" do visit "/d/#{url_redirect.token}" select_disclosure "Installment plan" do expect(page).to have_text "This installment plan has been paid in full." end end end context "failed" do before { subscription.unsubscribe_and_fail! } it "cuts off access to the product and includes a link to update payment method" do visit "/d/#{url_redirect.token}" expect(page).to have_text("Your installment plan is inactive") expect(page).to have_link("Update payment method", href: /#{Regexp.quote(manage_installment_plan_path)}/) end end context "cancelled by seller" do before { subscription.cancel!(by_seller: true) } it "cuts off access to the product and includes a link to update payment method" do visit "/d/#{url_redirect.token}" expect(page).to have_text("Your installment plan is inactive") end end end describe "membership with untitled tier" do it "uses the product name if tier's name is Untitled" do product = create(:membership_product, name: "my membership") tier = create(:variant, :with_product_file, variant_category: product.tier_category, name: "Untitled") purchase = create(:membership_purchase, link: product, variant_attributes: [tier]) url_redirect = create(:url_redirect, purchase:) visit "/d/#{url_redirect.token}" expect(page).to have_title "my membership" expect(page).to_not have_content "Untitled" end end describe("new user") do before :each do link = create(:product_with_pdf_file) @purchase = create(:purchase, link:, email: "user@testing.com") @url_redirect = create(:url_redirect, link:, purchase: @purchase) visit("/d/#{@url_redirect.token}") end it("fails to sign me up") do fill_in("Your password", with: "123") click_on("Create") expect(page).to have_alert(text: "Password is too short (minimum is 4 characters)") expect(page).to_not have_button("Add to library") expect(User.exists?(email: "user@testing.com")).to(be(false)) end it("signs me up and takes me to library") do fill_in("Your password", with: "123456") click_on("Create") wait_for_ajax expect(page).to_not have_text("Create an account to access all of your purchases in one place") expect(User.exists?(email: "user@testing.com")).to(be(true)) user = User.last expect(Purchase.last.purchaser_id).to eq user.id end end describe "single video" do it "doesn't allow the file to be downloaded if it's streaming only" do product = create(:product) product.product_files << create(:streamable_video, stream_only: true) url_redirect = create(:url_redirect, link: product, purchase: nil) allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000) visit("/d/#{url_redirect.token}") expect(page).not_to have_selector("button", exact_text: "Download") end it "doesn't display the download option for a rental" do product = create(:product) product.product_files << create(:streamable_video) url_redirect = create(:url_redirect, link: product, purchase: nil, is_rental: true) allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000) visit("/d/#{url_redirect.token}") expect(page).not_to have_selector("button", exact_text: "Download") end end it "allows resending the receipt" do url_redirect = create(:url_redirect) allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000) visit("/d/#{url_redirect.token}") select_disclosure "Receipt" do click_on "Resend receipt" end expect(page).to have_alert(text: "Receipt resent") expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(url_redirect.purchase.id).on("critical") end describe "archive actions" do before :each do @user = create(:user) end context "when unauthenticated" do it "doesn't shows archive button" do purchase = create(:purchase, purchaser: @user) create(:url_redirect, purchase:) Link.import(refresh: true, force: true) visit purchase.url_redirect.download_page_url expect(page).not_to have_button "Archive" end end context "when authenticated" do before :each do login_as @user end it "allows archiving" do purchase = create(:purchase, purchaser: @user) create(:url_redirect, purchase:) Link.import(refresh: true, force: true) visit purchase.url_redirect.download_page_url select_disclosure "Library" do click_on "Archive from library" end wait_for_ajax select_disclosure "Library" do expect(page).to have_button "Unarchive from library" end end it "allows unarchiving" do purchase = create(:purchase, purchaser: @user, is_archived: true) create(:url_redirect, purchase:) Link.import(refresh: true, force: true) visit purchase.url_redirect.download_page_url select_disclosure "Library" do click_on "Unarchive from library" end wait_for_ajax select_disclosure "Library" do expect(page).to have_button "Archive from library" end end it "doesn't shows when there is no purchase" do product = create(:product) url_redirect = create(:url_redirect, link: product, purchase: nil) visit url_redirect.download_page_url expect(page).to_not have_disclosure "Library" end end end describe "external links as files" do before do @url_redirect = create(:url_redirect) @product = @url_redirect.referenced_link @product.product_files << create(:product_file, link: @product, url: "https://gumroad.com", filetype: "link", display_name: "Gumroad – Sell what you know and see what sticks") login_as(@url_redirect.purchase.purchaser) Link.import(refresh: true) end it "shows Open button for external links" do visit("/d/#{@url_redirect.token}") expect(page).to have_link("Open", exact: true) end it "does not show the Download button for external links" do visit("/d/#{@url_redirect.token}") expect(page).to_not have_link("Download", exact: true) end it "Open button absent for non external-link product files" do @product.product_files.delete_all create(:non_listenable_audio, :analyze, link: @product) allow(@url_redirect).to receive(:redirect_or_s3_location).and_return("fakelink") visit("/d/#{@url_redirect.token}") expect(page).to_not have_link("Open", exact: true) end it "redirects to the external url on clicking Open" do visit("/d/#{@url_redirect.token}") new_window = window_opened_by { click_on "Open" } within_window new_window do expect(page).to have_current_path("https://gumroad.com") end end it "redirects to the external url on clicking the name" do visit("/d/#{@url_redirect.token}") new_window = window_opened_by { click_on "Gumroad – Sell what you know and see what sticks" } within_window new_window do expect(page).to have_current_path("https://gumroad.com") end end end describe "seller with no name and username" do before do @user = create(:user, name: nil, username: nil) @product = create(:product, user: @user) @purchase = create(:purchase, email: "test@abc.com", link: @product) @url_redirect = create(:url_redirect, purchase: @purchase) end it "renders the page when the seller's URL is nil" do visit("/d/#{@url_redirect.token}") expect(page).to have_content(@product.name) end end describe "thank you note text" do it "does not render custom receipt text even if it exists" do custom_receipt_text = "Thanks for your purchase! https://example.com" product = create(:product, custom_receipt: custom_receipt_text) purchase = create(:purchase, email: "test@tynt.com", link: product) url_redirect = create(:url_redirect, purchase:) visit url_redirect.download_page_url expect(page).to_not have_text(custom_receipt_text) end it "does not render a paragraph if there is no custom receipt text" do product = create(:product) purchase = create(:purchase, email: "test@tynt.com", link: product) url_redirect = create(:url_redirect, purchase:) visit url_redirect.download_page_url expect(page).to_not have_selector("p") end end it "plays videos in the order they are shown on the download page for an installment" do video_blob = ActiveStorage::Blob.create_and_upload!(io: Rack::Test::UploadedFile.new(Rails.root.join("spec", "support", "fixtures", "sample.mov"), "video/quicktime"), filename: "sample.mov", key: "test/sample.mov") allow_any_instance_of(UrlRedirect).to receive(:html5_video_url_and_guid_for_product_file).and_return([video_blob.url, ""]) product = create(:product) purchase = create(:purchase, link: product) url_redirect = create(:url_redirect, link: product, purchase:) post = create(:published_installment, seller: product.user, link: product, shown_on_profile: false) create(:creator_contacting_customers_email_info_sent, purchase: purchase, installment: post) post.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/2/original/chapter2.mp4", position: 1, created_at: 2.day.ago) post.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/1/original/chapter1.mp4", position: 0, created_at: 1.day.ago) post.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/4/original/chapter4.mp4", position: 3, created_at: 1.hour.ago) post.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachments/3/original/chapter3.mp4", position: 2, created_at: 12.hours.ago) visit("/d/#{url_redirect.token}") within "[aria-label=Posts]" do within find("[role=listitem] h4", text: post.displayed_name).ancestor("[role=listitem]") do click_on "View" end end expect(page).to have_section post.displayed_name click_on "View content" expect(find_all("[role='treeitem'] h4").map(&:text)). to match_array(["chapter1", "chapter2", "chapter3", "chapter4"]) within(find_file_row!(name: "chapter1")) do click_on "Watch" end page.driver.browser.switch_to.window(page.driver.browser.window_handles.last) click_on "More Videos" expect(page).to_not have_button("1. chapter1") expect(page).to have_button("Next Upchapter2") expect(page).to have_button("3. chapter3") expect(page).to have_button("4. chapter4") click_on "Previous" expect(page).to have_button("1. chapter1") end describe "email confirmation" do let(:product) { create(:product) } let(:purchase) { create(:purchase, link: product) } let(:url_redirect) { create(:url_redirect, link: product, purchase:) } before do visit(confirm_page_path(id: url_redirect.token, destination: "download_page")) end it "redirects to the download page after confirming email" do expect(page).to have_text("You've viewed this product a few times already") expect(page).to_not have_text("Liked it? Give it a rating") expect(page).to_not have_disclosure("Receipt") expect(page).to_not have_text("Create an account to access all of your purchases in one place") fill_in "Email address", with: purchase.email click_on "Confirm email" expect(page).to_not have_text("You've viewed this product a few times already") expect(page).to have_text("Liked it? Give it a rating") expect(page).to have_disclosure("Receipt") expect(page).to have_text("Create an account to access all of your purchases in one place") expect(page).to have_text(product.name) end it "renders the same page if the email is invalid" do expect(page).to have_text("You've viewed this product a few times already") fill_in "Email address", with: "invalid" click_on "Confirm email" expect(page).to have_alert(text: "Wrong email. Please try again.") expect(page).to have_text("You've viewed this product a few times already") end end describe "bundle product" do let(:seller) { create(:named_seller) } let(:purchase) { create(:purchase, seller:, link: create(:product, :bundle, user: seller)) } before { purchase.create_artifacts_and_send_receipt! } it "links to the bundle receipt" do visit purchase.product_purchases.first.url_redirect.download_page_url select_disclosure "Receipt" expect(page).to have_link("View receipt", href: receipt_purchase_url(purchase.external_id, email: purchase.email, host: Capybara.app_host)) click_on "Resend receipt" expect(page).to have_alert(text: "Receipt resent") expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(purchase.id).on("critical") end end describe "post-purchase custom fields" do let(:seller) { create(:user) } let(:product) { create(:product, user: seller) } let(:purchase) { create(:purchase, link: product) } let!(:url_redirect) { create(:url_redirect, link: product, purchase:) } let(:short_answer) { create(:custom_field, field_type: CustomField::TYPE_TEXT, name: "Short Answer", seller:, products: [product], is_post_purchase: true) } let(:long_answer) { create(:custom_field, field_type: CustomField::TYPE_LONG_TEXT, name: "Long Answer", seller:, products: [product], is_post_purchase: true) } let(:file_upload) { create(:custom_field, field_type: CustomField::TYPE_FILE, name: nil, seller:, products: [product], is_post_purchase: true) } before do create(:product_rich_content, entity: product, description: [ { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "id" => short_answer.external_id, "label" => "Short Answer" } }, { "type" => RichContent::LONG_ANSWER_NODE_TYPE, "attrs" => { "id" => long_answer.external_id, "label" => "Long Answer" } }, { "type" => RichContent::FILE_UPLOAD_NODE_TYPE, "attrs" => { "id" => file_upload.external_id, } } ] ) end it "allows completing post-purchase custom fields" do visit url_redirect.download_page_url short_answer_field = find_field("Short Answer") short_answer_field.fill_in with: "This is a short answer" short_answer_field.native.send_keys(:tab) wait_for_ajax expect(page).to have_alert(text: "Response saved!") long_answer_field = find_field("Long Answer") long_answer_field.fill_in with: "This is a longer answer with multiple sentences. It can contain more detailed information." long_answer_field.native.send_keys(:tab) wait_for_ajax expect(page).to have_alert(text: "Response saved!") expect(page).to have_text("Files must be smaller than 10 MB") attach_file("Upload files", file_fixture("smilie.png"), visible: false) wait_for_ajax expect(page).to have_alert(text: "Files uploaded successfully!") expect(page).to have_text("smilie") expect(page).to have_text("PNG") expect(page).to have_text("98.1 KB") purchase.reload expect(purchase.purchase_custom_fields.count).to eq(3) text_field = purchase.purchase_custom_fields.find_by(field_type: CustomField::TYPE_TEXT)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/download_page/product_reviews_spec.rb
spec/requests/download_page/product_reviews_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Download Page product reviews", type: :system, js: true) do let(:product) { create(:product_with_pdf_files_with_size, custom_permalink: "custom") } let(:purchase) { create(:purchase_with_balance, link: product, email: "one@gr.test", created_at: 2.years.ago) } let(:url_redirect) { purchase.url_redirect } it "allows the user to provide a rating regardless of display_product_reviews being enabled for that product" do visit("/d/#{url_redirect.token}") choose "3 stars" click_on "Post review" expect(page).to have_alert(text: "Review submitted successfully!") expect(purchase.reload.original_product_review.rating).to eq(3) product.display_product_reviews = false product.save! visit("/d/#{url_redirect.token}") expect(page).to have_text("Your rating:") expect(page).to have_radio_button("3 stars", checked: true) end it "displays existing rating and allows the user to update it regardless of display_product_reviews being enabled for that product" do create(:product_review, purchase:, rating: 4) expect(purchase.reload.original_product_review.rating).to eq(4) visit("/d/#{url_redirect.token}") expect(page).to have_radio_button("4 stars", checked: true) click_on "Edit" choose "3 stars" click_on "Update review" expect(page).to have_alert(text: "Review submitted successfully!") expect(purchase.reload.original_product_review.rating).to eq(3) product.display_product_reviews = false product.save! visit("/d/#{url_redirect.token}") expect(page).to have_text("Your rating:") expect(page).to have_radio_button("3 stars", checked: true) end it "displays and updates the product review of the original purchase in case of recurring purchase of a membership" do member = create(:user) membership_product = create(:product_with_pdf_files_with_size, is_recurring_billing: true, subscription_duration: :monthly, block_access_after_membership_cancellation: true, price_cents: 100) subscription = create(:subscription, link: membership_product) original_purchase = create(:purchase_with_balance, link: membership_product, is_original_subscription_purchase: true, subscription:, purchaser: member) recurring_purchase = create(:purchase_with_balance, link: membership_product, subscription:, purchaser: member) subscription.purchases << original_purchase << recurring_purchase url_redirect = recurring_purchase.url_redirect login_as(member) visit("/d/#{url_redirect.token}") expect(page).to have_text("Liked it? Give it a rating:") choose "3 stars" click_on "Post review" expect(page).to have_alert(text: "Review submitted successfully!") expect(original_purchase.reload.original_product_review.rating).to eq(3) expect(original_purchase.original_product_review).to eq(recurring_purchase.reload.original_product_review) visit("/d/#{url_redirect.token}") expect(page).to have_text("Your rating:") expect(page).to have_radio_button("3 stars", checked: true) click_on "Edit" choose "1 star" click_on "Update review" expect(page).to have_alert(text: "Review submitted successfully!") expect(original_purchase.reload.original_product_review.rating).to eq(1) end it "does not display or allow the user to review if the purchase is ineligible to submit a review" do purchase.update!(purchase_state: "failed") visit "/d/#{url_redirect.token}" expect(page).not_to have_content "Liked it? Give it a rating:" purchase.update!(purchase_state: "successful", should_exclude_product_review: true) visit "/d/#{url_redirect.token}" expect(page).not_to have_content "Liked it? Give it a rating:" end context "free trial subscriptions" do let(:purchase) { create(:free_trial_membership_purchase) } let(:url_redirect) { create(:url_redirect, purchase:) } it "allows the user to rate the product after the free trial" do purchase.subscription.charge! purchase.subscription.update!(free_trial_ends_at: 1.minute.ago) visit "/d/#{url_redirect.token}" choose "3 stars" click_on "Post review" expect(page).to have_alert(text: "Review submitted successfully!") expect(purchase.reload.original_product_review.rating).to eq(3) end end describe "written reviews" do it "allows the user to provide a review" do visit purchase.url_redirect.download_page_url expect(page).to have_field("Liked it? Give it a rating:", with: "") expect(page).to have_button("Post review", disabled: true) choose "4 stars" fill_in "Want to leave a written review?", with: "This is a great product!" click_on "Post review" expect(page).to have_alert(text: "Review submitted successfully!") expect(page).to_not have_field("Want to leave a written review?") expect(page).to have_radio_button("4 stars", checked: true) expect(page).to have_text('"This is a great product!"') expect(page).to have_button("Edit") review = purchase.reload.original_product_review expect(review.rating).to eq(4) expect(review.message).to eq("This is a great product!") end context "user has left a review" do let!(:review) { create(:product_review, purchase:, rating: 4, message: nil) } it "allows the user to update their review" do visit purchase.url_redirect.download_page_url expect(page).to_not have_field("Want to leave a written review?") expect(page).to have_radio_button("4 stars", checked: true) expect(page).to have_text("No written review") expect(page).to have_button("Edit") click_on "Edit" fill_in "Want to leave a written review?", with: "This is a great product!" choose "5 stars" click_on "Update review" expect(page).to have_alert(text: "Review submitted successfully!") expect(page).to_not have_field("Want to leave a written review?") expect(page).to have_radio_button("5 stars", checked: true) expect(page).to have_text('"This is a great product!"') expect(page).to have_button("Edit") review.reload expect(review.rating).to eq(5) expect(review.message).to eq("This is a great product!") end end end context "purchase is over a year old and reviews are disabled after 1 year" do before { product.user.update!(disable_reviews_after_year: true) } it "doesn't allow reviews and displays a status" do visit purchase.url_redirect.download_page_url expect(page).to have_radio_button("1 star", disabled: true) expect(page).to have_radio_button("2 stars", disabled: true) expect(page).to have_radio_button("3 stars", disabled: true) expect(page).to have_radio_button("4 stars", disabled: true) expect(page).to have_radio_button("5 stars", disabled: true) expect(page).to have_field("Want to leave a written review?", disabled: true) expect(page).to have_selector("[role='status']", text: "Reviews may not be created or modified for this product 1 year after purchase.") expect(page).to have_button("Post review", disabled: true) end end context "purchase is in free trial" do let(:purchase) { create(:free_trial_membership_purchase) } before { purchase.create_url_redirect! } it "doesn't allow reviews and displays a status" do visit purchase.url_redirect.download_page_url expect(page).to have_radio_button("1 star", disabled: true) expect(page).to have_radio_button("2 stars", disabled: true) expect(page).to have_radio_button("3 stars", disabled: true) expect(page).to have_radio_button("4 stars", disabled: true) expect(page).to have_radio_button("5 stars", disabled: true) expect(page).to have_field("Want to leave a written review?", disabled: true) expect(page).to have_selector("[role='status']", text: "Reviews are not allowed during the free trial period.") expect(page).to have_button("Post review", disabled: true) end end context "video reviews" do it "allows both text and video reviews" do visit purchase.url_redirect.download_page_url expect(page).to have_radio_button("Text review") expect(page).to have_radio_button("Video review") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/receipt_spec.rb
spec/requests/purchases/receipt_spec.rb
# frozen_string_literal: true require "spec_helper" describe("Viewing a purchase receipt", type: :system, js: true) do # Shared context for all tests let(:purchase) { create(:membership_purchase) } let(:manage_membership_url) { Rails.application.routes.url_helpers.manage_subscription_url(purchase.subscription.external_id, host: "#{PROTOCOL}://#{DOMAIN}") } before do create(:url_redirect, purchase:) end describe "membership purchase" do it "requires email confirmation to access receipt page" do visit receipt_purchase_url(purchase.external_id, host: "#{PROTOCOL}://#{DOMAIN}") expect(page).to have_content("Confirm your email address") fill_in "Email address:", with: purchase.email click_button "View receipt" expect(page).to have_link "subscription settings", href: manage_membership_url expect(page).to have_link "Manage membership", href: manage_membership_url end it "shows error message when incorrect email is provided" do visit receipt_purchase_url(purchase.external_id, host: "#{PROTOCOL}://#{DOMAIN}") expect(page).to have_content("Confirm your email address") fill_in "Email address:", with: "wrong@example.com" click_button "View receipt" expect(page).to have_content("Wrong email. Please try again.") expect(page).to have_content("Confirm your email address") end end describe "when user is a team member" do let(:team_member) { create(:user) } before do team_member.update!(is_team_member: true) sign_in team_member end it "allows access to receipt without email confirmation" do visit receipt_purchase_url(purchase.external_id, host: "#{PROTOCOL}://#{DOMAIN}") expect(page).to have_link "subscription settings", href: manage_membership_url expect(page).to have_link "Manage membership", href: manage_membership_url end end describe "Receipt customization" do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:purchase) { create(:purchase, link: product, seller: seller, email: "customer@example.com") } before do purchase.create_url_redirect! end context "when product has receipt customization" do before do product.custom_view_content_button_text = "Access Your Purchase" product.custom_receipt_text = "Welcome! Your purchase includes lifetime updates." product.save end it "displays custom content in the receipt page" do visit receipt_purchase_url(purchase.external_id, host: "#{PROTOCOL}://#{DOMAIN}") fill_in "Email address:", with: purchase.email click_button "View receipt" expect(page).to have_text("Access Your Purchase") expect(page).to have_text("Welcome! Your purchase includes lifetime updates.") expect(page).not_to have_text("View content") end end context "when product has no receipt customization" do it "displays default content in the receipt page" do visit receipt_purchase_url(purchase.external_id, host: "#{PROTOCOL}://#{DOMAIN}") fill_in "Email address:", with: purchase.email click_button "View receipt" expect(page).to have_text("View content") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/tipping_spec.rb
spec/requests/purchases/tipping_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Product checkout with tipping", type: :system, js: true) do let(:seller) { create(:named_seller, :eligible_for_service_products, tipping_enabled: true) } let(:product1) { create(:product, name: "Product 1", user: seller, price_cents: 1000, quantity_enabled: true) } let(:product2) { create(:product, name: "Product 2", user: seller, price_cents: 2000) } context "when the products have tipping enabled" do it "allows the buyer to tip a percentage" do visit product1.long_url fill_in "Quantity", with: 2 add_to_cart(product1, quantity: 2) visit product2.long_url add_to_cart(product2) fill_checkout_form(product2) expect(page).to have_radio_button("0%", checked: true) choose "10%" expect(page).to have_text("Subtotal US$40", normalize_ws: true) expect(page).to have_text("Tip US$4", normalize_ws: true) expect(page).to have_text("Total US$44", normalize_ws: true) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase1 = Purchase.last expect(purchase1).to be_successful expect(purchase1.link).to eq(product1) expect(purchase1.price_cents).to eq(2200) expect(purchase1.tip.value_cents).to eq(200) purchase2 = Purchase.second_to_last expect(purchase2).to be_successful expect(purchase2.link).to eq(product2) expect(purchase2.price_cents).to eq(2200) expect(purchase2.tip.value_cents).to eq(200) end it "allows the buyer to tip a fixed amount" do visit product1.long_url add_to_cart(product1) visit product2.long_url add_to_cart(product2) fill_checkout_form(product2) expect(page).to have_radio_button("0%", checked: true) choose "Other" fill_in "Tip", with: 20 expect(page).to have_text("Subtotal US$30", normalize_ws: true) expect(page).to have_text("Tip US$20", normalize_ws: true) expect(page).to have_text("Total US$50", normalize_ws: true) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase1 = Purchase.last expect(purchase1).to be_successful expect(purchase1.link).to eq(product1) expect(purchase1.price_cents).to eq(1667) expect(purchase1.tip.value_cents).to eq(667) purchase2 = Purchase.second_to_last expect(purchase2).to be_successful expect(purchase2.link).to eq(product2) expect(purchase2.price_cents).to eq(3333) expect(purchase2.tip.value_cents).to eq(1333) end context "when only coffee products are in the cart" do let(:coffee_product) { create(:product, user: seller, price_cents: 1000, native_type: Link::NATIVE_TYPE_COFFEE) } let(:product) { create(:product, user: seller, price_cents: 1500) } it "doesn't allow tipping" do visit coffee_product.long_url click_on "Donate" fill_checkout_form(coffee_product) expect(page).not_to have_text("Add a tip") expect(page).not_to have_radio_button("0%") expect(page).not_to have_radio_button("10%") expect(page).not_to have_radio_button("20%") expect(page).not_to have_radio_button("Other") expect(page).to have_text("Subtotal US$10", normalize_ws: true) expect(page).to have_text("Total US$10", normalize_ws: true) visit product.long_url add_to_cart(product) fill_checkout_form(product) expect(page).to have_text("Add a tip") expect(page).to have_radio_button("0%", checked: true) expect(page).to have_radio_button("10%") expect(page).to have_radio_button("20%") expect(page).to have_radio_button("Other") choose "10%" expect(page).to have_text("Subtotal US$25", normalize_ws: true) expect(page).to have_text("Tip US$2.50", normalize_ws: true) expect(page).to have_text("Total US$27.50", normalize_ws: true) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase1 = Purchase.last expect(purchase1).to be_successful expect(purchase1.link).to eq(coffee_product) expect(purchase1.price_cents).to eq(1100) expect(purchase1.tip.value_cents).to eq(100) purchase2 = Purchase.second_to_last expect(purchase2).to be_successful expect(purchase2.link).to eq(product) expect(purchase2.price_cents).to eq(1650) expect(purchase2.tip.value_cents).to eq(150) end end end context "when the cart is free" do let(:seller2) { create(:user, :eligible_for_service_products, tipping_enabled: true, name: "Seller 2", username: "seller2", email: "seller2@example.com", payment_address: "seller2@example.com") } let(:free_product1) { create(:product, name: "Free Product", user: seller, price_cents: 0) } let(:free_product2) { create(:product, name: "Free Product 2", user: seller2, price_cents: 0) } it "does not show tip selector and allows checkout without tip" do visit free_product1.long_url add_to_cart(free_product1, pwyw_price: 0) visit free_product2.long_url add_to_cart(free_product2, pwyw_price: 0) expect(page).not_to have_text("Add a tip") expect(page).not_to have_radio_button("0%") expect(page).not_to have_radio_button("10%") expect(page).not_to have_radio_button("20%") expect(page).not_to have_radio_button("Other") expect(page).not_to have_field("Tip") check_out(free_product1, is_free: true) purchase = Purchase.last expect(purchase).to be_successful expect(purchase.link).to eq(free_product1) expect(purchase.price_cents).to eq(0) expect(purchase.tip).to be_nil purchase2 = Purchase.second_to_last expect(purchase2).to be_successful expect(purchase2.link).to eq(free_product2) expect(purchase2.price_cents).to eq(0) expect(purchase2.tip).to be_nil end end context "when there's a membership in the cart" do let(:membership_product) { create(:membership_product) } it "doesn't allow tipping" do visit membership_product.long_url click_on "Subscribe" fill_checkout_form(membership_product) wait_for_ajax expect(page).not_to have_text("Add a tip") click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = Purchase.last expect(purchase).to be_successful expect(purchase.link).to eq(membership_product) expect(purchase.tip).to be_nil end end context "when there's a legacy subscription in the cart" do let(:product) { create(:product, :is_subscription, user: seller) } it "doesn't allow tipping" do visit product.long_url click_on "Subscribe" fill_checkout_form(product) wait_for_ajax expect(page).not_to have_text("Add a tip") click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = Purchase.last expect(purchase).to be_successful expect(purchase.link).to eq(product) expect(purchase.tip).to be_nil end end context "when custom tipping options are set" do before do TipOptionsService.set_tip_options([5, 15, 25]) TipOptionsService.set_default_tip_option(15) end it "allows selecting a custom tip option" do visit product1.long_url add_to_cart(product1) expect(page).to have_radio_button("5%", checked: false) expect(page).to have_radio_button("15%", checked: true) expect(page).to have_radio_button("25%", checked: false) expect(page).to have_radio_button("Other", checked: false) end end context "when there's a discount code in the cart" do let(:offer_code) { create(:percentage_offer_code, user: product1.user, products: [product1]) } it "tips on the post-discount price" do visit "#{product1.long_url}/#{offer_code.code}" add_to_cart(product1, offer_code:) visit product2.long_url add_to_cart(product2) fill_checkout_form(product2) expect(page).to have_text("Subtotal US$30", normalize_ws: true) expect(page).to have_text("Discounts #{offer_code.code} US$-5", normalize_ws: true) expect(page).to have_text("Total US$25", normalize_ws: true) choose "20%" wait_for_ajax expect(page).to have_text("Subtotal US$30", normalize_ws: true) expect(page).to have_text("Discounts #{offer_code.code} US$-5", normalize_ws: true) expect(page).to have_text("Tip US$5", normalize_ws: true) expect(page).to have_text("Total US$30", normalize_ws: true) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase1 = Purchase.last expect(purchase1).to be_successful expect(purchase1.link).to eq(product1) expect(purchase1.price_cents).to eq(600) expect(purchase1.tip.value_cents).to eq(100) purchase2 = Purchase.second_to_last expect(purchase2).to be_successful expect(purchase2.link).to eq(product2) expect(purchase2.price_cents).to eq(2400) expect(purchase2.tip.value_cents).to eq(400) end end context "when the product is priced in non-USD currency" do let(:product) { create(:product, user: seller, price_cents: 500000, price_currency_type: Currency::KRW) } it "computes the correct tip" do visit product.long_url add_to_cart(product) fill_checkout_form(product) choose "20%" wait_for_ajax expect(page).to have_text("Subtotal US$4.34", normalize_ws: true) expect(page).to have_text("Tip US$0.87", normalize_ws: true) expect(page).to have_text("Total US$5.21", normalize_ws: true) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = Purchase.last expect(purchase).to be_successful expect(purchase.displayed_price_currency_type).to be(:krw) expect(purchase.displayed_price_cents).to eq(600000) expect(purchase.price_cents).to eq(521) expect(purchase.tip.value_cents).to eq(100000) expect(purchase.tip.value_usd_cents).to eq(87) end end context "when there is no tip" do it "doesn't create a tip record" do visit product1.long_url add_to_cart(product1) fill_checkout_form(product1) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = Purchase.last expect(purchase).to be_successful expect(purchase.tip).to be_nil end end context "when the product is a commission" do let(:commission_product) { create(:commission_product) } before { commission_product.user.update!(tipping_enabled: true) } it "charges the correct amount for the deposit purchase" do visit commission_product.long_url add_to_cart(commission_product) visit product2.long_url add_to_cart(product2) fill_checkout_form(commission_product) expect(page).to have_text("Subtotal US$22", normalize_ws: true) expect(page).to have_text("Total US$22", normalize_ws: true) expect(page).to have_text("Payment today US$21", normalize_ws: true) expect(page).to have_text("Payment after completion US$1", normalize_ws: true) choose "20%" expect(page).to have_text("Subtotal US$22", normalize_ws: true) expect(page).to have_text("Tip US$4.40", normalize_ws: true) expect(page).to have_text("Total US$26.40", normalize_ws: true) expect(page).to have_text("Payment today US$25.20", normalize_ws: true) expect(page).to have_text("Payment after completion US$1.20", normalize_ws: true) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = Purchase.last expect(purchase).to be_successful expect(purchase.price_cents).to eq(120) expect(purchase.tip.value_cents).to eq(20) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/generate_invoice_confirmation_page_spec.rb
spec/requests/purchases/generate_invoice_confirmation_page_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Generate invoice confirmation page", type: :system, js: true do before :each do @purchase = create(:purchase) end it "asks to confirm the email address before showing the generate invoice page" do visit "/purchases/#{@purchase.external_id}/generate_invoice" expect(page).to have_current_path(confirm_generate_invoice_path(id: @purchase.external_id)) expect(page).to have_text "Generate invoice" expect(page).to have_text "Please enter the purchase's email address to generate the invoice." fill_in "Email address", with: "wrong.email@example.com" click_on "Confirm email" expect(page).to have_current_path(confirm_generate_invoice_path(id: @purchase.external_id)) expect(page).to have_alert(text: "Incorrect email address. Please try again.") fill_in "Email address", with: @purchase.email click_on "Confirm email" expect(page).to have_current_path(generate_invoice_by_buyer_path(@purchase.external_id, email: @purchase.email)) expect(page).to have_text @purchase.link.name allow_any_instance_of(PDFKit).to receive(:to_pdf).and_return("") invoice_s3_url = "https://s3.example.com/invoice.pdf" s3_double = double(presigned_url: invoice_s3_url) allow_any_instance_of(Purchase).to receive(:upload_invoice_pdf).and_return(s3_double) fill_in "Full name", with: "John Doe" fill_in "Street address", with: "123 Main St" fill_in "City", with: "San Francisco" fill_in "State", with: "CA" fill_in "ZIP code", with: "94101" select "United States", from: "Country" new_window = window_opened_by { click_on "Download" } within_window new_window do expect(page).to have_current_path(invoice_s3_url) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/dispute_evidence_spec.rb
spec/requests/purchases/dispute_evidence_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Dispute evidence page", type: :system, js: true) do let(:dispute) { create(:dispute_formalized, reason: Dispute::REASON_FRAUDULENT) } let(:dispute_evidence) { create(:dispute_evidence, dispute:) } let(:purchase) { dispute_evidence.disputable.purchase_for_dispute_evidence } let(:product) { purchase.link } it "renders the page" do visit purchase_dispute_evidence_path(purchase.external_id) expect(page).to have_text("Submit additional information") expect(page).to have_text("Any additional information you can provide in the next 72 hours will help us win on your behalf.") expect(page).to have_text("The cardholder claims they did not authorize the purchase.") expect(page).to have_text("Why should you win this dispute?") expect(page).not_to have_text("Why is the customer not entitled to a refund?") expect(page).to have_button("Submit", disabled: true) expect(page).to have_selector("[role=listitem] h4", text: "Receipt") end describe "reason_for_winning field" do it "renders filtered options by fraudulent reason" do visit purchase_dispute_evidence_path(purchase.external_id) within_fieldset("Why should you win this dispute?") do expect(page).to have_text("The cardholder withdrew the dispute") expect(page).to have_text("The cardholder was refunded") expect(page).not_to have_text("The transaction was non-refundable") expect(page).not_to have_text("The refund or cancellation request was made after the date allowed by your terms") expect(page).not_to have_text("The product received was as advertised") expect(page).not_to have_text("The cardholder received a credit or voucher") expect(page).not_to have_text("The cardholder received the product or service") expect(page).to have_text("The purchase was made by the rightful cardholder") expect(page).not_to have_text("The purchase is unique") expect(page).not_to have_text("The product, service, event or booking was cancelled or delayed due to a government order (COVID-19)") expect(page).to have_text("Other") end end it "requires a value when Other is selected" do visit purchase_dispute_evidence_path(purchase.external_id) within_fieldset("Why should you win this dispute?") do choose("Other") end expect(page).to have_button("Submit", disabled: true) fill_in("Why should you win this dispute?", with: "Sample text.") expect(page).to have_button("Submit") end it "submits the form successfully" do visit purchase_dispute_evidence_path(purchase.external_id) within_fieldset("Why should you win this dispute?") do choose("The cardholder was refunded") end click_on("Submit") expect(page).to have_text("Thank you!") dispute_evidence.reload expect(dispute_evidence.reason_for_winning).to eq("The cardholder was refunded") end end context "cancellation_rebuttal field" do context "when the purchase is not a subscription" do it "doesn't render the field" do visit purchase_dispute_evidence_path(purchase.external_id) expect(page).not_to have_radio_button("The customer did not request cancellation") end end context "when the purchase is a subscription" do let(:dispute) do create( :dispute_formalized, purchase: create(:membership_purchase), reason: Dispute::REASON_SUBSCRIPTION_CANCELED ) end context "when the dispute reason is subscription_canceled" do it "renders the field" do visit purchase_dispute_evidence_path(purchase.external_id) expect(page).to have_radio_button("The customer did not request cancellation") end it "requires a value when Other is selected" do visit purchase_dispute_evidence_path(purchase.external_id) within_fieldset("Why was the customer's subscription not canceled?") do choose("Other") end expect(page).to have_button("Submit", disabled: true) fill_in("Why was the customer's subscription not canceled?", with: "Sample text.") expect(page).to have_button("Submit") end it "submits the form successfully" do visit purchase_dispute_evidence_path(purchase.external_id) within_fieldset("Why was the customer's subscription not canceled?") do choose("Other") end fill_in("Why was the customer's subscription not canceled?", with: "Cancellation rebuttal") click_on("Submit") expect(page).to have_text("Thank you!") dispute_evidence.reload expect(dispute_evidence.cancellation_rebuttal).to eq("Cancellation rebuttal") end end context "when the dispute reason is not subscription_canceled" do before do dispute.update!(reason: Dispute::REASON_FRAUDULENT) end it "doesn't render the field" do visit purchase_dispute_evidence_path(purchase.external_id) expect(page).not_to have_radio_button("The customer did not request cancellation") end end end end describe "refund_refusal_explanation field" do [Dispute::REASON_CREDIT_NOT_PROCESSED, Dispute::REASON_GENERAL].each do |reason| context "when the dispute reason is #{reason}" do let(:dispute) { create(:dispute_formalized, reason:) } it "renders the field" do visit purchase_dispute_evidence_path(purchase.external_id) fill_in("Why is the customer not entitled to a refund?", with: "Refund refusal explanation") click_on("Submit") expect(page).to have_text("Thank you!") dispute_evidence.reload expect(dispute_evidence.refund_refusal_explanation).to eq("Refund refusal explanation") end end end end describe "customer_communication_file field" do it "submits the form successfully" do # Purging in test ENV returns Aws::S3::Errors::AccessDenied allow_any_instance_of(ActiveStorage::Blob).to receive(:purge).and_return(nil) visit purchase_dispute_evidence_path(purchase.external_id) page.attach_file(file_fixture("smilie.png")) do click_on "Upload customer communication" end wait_for_ajax # For some reason, the signed_id is not passed to the server until we wait for a few seconds (wait_for_ajax is not enough) sleep(3) click_on("Submit") expect(page).to have_text("Thank you!") dispute_evidence.reload expect(dispute_evidence.customer_communication_file.attached?).to be(true) end it "allows the user to delete uploaded file" do visit purchase_dispute_evidence_path(purchase.external_id) page.attach_file(file_fixture("smilie.png")) do click_on "Upload customer communication" end wait_for_ajax expect(page).to have_selector("[role=listitem] h4", text: "Customer communication") expect(page).to have_button("Submit") click_on("Remove") wait_for_ajax expect(page).to have_button("Upload customer communication") expect(page).to have_button("Submit", disabled: true) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product_spec.rb
spec/requests/purchases/product_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Purchase product page", type: :system, js: true) do let(:purchase) { create(:purchase) } let(:product) { purchase.link } it "shows the product for the purchase" do visit purchase_product_path(purchase.external_id) expect(page).to have_text(product.name) end describe "Refund policy" do before do purchase.create_purchase_refund_policy!( title: ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[30], max_refund_period_in_days: 30, fine_print: "This is the fine print of the refund policy." ) end it "renders refund policy" do visit purchase_product_path(purchase.external_id) click_on("30-day money back guarantee") within_modal "30-day money back guarantee" do expect(page).to have_text("This is the fine print of the refund policy.") end end context "when the URL contains refund-policy anchor" do it "renders with the modal open and creates event" do expect do visit purchase_product_path(purchase.external_id, anchor: "refund-policy") end.to change { Event.count }.by(1) within_modal "30-day money back guarantee" do expect(page).to have_text("This is the fine print of the refund policy.") end event = Event.last expect(event.event_name).to eq(Event::NAME_PRODUCT_REFUND_POLICY_FINE_PRINT_VIEW) expect(event.link_id).to eq(product.id) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/generate_invoice_spec.rb
spec/requests/purchases/product/generate_invoice_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Generate invoice for purchase", type: :system, js: true) do context "when purchasing from a product page" do before do @product = create(:product) @product2 = create(:product) end it "shows a link to generate invoice" do visit @product.long_url add_to_cart(@product) visit @product2.long_url add_to_cart(@product2) @product2.update(price_cents: 600) check_out(@product2, error: "The price just changed! Refresh the page for the updated price.") expect(page).to have_content("Need an invoice for this? Generate") purchase = Purchase.last expect(page).to have_link "Generate", href: generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) end end context "when purchasing from user profile" do before do @creator = create(:user) @product = create(:product, user: @creator, unique_permalink: "aa") @product2 = create(:product, user: @creator, unique_permalink: "bb") end it "shows a link to generate invoice" do expect do visit @product.long_url add_to_cart(@product) visit @product2.long_url add_to_cart(@product2) @product2.update(price_cents: 600) check_out(@product2, error: "The price just changed! Refresh the page for the updated price.") purchase = Purchase.last expect(page).to have_link "Generate", href: generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) end.to change { Purchase.successful.count }.by(1) end end describe "generating an invoice" do before do @creator = create(:user, name: "US Seller") @product = create(:product, user: @creator) @physical_product = create(:physical_product, user: @creator) end it "allows the user to customize and download invoice" do purchase = create(:physical_purchase, link: @physical_product) visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) # Form should be pre-filled with existing purchase info expect(find_field("Full name").value).to eq(purchase.full_name) expect(find_field("Street address").value).to eq(purchase.street_address) expect(find_field("City").value).to eq(purchase.city) expect(find_field("State").value).to eq(purchase.state) expect(find_field("ZIP code").value).to eq(purchase.zip_code) # Edit name and address fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..") do expect(page).not_to have_content("VAT Registration Number") expect(page).not_to have_content(GUMROAD_VAT_REGISTRATION_NUMBER) expect(page).to have_content(purchase.seller.name_or_username) expect(page).to have_content(purchase.seller.email) expect(page).to have_content("Products supplied by Gumroad.") end within find("h5", text: "Invoice").first(:xpath, ".//..") do expect(page).to have_content "Wonderful Alice Crooked St. Wonderland, CA 12345 United States", normalize_ws: true expect(page).not_to have_content("Additional notes") end fill_in("Additional notes", with: "Custom information.") within find("h5", text: "Invoice").first(:xpath, ".//..") do expect(page).to have_content "Additional notes" expect(page).to have_content "Custom information." end click_on "Download" wait_for_ajax invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include("Wonderful Alice") expect(pdf_text).to include("Crooked St.") expect(pdf_text).to include("Wonderland, CA, 12345 United States") expect(pdf_text).to include("Item purchased") expect(pdf_text).to include(purchase.email) expect(pdf_text).to include(purchase.link.name) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include("Additional notes") expect(pdf_text).to include("Custom information.") expect(pdf_text).to_not include("VAT Registration Number") expect(pdf_text).to_not include(GUMROAD_VAT_REGISTRATION_NUMBER) expect(pdf_text).to have_content("Products supplied by Gumroad.") end it "shows Gumroad's VAT registration number for EU purchases" do purchase = create(:purchase, link: @product, country: "Italy", quantity: 2) visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("VAT Registration Number") expect(page).to have_content(GUMROAD_VAT_REGISTRATION_NUMBER) end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include(purchase.email) expect(pdf_text).to include("Item purchased") expect(pdf_text).to include("#{purchase.link.name} ×") expect(pdf_text).to include(purchase.quantity.to_s) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include("VAT Registration Number") expect(pdf_text).to include(GUMROAD_VAT_REGISTRATION_NUMBER) end it "shows Gumroad's ABN for Australian purchases" do purchase = create(:purchase, link: @product, country: "Australia") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("Australian Business Number") expect(page).to have_content(GUMROAD_AUSTRALIAN_BUSINESS_NUMBER) end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include(purchase.email) expect(pdf_text).to include("Item purchased") expect(pdf_text).to include(purchase.link.name) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include(purchase.quantity.to_s) expect(pdf_text).to include("Australian Business Number") expect(pdf_text).to include(GUMROAD_AUSTRALIAN_BUSINESS_NUMBER) end it "shows Gumroad's QST registration number for recommended Canada purchases" do purchase = create(:purchase, link: @product, country: "Canada", was_product_recommended: true) visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("QST Registration Number") expect(page).to have_content(GUMROAD_QST_REGISTRATION_NUMBER) expect(page).to have_content("Canada GST Registration Number") expect(page).to have_content(GUMROAD_CANADA_GST_REGISTRATION_NUMBER) end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include(purchase.email) expect(pdf_text).to include("Item purchased") expect(pdf_text).to include(purchase.link.name) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include(purchase.quantity.to_s) expect(pdf_text).to include("QST Registration Number") expect(pdf_text).to include(GUMROAD_QST_REGISTRATION_NUMBER) expect(pdf_text).to include("Canada GST Registration Number") expect(pdf_text).to include(GUMROAD_CANADA_GST_REGISTRATION_NUMBER) end it "shows Gumroad's Norway VAT registration for Norwegian purchases" do purchase = create(:purchase, link: @product, country: "Norway") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("Norway VAT Registration") expect(page).to have_content(GUMROAD_NORWAY_VAT_REGISTRATION) end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include(purchase.email) expect(pdf_text).to include("Item purchased") expect(pdf_text).to include(purchase.link.name) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include("Norway VAT Registration") expect(pdf_text).to include(GUMROAD_NORWAY_VAT_REGISTRATION) end it "shows Gumroad's TRN for Bahrain purchases" do purchase = create(:purchase, link: @product, country: "Bahrain") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("VAT Registration Number") expect(page).to have_content(GUMROAD_OTHER_TAX_REGISTRATION) end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include(purchase.email) expect(pdf_text).to include("Item purchased") expect(pdf_text).to include(purchase.link.name) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include("VAT Registration Number") expect(pdf_text).to include(GUMROAD_OTHER_TAX_REGISTRATION) end it "shows Gumroad's KRA PIN for Kenya purchases" do purchase = create(:purchase, link: @product, country: "Kenya") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("VAT Registration Number") expect(page).to have_content(GUMROAD_OTHER_TAX_REGISTRATION) end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include(purchase.email) expect(pdf_text).to include("Item purchased") expect(pdf_text).to include(purchase.link.name) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include("VAT Registration Number") expect(pdf_text).to include(GUMROAD_OTHER_TAX_REGISTRATION) end it "shows Gumroad's FIRS TIN for Nigeria purchases" do purchase = create(:purchase, link: @product, country: "Nigeria") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("VAT Registration Number") expect(page).to have_content(GUMROAD_OTHER_TAX_REGISTRATION) end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include(purchase.email) expect(pdf_text).to include("Item purchased") expect(pdf_text).to include(purchase.link.name) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include("VAT Registration Number") expect(pdf_text).to include(GUMROAD_OTHER_TAX_REGISTRATION) end it "shows Gumroad's TRA TIN for Tanzania purchases" do purchase = create(:purchase, link: @product, country: "Tanzania") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("VAT Registration Number") expect(page).to have_content(GUMROAD_OTHER_TAX_REGISTRATION) end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include(purchase.email) expect(pdf_text).to include("Item purchased") expect(pdf_text).to include(purchase.link.name) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include("VAT Registration Number") expect(pdf_text).to include(GUMROAD_OTHER_TAX_REGISTRATION) end it "shows Gumroad's VAT registration number for Oman purchases" do purchase = create(:purchase, link: @product, country: "Oman") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("VAT Registration Number") expect(page).to have_content(GUMROAD_OTHER_TAX_REGISTRATION) end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include(purchase.email) expect(pdf_text).to include("Item purchased") expect(pdf_text).to include(purchase.link.name) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include("VAT Registration Number") expect(pdf_text).to include(GUMROAD_OTHER_TAX_REGISTRATION) end it "shows Gumroad's Tax Registration Number for other countries that collect tax on all products" do purchase = create(:purchase, link: @product, country: "Iceland") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("VAT Registration Number") expect(page).to have_content(GUMROAD_OTHER_TAX_REGISTRATION) end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include(purchase.email) expect(pdf_text).to include("Item purchased") expect(pdf_text).to include(purchase.link.name) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include("VAT Registration Number") expect(pdf_text).to include(GUMROAD_OTHER_TAX_REGISTRATION) end it "shows Gumroad's Tax Registration Number for other countries that collect tax on digital products" do purchase = create(:purchase, link: @product, country: "Chile") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("VAT Registration Number") expect(page).to have_content(GUMROAD_OTHER_TAX_REGISTRATION) end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to include(purchase.external_id_numeric.to_s) expect(pdf_text).to include(purchase.email) expect(pdf_text).to include("Item purchased") expect(pdf_text).to include(purchase.link.name) expect(pdf_text).to include(purchase.formatted_non_refunded_total_transaction_amount) expect(pdf_text).to include("VAT Registration Number") expect(pdf_text).to include(GUMROAD_OTHER_TAX_REGISTRATION) end it "shows Gumroad as the supplier for a physical product sale" do purchase = create(:physical_purchase, link: @physical_product, country: "Australia") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("Supplier\nGumroad, Inc") expect(page).to have_content(purchase.seller.name_or_username) expect(page).to have_content(purchase.seller.email) expect(page).to have_content("Products supplied by Gumroad.") end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).not_to have_content("Supplier: Gumroad") expect(pdf_text).to have_content(purchase.seller.name_or_username) expect(pdf_text).to have_content(purchase.seller.email) expect(pdf_text).to have_content("Products supplied by Gumroad.") end it "shows Gumroad as the supplier for a non-physical product sale to the US" do purchase = create(:purchase, link: @product, country: "United States") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content(purchase.seller.name_or_username) expect(page).to have_content(purchase.seller.email) expect(page).to have_content("Products supplied by Gumroad.") end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish expect(pdf_text).to have_content(purchase.seller.name_or_username) expect(pdf_text).to have_content(purchase.seller.email) expect(pdf_text).to have_content("Products supplied by Gumroad.") end it "shows Gumroad as the supplier for a sale via Gumroad Discover" do purchase = create(:purchase, link: @product, country: "United States", was_product_recommended: true, recommended_by: "discover") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("Gumroad, Inc") expect(page).not_to have_content("Products supplied by #{purchase.seller.display_name}.") end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish within find("h5", text: "Supplier").first(:xpath, ".//..") do expect(pdf_text).to have_content("Gumroad, Inc.") expect(pdf_text).not_to have_content("Products supplied by #{purchase.seller.display_name}.") end end it "shows Gumroad as the supplier for a physical product sale" do purchase = create(:physical_purchase, link: @physical_product, country: "Australia") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("Supplier\nGumroad, Inc") expect(page).to have_content(purchase.seller.name_or_username) expect(page).to have_content(purchase.seller.email) expect(page).to have_content("Products supplied by Gumroad.") end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish within find("h5", text: "Supplier").first(:xpath, ".//..") do expect(pdf_text).to have_content("Gumroad, Inc.") expect(pdf_text).to have_content(purchase.seller.name_or_username) expect(pdf_text).to have_content(purchase.seller.email) expect(pdf_text).to have_content("Products supplied by Gumroad.") end end it "shows Gumroad as the supplier for a non-physical product sale to the US" do purchase = create(:purchase, link: @product, country: "United States") visit generate_invoice_by_buyer_path(purchase.external_id, email: purchase.email) fill_in("Full name", with: "Wonderful Alice") fill_in("Street address", with: "Crooked St.") fill_in("City", with: "Wonderland") fill_in("State", with: "CA") fill_in("ZIP code", with: "12345") within find("h5", text: "Supplier").first(:xpath, ".//..//..") do expect(page).to have_content("Supplier\nGumroad, Inc") expect(page).to have_content(purchase.seller.name_or_username) expect(page).to have_content(purchase.seller.email) expect(page).to have_content("Products supplied by Gumroad.") end click_on "Download" invoice_url = find_link("here")[:href] reader = PDF::Reader.new(URI.open(invoice_url)) expect(reader.pages.size).to be(1) pdf_text = reader.page(1).text.squish within find("h5", text: "Supplier").first(:xpath, ".//..") do expect(pdf_text).to have_content("Gumroad, Inc.") expect(pdf_text).to have_content(purchase.seller.name_or_username) expect(pdf_text).to have_content(purchase.seller.email) expect(pdf_text).to have_content("Products supplied by Gumroad.") end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/custom_fields_spec.rb
spec/requests/purchases/product/custom_fields_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Product checkout - custom fields", type: :system, js: true) do before do @product = create(:product) end it "prefills custom fields from query params, except for terms acceptance" do @product.custom_fields << [ create(:custom_field, type: "text", name: "your nickname"), create(:custom_field, type: "checkbox", name: "extras"), create(:custom_field, type: "terms", name: "http://example.com") ] @product.save! visit "/l/#{@product.unique_permalink}?your%20nickname=test&extras=true&#{CGI.escape "http://example.com"}=true" add_to_cart(@product) wait_for_ajax expect(page).to have_field("your nickname (optional)", with: "test") expect(page).to have_checked_field("extras (optional)") expect(page).not_to have_checked_field("I accept Terms and Conditions") end it "validates required text and checkbox fields, and always validates terms acceptance, lets purchase when all valid" do @product.custom_fields << [ create(:custom_field, type: "text", name: "your nickname", required: true), create(:custom_field, type: "checkbox", name: "extras", required: true), create(:custom_field, type: "terms", name: "http://example.com") ] @product.save! visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, error: true) expect(find_field("your nickname")["aria-invalid"]).to eq "true" fill_in "your nickname", with: "test" check_out(@product, error: true) expect(find_field("extras")["aria-invalid"]).to eq "true" check "extras" check_out(@product, error: true) expect(find_field("I accept")["aria-invalid"]).to eq "true" check "I accept" check_out(@product) purchase = Purchase.last expect(purchase.custom_fields).to eq( [ { name: "your nickname", value: "test", type: CustomField::TYPE_TEXT }, { name: "extras", value: true, type: CustomField::TYPE_CHECKBOX }, { name: "http://example.com", value: true, type: CustomField::TYPE_TERMS } ] ) end it "does not require optional inputs to be filled or optional checkboxes to be checked, purchase goes through" do @product.custom_fields << [ create(:custom_field, type: "text", name: "your nickname"), create(:custom_field, type: "checkbox", name: "extras"), ] @product.save! visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product) purchase = Purchase.last expect(purchase.custom_fields).to eq([{ name: "extras", value: false, type: CustomField::TYPE_CHECKBOX }]) end context "with multiple products" do let(:seller1) { create(:user, custom_fields: [create(:custom_field, name: "Full Name", global: true, required: true)]) } let(:seller2) { create(:user, custom_fields: [create(:custom_field, name: "Full Name", global: true)]) } let(:seller1_product1) { create(:product, name: "Product 1-1", user: seller1) } let(:seller1_product2) { create(:product, name: "Product 1-2", user: seller1) } let(:seller2_product1) { create(:product, name: "Product 2-1", user: seller2) } let(:seller2_product2) { create(:product, name: "Product 2-2", user: seller2) } before do create(:custom_field, type: CustomField::TYPE_CHECKBOX, name: "Business?", seller: seller1, products: [seller1_product1, seller1_product2]) create(:custom_field, type: CustomField::TYPE_TERMS, name: "https://example.com", seller: seller2, products: [seller2_product1, seller2_product2], collect_per_product: true) create(:custom_field, type: CustomField::TYPE_TEXT, name: "Only one product", seller: seller2, products: [seller2_product1], collect_per_product: true) end it "groups custom fields by seller" do [seller1_product1, seller1_product2, seller2_product1, seller2_product2].each do |product| visit product.long_url add_to_cart(product) end within_section seller1.username, section_element: :section do fill_in "Full Name", with: "John Doe" expect(page).to have_unchecked_field("Business? (optional)") expect(page).not_to have_selector(:fieldset, seller1_product1.name) expect(page).not_to have_selector(:fieldset, seller1_product2.name) end within_section seller2.username, section_element: :section do expect(page).to have_field("Full Name") within_fieldset(seller2_product1.name) do check "I accept" fill_in "Only one product", with: "test" end within_fieldset(seller2_product2.name) do check "I accept" end end check_out(seller1_product1) order = Order.last expect(order.purchases.find_by(link: seller1_product1).custom_fields).to eq( [{ name: "Full Name", value: "John Doe", type: CustomField::TYPE_TEXT }, { name: "Business?", value: false, type: CustomField::TYPE_CHECKBOX }] ) expect(order.purchases.find_by(link: seller1_product2).custom_fields).to eq( [{ name: "Full Name", value: "John Doe", type: CustomField::TYPE_TEXT }, { name: "Business?", value: false, type: CustomField::TYPE_CHECKBOX }] ) expect(order.purchases.find_by(link: seller2_product1).custom_fields).to eq( [{ name: "https://example.com", value: true, type: CustomField::TYPE_TERMS }, { name: "Only one product", value: "test", type: CustomField::TYPE_TEXT }] ) expect(order.purchases.find_by(link: seller2_product2).custom_fields).to eq( [{ name: "https://example.com", value: true, type: CustomField::TYPE_TERMS }] ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/subscription_payment_options_spec.rb
spec/requests/purchases/product/subscription_payment_options_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Purchasing a multi-recurrence subscription product from product page", type: :system, js: true) do before do @product = create(:subscription_product_with_versions, price_cents: 10_00) @price_yearly = create(:price, link: @product, price_cents: 70_00, recurrence: BasePrice::Recurrence::YEARLY) end it "allows the product to be bought" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product, option: "Untitled 1") check_out(@product) expect(Purchase.last.price_cents).to eq(10_00) expect(Subscription.last.period).to eq(1.month) end it "shows the duration, allow the product to be bought, and create correct subscription" do @product.update_attribute(:duration_in_months, 12) visit "/l/#{@product.unique_permalink}" add_to_cart(@product, option: "Untitled 1") check_out(@product) expect(Purchase.last.price_cents).to eq(10_00) expect(Subscription.last.period).to eq(1.month) expect(Subscription.last.charge_occurrence_count).to eq(12) end it "allows the product to be bought with a different payment option" do visit "/l/#{@product.unique_permalink}" expect(page).to have_radio_button(text: "$10") select "Yearly", from: "Recurrence" expect(page).to have_radio_button(text: "$70") add_to_cart(@product, option: "Untitled 1") check_out(@product) expect(Purchase.last.price_cents).to eq(70_00) expect(Subscription.last.period).to eq(12.months) end it "allows the product to be bought with a different payment option with an offer code" do offer_code = create(:offer_code, products: [@product], amount_cents: nil, amount_percentage: 50, code: "half") visit "/l/#{@product.unique_permalink}/#{offer_code.code}" expect(page).to have_radio_button(text: "$10") select "Yearly", from: "Recurrence" expect(page).to have_radio_button(text: "$70") expect(page).to have_selector("[role='status']", text: "50% off will be applied at checkout (Code #{offer_code.code.upcase})") expect(page).to have_radio_button("Untitled 1", text: /\$70\s+\$35/) expect(page).to have_radio_button("Untitled 2", text: /\$70\s+\$35/) add_to_cart(@product, option: "Untitled 1", offer_code:) check_out(@product) expect(Purchase.last.price_cents).to eq(35_00) expect(Subscription.last.period).to eq(12.months) end it "allows the buyer to switch back and forth and still buy the correct occurence" do visit "/l/#{@product.unique_permalink}" select "Yearly", from: "Recurrence" add_to_cart(@product, recurrence: "Monthly", option: "Untitled 1") check_out(@product) expect(Purchase.last.price_cents).to eq(10_00) expect(Subscription.last.period).to eq(1.month) end it "allows the buyer to purchase a fixed length subscription with an offer code and have the correct charge occurrence message" do @product.duration_in_months = 12 @product.save @product.user.update!(display_offer_code_field: true) code = "offer" create(:offer_code, code:, products: [@product], amount_percentage: 50, amount_cents: nil) visit "/l/#{@product.unique_permalink}" select "Yearly", from: "Recurrence" add_to_cart(@product, recurrence: "Monthly", option: "Untitled 1") expect(page).to have_text("Total US$10", normalize_ws: true) fill_in "Discount code", with: code click_on "Apply" expect(page).to have_text("Total US$5", normalize_ws: true) check_out(@product) expect(Purchase.last.price_cents).to eq(5_00) expect(Subscription.last.period).to eq(1.month) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/taxes_spec.rb
spec/requests/purchases/product/taxes_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Product Page - Tax Scenarios", type: :system, js: true) do describe "sales tax", shipping: true do before do @creator = create(:user_with_compliance_info) @product = create(:physical_product, user: @creator, require_shipping: true, price_cents: 500_00) end it "calls the tax endpoint for a real zip code that doesn't show in the enterprise zip codes database" do visit("/l/#{@product.unique_permalink}") add_to_cart(@product) check_out(@product, address: { street: "3029 W Sherman Rd", city: "San Tan Valley", state: "AZ", zip_code: "85144", country: "US" }, should_verify_address: true) do expect(page).to have_text("Subtotal US$500", normalize_ws: true) expect(page).to have_text("Sales tax US$53.50", normalize_ws: true) end expect(page).to have_text("Your purchase was successful!") expect(Purchase.successful.count).to eq 1 new_purchase = Purchase.last expect(new_purchase.link_id).to eq(@product.id) expect(new_purchase.price_cents).to eq(500_00) expect(new_purchase.total_transaction_cents).to eq(55_350) expect(new_purchase.fee_cents).to eq(65_30) # 500_00 * 0.129 + 50c + 30c expect(new_purchase.tax_cents).to eq(0) expect(new_purchase.gumroad_tax_cents).to eq(53_50) expect(new_purchase.was_tax_excluded_from_price).to eq(true) expect(new_purchase.was_purchase_taxable).to eq(true) expect(new_purchase.zip_tax_rate).to be_nil expect(new_purchase.purchase_sales_tax_info).to_not be(nil) expect(new_purchase.purchase_sales_tax_info.ip_address).to_not be(new_purchase.ip_address) expect(new_purchase.purchase_sales_tax_info.elected_country_code).to eq(Compliance::Countries::USA.alpha2) expect(new_purchase.purchase_sales_tax_info.country_code).to eq(Compliance::Countries::USA.alpha2) expect(new_purchase.purchase_sales_tax_info.card_country_code).to eq(Compliance::Countries::USA.alpha2) expect(new_purchase.purchase_sales_tax_info.postal_code).to eq("85144") end describe "price modifiers" do it "re-evaluates price and tax when there are variants" do variant_category = create(:variant_category, link: @product, title: "type") variants = [["type 1", 150], ["type 2", 200]] variants.each do |name, price_difference_cents| create(:variant, variant_category:, name:, price_difference_cents:) end Product::SkusUpdaterService.new(product: @product).perform Sku.not_is_default_sku.first.update_attribute(:price_difference_cents, 150) visit("/l/#{@product.unique_permalink}") add_to_cart(@product, option: "type 1") check_out(@product, address: { street: "3029 W Sherman Rd", city: "San Tan Valley", state: "AZ", zip_code: "85144" }, should_verify_address: true) do expect(page).to have_text("Subtotal US$501.50", normalize_ws: true) expect(page).to have_text("Sales tax US$53.66", normalize_ws: true) expect(page).to have_text("Total US$555.16", normalize_ws: true) end expect(page).to have_text("Your purchase was successful!") expect(Purchase.successful.count).to eq 1 new_purchase = Purchase.last expect(new_purchase.link_id).to eq(@product.id) expect(new_purchase.price_cents).to eq(501_50) expect(new_purchase.total_transaction_cents).to eq(555_16) expect(new_purchase.fee_cents).to eq(65_49) # 535_10 * 0.129 + 50c + 30c expect(new_purchase.gumroad_tax_cents).to eq(53_66) expect(new_purchase.tax_cents).to eq(0) expect(new_purchase.was_tax_excluded_from_price).to eq(true) expect(new_purchase.was_purchase_taxable).to eq(true) expect(new_purchase.zip_tax_rate).to be_nil expect(new_purchase.purchase_sales_tax_info).to_not be(nil) expect(new_purchase.purchase_sales_tax_info.ip_address).to_not be(new_purchase.ip_address) expect(new_purchase.purchase_sales_tax_info.elected_country_code).to eq(Compliance::Countries::USA.alpha2) expect(new_purchase.purchase_sales_tax_info.country_code).to eq(Compliance::Countries::USA.alpha2) expect(new_purchase.purchase_sales_tax_info.card_country_code).to eq(Compliance::Countries::USA.alpha2) expect(new_purchase.purchase_sales_tax_info.postal_code).to eq("85144") end it "re-evaluates price and tax when an offer code is applied - code in url" do offer_code = create(:offer_code, products: [@product], amount_cents: 10_000, code: "taxoffer") visit "/l/#{@product.unique_permalink}/taxoffer" add_to_cart(@product, offer_code:) check_out(@product, address: { street: "3029 W Sherman Rd", city: "San Tan Valley", state: "AZ", zip_code: "85144" }, should_verify_address: true) do expect(page).to have_text("$500") expect(page).to have_text("Subtotal US$500", normalize_ws: true) expect(page).to have_text("Sales tax US$42.80", normalize_ws: true) expect(page).to have_text("Discounts taxoffer US$-100", normalize_ws: true) expect(page).to have_text("Total US$442.80", normalize_ws: true) end expect(page).to have_text("Your purchase was successful!") expect(Purchase.successful.count).to eq 1 new_purchase = Purchase.last expect(new_purchase.link_id).to eq(@product.id) expect(new_purchase.price_cents).to eq(400_00) expect(new_purchase.total_transaction_cents).to eq(442_80) expect(new_purchase.fee_cents).to eq(52_40) # 434_50 * 0.129 + 50c + 30c expect(new_purchase.gumroad_tax_cents).to eq(42_80) expect(new_purchase.tax_cents).to eq(0) expect(new_purchase.was_tax_excluded_from_price).to eq(true) expect(new_purchase.was_purchase_taxable).to eq(true) expect(new_purchase.zip_tax_rate).to be_nil expect(new_purchase.purchase_sales_tax_info).to_not be(nil) expect(new_purchase.purchase_sales_tax_info.ip_address).to_not be(new_purchase.ip_address) expect(new_purchase.purchase_sales_tax_info.elected_country_code).to eq(Compliance::Countries::USA.alpha2) expect(new_purchase.purchase_sales_tax_info.country_code).to eq(Compliance::Countries::USA.alpha2) expect(new_purchase.purchase_sales_tax_info.card_country_code).to eq(Compliance::Countries::USA.alpha2) expect(new_purchase.purchase_sales_tax_info.postal_code).to eq("85144") end it "re-evaluates price and tax when a tip is added" do @product.user.update!(tipping_enabled: true) visit @product.long_url add_to_cart(@product) fill_checkout_form(@product, address: { street: "3029 W Sherman Rd", city: "San Tan Valley", state: "AZ", zip_code: "85144" }) expect(page).to have_text("Subtotal US$500", normalize_ws: true) expect(page).to_not have_text("Tip US$", normalize_ws: true) expect(page).to have_text("Sales tax US$53.50", normalize_ws: true) expect(page).to have_text("Total US$553.50", normalize_ws: true) choose "10%" wait_for_ajax expect(page).to have_text("Subtotal US$500", normalize_ws: true) expect(page).to have_text("Tip US$50", normalize_ws: true) expect(page).to have_text("Sales tax US$58.85", normalize_ws: true) expect(page).to have_text("Total US$608.85", normalize_ws: true) click_on "Pay" if page.has_text?("We are unable to verify your shipping address. Is your address correct?", wait: 5) click_on "Yes, it is" elsif page.has_text?("You entered this address:", wait: 5) && page.has_text?("We recommend using this format:", wait: 5) click_on "No, continue" end expect(page).to have_alert(text: "Your purchase was successful!") purchase = Purchase.last expect(purchase.link_id).to eq(@product.id) expect(purchase.price_cents).to eq(550_00) expect(purchase.total_transaction_cents).to eq(608_85) expect(purchase.fee_cents).to eq(71_75) # 597_44 * 0.129 + 50c + 30c expect(purchase.gumroad_tax_cents).to eq(58_85) expect(purchase.tax_cents).to eq(0) expect(purchase.was_tax_excluded_from_price).to eq(true) expect(purchase.was_purchase_taxable).to eq(true) expect(purchase.zip_tax_rate).to be_nil expect(purchase.purchase_sales_tax_info).to_not be(nil) expect(purchase.purchase_sales_tax_info.ip_address).to_not be(purchase.ip_address) expect(purchase.purchase_sales_tax_info.elected_country_code).to eq(Compliance::Countries::USA.alpha2) expect(purchase.purchase_sales_tax_info.country_code).to eq(Compliance::Countries::USA.alpha2) expect(purchase.purchase_sales_tax_info.card_country_code).to eq(Compliance::Countries::USA.alpha2) expect(purchase.purchase_sales_tax_info.postal_code).to eq("85144") expect(purchase.tip.value_cents).to eq(50_00) end end end describe "US sales tax", taxjar: true do it "calculates and charges sales tax when WI customer makes purchase" do product = create(:product, price_cents: 100_00) visit "/l/#{product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(product) check_out(product, zip_code: "53703") do expect(page).to have_text("Subtotal US$100", normalize_ws: true) expect(page).to have_text("Sales tax US$5.50", normalize_ws: true) expect(page).to have_text("Total US$105.50", normalize_ws: true) end purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(105_50) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(5_50) expect(purchase.was_purchase_taxable).to be(true) end it "calculates and charges sales tax when WI customer makes purchase of a physical product" do product = create(:physical_product, price_cents: 100_00) visit "/l/#{product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(product) check_out(product, address: { street: "1 S Pinckney St", state: "WI", city: "Madison", zip_code: "53703" }, should_verify_address: true) do expect(page).to have_text("Subtotal US$100", normalize_ws: true) expect(page).to have_text("Sales tax US$5.50", normalize_ws: true) expect(page).to have_text("Total US$105.50", normalize_ws: true) end purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(105_50) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(5_50) expect(purchase.was_purchase_taxable).to be(true) end it "calculates and charges sales tax when WA customer makes purchase" do product = create(:product, price_cents: 100_00) visit "/l/#{product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(product) check_out(product, zip_code: "98121") do expect(page).to have_text("Subtotal US$100", normalize_ws: true) expect(page).to have_text("Sales tax US$10.35", normalize_ws: true) expect(page).to have_text("Total US$110.35", normalize_ws: true) end purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(110_35) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(10_35) expect(purchase.was_purchase_taxable).to be(true) end it "calculates and charges sales tax when WA customer makes purchase of a physical product" do product = create(:physical_product, price_cents: 100_00) visit "/l/#{product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(product) check_out(product, address: { street: "2031 7th Ave", state: "WA", city: "Seattle", zip_code: "98121" }, should_verify_address: true) do expect(page).to have_text("Subtotal US$100", normalize_ws: true) expect(page).to have_text("Sales tax US$10.35", normalize_ws: true) expect(page).to have_text("Total US$110.35", normalize_ws: true) end purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(110_35) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(10_35) expect(purchase.was_purchase_taxable).to be(true) end it "calculates and charges sales tax when WI customer purchases a non-physical product" do product = create(:product, price_cents: 100_00) visit "/l/#{product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(product) check_out(product, zip_code: "53703") do expect(page).to have_text("Subtotal US$100", normalize_ws: true) expect(page).to have_text("Sales tax US$5.50", normalize_ws: true) expect(page).to have_text("Total US$105.50", normalize_ws: true) end purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(105_50) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(5_50) expect(purchase.was_purchase_taxable).to be(true) end it "calculates and charges sales tax when WA customer purchases a non-physical product" do product = create(:product, price_cents: 100_00) visit "/l/#{product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(product) check_out(product, zip_code: "98121") do expect(page).to have_text("Subtotal US$100", normalize_ws: true) expect(page).to have_text("Sales tax US$10.35", normalize_ws: true) expect(page).to have_text("Total US$110.35", normalize_ws: true) end purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(110_35) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(10_35) expect(purchase.was_purchase_taxable).to be(true) end end describe "VAT" do before do Capybara.current_session.driver.browser.manage.delete_all_cookies create(:zip_tax_rate, country: "IT", zip_code: nil, state: nil, combined_rate: 0.22, is_seller_responsible: false) allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("2.47.255.255") # Italy @vat_link = create(:product, price_cents: 100_00) end it "does not show VAT in the ribbon / sticker and charges the right amount" do visit "/l/#{@vat_link.unique_permalink}" expect(page).to have_selector("[itemprop='offers']", text: "$100") add_to_cart(@vat_link) check_out(@vat_link, zip_code: nil, credit_card: { number: "4000003800000008" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(122_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(22_00) expect(purchase.was_purchase_taxable).to be(true) end it "allows entry of VAT ID and doesn't charge VAT" do visit "/l/#{@vat_link.unique_permalink}" expect(page).to have_selector("[itemprop='offers']", text: "$100") add_to_cart(@vat_link) expect(page).to have_text("VAT US$22", normalize_ws: true) check_out(@vat_link, vat_id: "NL860999063B01", zip_code: nil, credit_card: { number: "4000003800000008" }) do expect(page).not_to have_text("VAT US$", normalize_ws: true) end purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(100_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(0) expect(purchase.was_purchase_taxable).to be(false) expect(purchase.purchase_sales_tax_info.business_vat_id).to eq("NL860999063B01") # Check VAT ID is present on the invoice as well visit purchase.receipt_url click_on("Generate") expect(page).to(have_text("NL860999063B01")) end context "for a tiered membership product" do let(:product) { create(:membership_product_with_preset_tiered_pricing) } it "displays the correct VAT and charges the right amount" do visit "/l/#{product.unique_permalink}" add_to_cart(product, option: "First Tier") check_out(product, zip_code: nil, credit_card: { number: "4000003800000008" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(3_66) expect(purchase.price_cents).to eq(3_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(66) expect(purchase.was_purchase_taxable).to be(true) end it "allows entry of VAT ID and doesn't charge VAT" do visit "/l/#{product.unique_permalink}" add_to_cart(product, option: "First Tier") expect(page).to(have_text("VAT US$0.66", normalize_ws: true)) check_out(product, vat_id: "NL860999063B01", zip_code: nil, credit_card: { number: "4000003800000008" }) do expect(page).not_to have_text("VAT US$", normalize_ws: true) end purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(3_00) expect(purchase.price_cents).to eq(3_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(0) expect(purchase.was_purchase_taxable).to be(false) expect(purchase.purchase_sales_tax_info.business_vat_id).to eq("NL860999063B01") # Check VAT ID is present on the invoice as well visit purchase.receipt_url click_on("Generate") expect(page).to(have_text("NL860999063B01")) end end it "charges the right amount for a VAT country where the GeoIp2 lookup doesn't match IsoCountryCodes" do create(:zip_tax_rate, country: "CZ", zip_code: nil, state: nil, combined_rate: 0.21, is_seller_responsible: false) allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("93.99.163.13") # Czechia visit "/l/#{@vat_link.unique_permalink}" expect(page).to have_text("$100") add_to_cart(@vat_link) check_out(@vat_link, zip_code: nil, credit_card: { number: "4000002030000002" }) purchase = Purchase.last expect(purchase.country).to eq("Czechia") expect(purchase.total_transaction_cents).to eq(121_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(21_00) expect(purchase.was_purchase_taxable).to be(true) end it "charges VAT for a physical product" do product = create(:physical_product, price_cents: 100_00) visit "/l/#{product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(product) check_out(product, address: { street: "Via del Governo Vecchio, 87", city: "Rome", state: "Latium", zip_code: "00186" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(122_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(22_00) expect(purchase.was_purchase_taxable).to be(true) end it "displays the correct VAT and charges the right amount" do product = create(:physical_product, price_cents: 100_00) visit "/l/#{product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(product) check_out(product, address: { street: "Via del Governo Vecchio, 87", city: "Rome", state: "Latium", zip_code: "00186" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(122_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(22_00) expect(purchase.was_purchase_taxable).to be(true) end end describe "GST" do before do Capybara.current_session.driver.browser.manage.delete_all_cookies create(:zip_tax_rate, country: "AU", zip_code: nil, state: nil, combined_rate: 0.10, is_seller_responsible: false) allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("103.251.65.149") # Australia @product = create(:product, price_cents: 100_00) create(:user_compliance_info_empty, user: @product.user, first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca", zip_code: "94107", country: Compliance::Countries::USA.common_name) @product.save! end it "applies the GST" do visit "/l/#{@product.unique_permalink}" expect(page).to have_selector("[itemprop='price']", text: "$100") add_to_cart(@product) expect(page).to have_text("Total US$110", normalize_ws: true) check_out(@product, zip_code: nil, credit_card: { number: "4000000360000006" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(110_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(10_00) expect(purchase.was_purchase_taxable).to be(true) end it "allows entry of ABN ID and doesn't charge GST" do visit "/l/#{@product.unique_permalink}" expect(page).to have_selector("[itemprop='offers']", text: "$100") add_to_cart(@product) expect(page).to have_text("GST") check_out(@product, abn_id: "51824753556", zip_code: nil, credit_card: { number: "4000000360000006" }) do expect(page).not_to have_text("GST") end purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(100_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(0) expect(purchase.was_purchase_taxable).to be(false) expect(purchase.purchase_sales_tax_info.business_vat_id).to eq("51824753556") # Check ABN ID is present on the invoice as well visit purchase.receipt_url click_on("Generate") expect(page).to(have_text("51824753556")) end it "applies GST for physical products" do @product = create(:physical_product, price_cents: 100_00) create(:user_compliance_info_empty, user: @product.user, first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca", zip_code: "94107", country: Compliance::Countries::USA.common_name) @product.save! visit "/l/#{@product.unique_permalink}" expect(page).to have_selector("[itemprop='offers']", text: "$100") add_to_cart(@product) expect(page).to have_text("Total US$110", normalize_ws: true) check_out(@product, address: { street: "278 Rocky Point Rd", city: "Ramsgate", state: "NSW", zip_code: "2217" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(110_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(10_00) expect(purchase.was_purchase_taxable).to be(true) end it "applies GST for physical products" do product = create(:physical_product, price_cents: 100_00) create(:user_compliance_info_empty, user: product.user, first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca", zip_code: "94107", country: Compliance::Countries::USA.common_name) product.save! visit "/l/#{product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(product) expect(page).to have_text("Total US$110", normalize_ws: true) check_out(product, address: { street: "278 Rocky Point Rd", city: "Ramsgate", state: "NSW", zip_code: "2217" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(110_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(10_00) expect(purchase.was_purchase_taxable).to be(true) end end describe "Singapore GST" do before do Capybara.current_session.driver.browser.manage.delete_all_cookies create(:zip_tax_rate, country: "SG", zip_code: nil, state: nil, combined_rate: 0.08, is_seller_responsible: false, applicable_years: [2023]) allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("103.6.151.4") # Singapore @product = create(:product, price_cents: 100_00) create(:user_compliance_info_empty, user: @product.user, first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca", zip_code: "94107", country: Compliance::Countries::USA.common_name) @product.save! end it "applies the GST" do travel_to(Time.find_zone("UTC").local(2023, 4, 1)) do visit "/l/#{@product.unique_permalink}" expect(page).to have_selector("[itemprop='price']", text: "$100") add_to_cart(@product) expect(page).to have_text("GST US$8", normalize_ws: true) expect(page).to have_text("Total US$108", normalize_ws: true) check_out(@product, zip_code: nil, credit_card: { number: "4000007020000003" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(108_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(8_00) expect(purchase.was_purchase_taxable).to be(true) end end it "allows entry of GST ID and doesn't charge GST" do service_success_response = { "returnCode" => "10", "data" => { "Status" => "Registered" } } expect(HTTParty).to receive(:post).with(IRAS_ENDPOINT, anything).and_return(service_success_response) travel_to(Time.find_zone("UTC").local(2023, 4, 1)) do visit "/l/#{@product.unique_permalink}" expect(page).to have_selector("[itemprop='offers']", text: "$100") add_to_cart(@product) expect(page).to have_text("GST US$8", normalize_ws: true) check_out(@product, gst_id: "T9100001B", zip_code: nil, credit_card: { number: "4000007020000003" }) do expect(page).not_to have_text("GST US$8", normalize_ws: true) end purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(100_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(0) expect(purchase.was_purchase_taxable).to be(false) expect(purchase.purchase_sales_tax_info.business_vat_id).to eq("T9100001B") # Check GST ID is present on the invoice as well visit purchase.receipt_url click_on("Generate") expect(page).to(have_text("T9100001B")) end end it "applies GST for physical products" do travel_to(Time.find_zone("UTC").local(2023, 4, 1)) do @product = create(:physical_product, price_cents: 100_00) create(:user_compliance_info_empty, user: @product.user, first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca", zip_code: "94107", country: Compliance::Countries::USA.common_name) @product.save! visit "/l/#{@product.unique_permalink}" expect(page).to have_selector("[itemprop='offers']", text: "$100") add_to_cart(@product) expect(page).to have_text("GST US$8", normalize_ws: true) expect(page).to have_text("Total US$108", normalize_ws: true) check_out(@product, address: { street: "10 Bayfront Ave", city: "Singapore", state: "Singapore", zip_code: "018956" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(108_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(8_00) expect(purchase.was_purchase_taxable).to be(true) end end it "applies GST for physical products" do travel_to(Time.find_zone("UTC").local(2023, 4, 1)) do product = create(:physical_product, price_cents: 100_00) create(:user_compliance_info_empty, user: product.user, first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca", zip_code: "94107", country: Compliance::Countries::USA.common_name) product.save! visit "/l/#{product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(product) expect(page).to have_text("GST US$8", normalize_ws: true) expect(page).to have_text("Total US$108", normalize_ws: true) check_out(product, address: { street: "10 Bayfront Ave", city: "Singapore", state: "Singapore", zip_code: "018956" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(108_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(8_00) expect(purchase.was_purchase_taxable).to be(true) end end end describe "Norway Tax" do before do Capybara.current_session.driver.browser.manage.delete_all_cookies create(:zip_tax_rate, country: "NO", state: nil, zip_code: nil, combined_rate: 0.25, is_seller_responsible: false) create(:zip_tax_rate, country: "NO", state: nil, zip_code: nil, combined_rate: 0.00, is_seller_responsible: false, is_epublication_rate: true) allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("84.210.138.89") # Norway @product = create(:product, price_cents: 100_00) create(:user_compliance_info_empty, user: @product.user, first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca", zip_code: "94107", country: Compliance::Countries::USA.common_name) @product.save! end it "applies tax in Norway" do visit "/l/#{@product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(@product) expect(page).to have_text("VAT US$25", normalize_ws: true) expect(page).to have_text("Total US$125", normalize_ws: true) check_out(@product, zip_code: nil, credit_card: { number: "4000000360000006" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(125_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(25_00) expect(purchase.was_purchase_taxable).to be(true) end it "applies the epublication tax rate for epublications in Norway" do @product.update!(is_epublication: true) visit "/l/#{@product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(@product) expect(page).to have_text("Total US$100", normalize_ws: true) check_out(@product, zip_code: nil, credit_card: { number: "4000000360000006" }) purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(100_00) expect(purchase.price_cents).to eq(100_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(0) expect(purchase.was_purchase_taxable).to be(false) end it "allows entry of MVA ID and doesn't charge tax" do visit "/l/#{@product.unique_permalink}" expect(page).to have_text("$100") add_to_cart(@product)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/offer_codes_with_zero_discount_spec.rb
spec/requests/purchases/product/offer_codes_with_zero_discount_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Zero-discount offer-code usage from product page", type: :system, js: true) do context "manually set" do it "does not error when entering a $0 offer code and allows purchase" do product = create(:product, price_cents: 300, user: create(:user, display_offer_code_field: true)) offer_code = create(:offer_code, products: [product], amount_cents: 0) visit "/l/#{product.unique_permalink}" add_to_cart(product) check_out(product, offer_code: offer_code.code) purchase = Purchase.last expect(purchase.price_cents).to eq 300 expect(purchase.offer_code).to eq offer_code end it "does not error when entering a 0% offer code and allows purchase" do product = create(:product, price_cents: 300, user: create(:user, display_offer_code_field: true)) offer_code = create(:offer_code, products: [product], amount_cents: nil, amount_percentage: 0) visit "/l/#{product.unique_permalink}" add_to_cart(product) check_out(product, offer_code: offer_code.code) purchase = Purchase.last expect(purchase.price_cents).to eq 300 expect(purchase.offer_code).to eq offer_code end end context "set via URL" do it "applies a $0 offer code and allows purchase" do product = create(:product, price_cents: 300) offer_code = create(:offer_code, products: [product], amount_cents: 0) visit "/l/#{product.unique_permalink}/#{offer_code.code}" add_to_cart(product, offer_code:) wait_for_ajax expect(page).to have_text("Total US$3", normalize_ws: true) check_out(product) purchase = Purchase.last expect(purchase.price_cents).to eq 300 expect(purchase.offer_code).to eq offer_code end it "applies a 0% offer code and allows purchase" do product = create(:product, price_cents: 300) offer_code = create(:percentage_offer_code, products: [product], amount_percentage: 0) visit "/l/#{product.unique_permalink}/#{offer_code.code}" add_to_cart(product, offer_code:) wait_for_ajax expect(page).to have_text("Total US$3", normalize_ws: true) check_out(product) purchase = Purchase.last expect(purchase.price_cents).to eq 300 expect(purchase.offer_code).to eq offer_code end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/recommendations_spec.rb
spec/requests/purchases/product/recommendations_spec.rb
# frozen_string_literal: true require "spec_helper" describe "RecommendationsScenario", type: :system, js: true do before do @original_product = create(:product) @recommended_product = create(:product, user: create(:named_user), preview_url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/kFDzu.png") 3.times do |i| create(:purchase, email: "gumroaduser#{i}@gmail.com", link: @original_product) create(:purchase, email: "gumroaduser#{i}@gmail.com", link: @recommended_product) end Link.import(refresh: true, force: true) recreate_model_index(ProductPageView) end it "records discover purchases", :sidekiq_inline, :elasticsearch_wait_for_refresh do visit "/l/#{@recommended_product.unique_permalink}?recommended_by=discover" Timeout.timeout(Capybara.default_max_wait_time) do until EsClient.count(index: ProductPageView.index_name)["count"] == 1 sleep 0.5 end end page_view = EsClient.search(index: ProductPageView.index_name, size: 1)["hits"]["hits"][0]["_source"] expect(page_view).to include( "product_id" => @recommended_product.id, "referrer_domain" => "recommended_by_gumroad" ) expect do add_to_cart(@recommended_product, recommended_by: "discover") check_out(@recommended_product) end.to change { Purchase.successful.count }.by(1) purchase = Purchase.last expect(purchase.link_id).to eq @recommended_product.id expect(purchase.was_product_recommended).to be(true) end it "records the recommender_model_name if present", :sidekiq_inline, :elasticsearch_wait_for_refresh do visit "/l/#{@recommended_product.unique_permalink}?recommended_by=discover&recommender_model_name=#{RecommendedProductsService::MODEL_SALES}" expect do add_to_cart(@recommended_product) check_out(@recommended_product) end.to change { Purchase.successful.count }.by(1) purchase = Purchase.last! expect(purchase.link_id).to eq @recommended_product.id expect(purchase.recommender_model_name).to eq(RecommendedProductsService::MODEL_SALES) expect(purchase.recommended_purchase_info.recommender_model_name).to eq(RecommendedProductsService::MODEL_SALES) end def assert_buying_with_recommended_by_from_profile_page(recommended_by:) user = @recommended_product.user section = create(:seller_profile_products_section, seller: user, shown_products: [@recommended_product.id]) create(:seller_profile, seller: user, json_data: { tabs: [{ name: "", sections: [section.id] }] }) visit("/#{user.username}?recommended_by=#{recommended_by}") find_product_card(@recommended_product).click expect do add_to_cart(@recommended_product, recommended_by:, cart: true) check_out(@recommended_product) end.to change { Purchase.successful.count }.by(1) purchase = Purchase.last expect(purchase.link_id).to eq @recommended_product.id expect(purchase.was_product_recommended).to be(true) if recommended_by == "discover" expect(purchase.recommended_purchase_info.recommendation_type).to eq RecommendationType::GUMROAD_DISCOVER_RECOMMENDATION elsif recommended_by == "search" expect(purchase.recommended_purchase_info.recommendation_type).to eq RecommendationType::GUMROAD_SEARCH_RECOMMENDATION end end it "records the correct recommendation info when a product is bought from a creator's profile which contains " \ "'recommended_by=discover' in the URL" do assert_buying_with_recommended_by_from_profile_page(recommended_by: "discover") end it "records the correct recommendation info when a product is bought from a creator's profile which contains " \ "'recommended_by=search' in the URL" do assert_buying_with_recommended_by_from_profile_page(recommended_by: "search") end context "when a custom fee is set for the seller" do before do @recommended_product.user.update!(custom_fee_per_thousand: 50, user_risk_state: "compliant") @recommended_product.update!(taxonomy: Taxonomy.find_by!(slug: "design")) end it "charges the regular discover fee and not custom fee" do visit "/l/#{@recommended_product.unique_permalink}?recommended_by=discover&recommender_model_name=#{RecommendedProductsService::MODEL_SALES}" expect do add_to_cart(@recommended_product, recommended_by: "discover") check_out(@recommended_product) end.to change { Purchase.successful.count }.by(1) purchase = Purchase.last! expect(purchase.link_id).to eq @recommended_product.id expect(purchase.recommender_model_name).to eq(RecommendedProductsService::MODEL_SALES) expect(purchase.recommended_purchase_info.recommender_model_name).to eq(RecommendedProductsService::MODEL_SALES) expect(purchase.was_discover_fee_charged?).to eq(true) expect(purchase.custom_fee_per_thousand).to be_nil expect(purchase.fee_cents).to eq(30) # 30% discover fee end end describe "more like this" do let(:seller1) { create(:recommendable_user) } let(:seller2) { create(:named_user, recommendation_type: User::RecommendationType::NO_RECOMMENDATIONS) } let(:buyer) { create(:user) } let(:seller1_products) do build_list :product, 5, user: seller1 do |product, i| product.name = "Seller 1 Product #{i}" product.save! end end let(:seller2_products) do build_list :product, 2, user: seller2 do |product, i| product.name = "Seller 2 Product #{i}" product.save! end end before do create(:purchase, purchaser: buyer, link: seller1_products.first) seller1_products.drop(1).each_with_index do |product, i| SalesRelatedProductsInfo.update_sales_counts(product_id: seller1_products.first.id, related_product_ids: [product.id], increment: i + 1) end SalesRelatedProductsInfo.update_sales_counts(product_id: seller2_products.first.id, related_product_ids: seller2_products.drop(1).map(&:id), increment: 1) rebuild_srpis_cache end it "displays the correct recommended products and records the correct recommendation info on purchase" do login_as buyer visit seller2_products.first.long_url add_to_cart(seller2_products.first) expect(page).to_not have_section("Customers who bought this item also bought") visit seller1_products.first.long_url add_to_cart(seller1_products.first, logged_in_user: buyer) within_section "Customers who bought these items also bought" do expect(page).to have_selector("article:nth-child(1)", text: "Seller 1 Product 4") expect(page).to have_selector("article:nth-child(2)", text: "Seller 1 Product 3") expect(page).to have_selector("article:nth-child(3)", text: "Seller 1 Product 2") expect(page).to have_selector("article:nth-child(4)", text: "Seller 1 Product 1") expect(page).to_not have_text("Seller 2") click_on "Seller 1 Product 4" end add_to_cart(seller1_products.last, cart: true) within_section "Customers who bought these items also bought" do expect(page).to have_selector("article:nth-child(1)", text: "Seller 1 Product 3") expect(page).to have_selector("article:nth-child(2)", text: "Seller 1 Product 2") expect(page).to have_selector("article:nth-child(3)", text: "Seller 1 Product 1") expect(page).to_not have_text("Seller 2") end check_out(seller1_products.last, logged_in_user: buyer) purchase = Purchase.third_to_last expect(purchase.link).to eq(seller1_products.last) expect(purchase.recommender_model_name).to eq(RecommendedProductsService::MODEL_SALES) expect(purchase.recommended_purchase_info.recommender_model_name).to eq(RecommendedProductsService::MODEL_SALES) expect(purchase.recommended_purchase_info.recommendation_type).to eq(RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION) end context "when at least one creator has Gumroad affiliate recommendations enabled" do before do seller1.update!(recommendation_type: User::RecommendationType::GUMROAD_AFFILIATES_PRODUCTS) SalesRelatedProductsInfo.update_sales_counts(product_id: seller2_products.first.id, related_product_ids: [seller1_products.first.id], increment: 1000) rebuild_srpis_cache allow_any_instance_of(Link).to receive(:recommendable?).and_return(true) end it "recommends and attributes affiliate purchases for products with Gumroad affiliates enabled" do login_as buyer visit seller1_products.first.long_url add_to_cart(seller1_products.first, logged_in_user: buyer) click_on "Seller 2 Product 0" add_to_cart(seller2_products.first, logged_in_user: buyer, cart: true) check_out(seller2_products.first, logged_in_user: buyer) purchase = Purchase.second_to_last expect(purchase.link).to eq(seller2_products.first) expect(purchase.recommender_model_name).to eq(RecommendedProductsService::MODEL_SALES) expect(purchase.recommended_purchase_info.recommender_model_name).to eq(RecommendedProductsService::MODEL_SALES) expect(purchase.recommended_purchase_info.recommendation_type).to eq(RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION) expect(purchase.affiliate).to eq(seller1.global_affiliate) end end context "when a creator has direct affiliate recommendations enabled" do let!(:affiliate) { create(:direct_affiliate, seller: seller2, products: [seller2_products.first], affiliate_user: seller1) } before do seller1.update!(recommendation_type: User::RecommendationType::DIRECTLY_AFFILIATED_PRODUCTS) SalesRelatedProductsInfo.update_sales_counts(product_id: seller2_products.first.id, related_product_ids: [seller1_products.first.id], increment: 1000) rebuild_srpis_cache allow_any_instance_of(Link).to receive(:recommendable?).and_return(true) end it "it recommends and attributes affiliate purchases for products with Gumroad affiliates enabled" do login_as buyer visit seller1_products.first.long_url add_to_cart(seller1_products.first, logged_in_user: buyer) click_on "Seller 2 Product 0" add_to_cart(seller2_products.first, logged_in_user: buyer, cart: true) check_out(seller2_products.first, logged_in_user: buyer) purchase = Purchase.second_to_last expect(purchase.link).to eq(seller2_products.first) expect(purchase.recommender_model_name).to eq(RecommendedProductsService::MODEL_SALES) expect(purchase.recommended_purchase_info.recommender_model_name).to eq(RecommendedProductsService::MODEL_SALES) expect(purchase.recommended_purchase_info.recommendation_type).to eq(RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION) expect(purchase.affiliate).to eq(affiliate) end end context "when the product has increased discover placement" do before do seller1_products.first.update!(discover_fee_per_thousand: 400) end it "does not charge discover fees" do login_as buyer visit seller1_products.first.long_url add_to_cart(seller1_products.first, logged_in_user: buyer) click_on "Seller 1 Product 1" add_to_cart(seller1_products.second, logged_in_user: buyer, cart: true) check_out(seller1_products.second, logged_in_user: buyer) purchase = Purchase.second_to_last expect(purchase.link).to eq(seller1_products.second) expect(purchase.recommended_by).to eq(RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION) expect(purchase.was_discover_fee_charged?).to eq(false) expect(purchase.fee_cents).to eq(93) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/pending_collaborators_spec.rb
spec/requests/purchases/product/pending_collaborators_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Product checkout - with pending collaborators", type: :system, js: true) do let(:product) { create(:product, :recommendable, price_cents: 20_00) } let!(:pending_collaborator) do create( :collaborator, :with_pending_invitation, affiliate_basis_points: 50_00, products: [product] ) end it "does not credit the collaborator if the collaborator has not accepted the invitation" do visit short_link_path(product.unique_permalink) complete_purchase(product) purchase = Purchase.last expect(purchase.affiliate).to be_nil expect(purchase.affiliate_credit_cents).to eq 0 end context "when an affiliate is set" do # Products with collaborators can't have direct affiliates. let!(:global_affiliate) { create(:user).global_affiliate } it "credits the affiliate" do visit global_affiliate.referral_url_for_product(product) complete_purchase(product) purchase = Purchase.last expect(purchase.affiliate).to eq global_affiliate expect(purchase.affiliate_credit_cents).to eq 1_66 end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/signup_after_purchase_spec.rb
spec/requests/purchases/product/signup_after_purchase_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Sign up after purchase", type: :system, js: true do before do product = create(:product) product2 = create(:product) visit product.long_url add_to_cart(product) visit product2.long_url add_to_cart(product2) product2.update(price_cents: 600) check_out(product2, error: "The price just changed! Refresh the page for the updated price.") end context "when password is valid" do it "creates the account and saves payment method" do expect do fill_in("Enter password", with: SecureRandom.hex(24)) click_on("Sign up") wait_for_ajax expect(page).to have_content("Your account has been created. You'll get a confirmation email shortly.") expect(page).not_to have_field("Enter password", visible: false) expect(page).not_to have_selector("button", text: "Sign up") end.to change { User.count }.by(1) user = User.last expect(user.credit_card).to be_present expect(user.credit_card.visual).to eq "**** **** **** 4242" end end context "when password is invalid" do it "shows an error message for compromised passwords" do expect do fill_in("Enter password", with: "password") vcr_turned_on do only_matching_vcr_request_from(["pwnedpasswords"]) do VCR.use_cassette("Signup after purchase-with a compromised password") do with_real_pwned_password_check do click_on("Sign up") sleep 5 # frontend code will tokenize the card, then actually register. without the `sleep`, `wait_for_ajax` would terminate too soon and break compromised password check wait_for_ajax end end end end expect(page).to have_content("Password has previously appeared in a data breach as per haveibeenpwned.com and should never be used. Please choose something harder to guess.") expect(page).to have_selector("button", text: "Sign up") end.not_to change { User.count } end it "shows an error message for passwords too short" do expect do fill_in("Enter password", with: "1") click_on("Sign up") wait_for_ajax expect(page).to have_content("Password is too short (minimum is 4 characters)") expect(page).to have_selector("button", text: "Sign up") end.not_to change { User.count } end it "allows to fix a validation error and submit again" do expect do fill_in("Enter password", with: "1") click_on("Sign up") wait_for_ajax expect(page).to have_content("Password is too short (minimum is 4 characters)") expect(page).to have_selector("button", text: "Sign up") end.not_to change { User.count } expect do fill_in("Enter password", with: SecureRandom.hex(24)) click_on("Sign up") wait_for_ajax expect(page).to have_content("Your account has been created. You'll get a confirmation email shortly.") expect(page).not_to have_field("Enter password", visible: false) expect(page).not_to have_selector("button", text: "Sign up") end.to change { User.count }.by(1) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/installment_plan_spec.rb
spec/requests/purchases/product/installment_plan_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Product with installment plan", type: :system, js: true do let!(:seller) { create(:user, tipping_enabled: true) } let!(:product) { create(:product, name: "Awesome product", user: seller, price_cents: 1000) } let!(:installment_plan) { create(:product_installment_plan, link: product, number_of_installments: 3) } it "allows paying in installments" do visit product.long_url expect(page).to have_text("First installment of $3.34, followed by 2 monthly installments of $3.33", normalize_ws: true) click_on "Pay in 3 installments" within_cart_item product.name do expect(page).to have_text("US$10 in 3 installments", normalize_ws: true) select_disclosure "Edit" do choose "Pay in full" click_on "Save changes" end end expect(page).to have_text("Subtotal US$10", normalize_ws: true) expect(page).to have_text("Total US$10", normalize_ws: true) expect(page).not_to have_text("Payment today", normalize_ws: true) expect(page).not_to have_text("Future installments", normalize_ws: true) within_cart_item product.name do expect(page).to_not have_text("in 3 installments") select_disclosure "Edit" do choose "Pay in 3 installments" click_on "Save changes" end end within_cart_item product.name do expect(page).to have_text("US$10 in 3 installments", normalize_ws: true) end expect(page).to have_text("Subtotal US$10", normalize_ws: true) expect(page).to have_text("Total US$10", normalize_ws: true) expect(page).to have_text("Payment today US$3.34", normalize_ws: true) expect(page).to have_text("Future installments US$6.66", normalize_ws: true) fill_checkout_form(product) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = product.sales.last subscription = purchase.subscription expect(purchase).to have_attributes( price_cents: 334, is_installment_payment: true, is_original_subscription_purchase: true, ) expect(subscription).to have_attributes( is_installment_plan: true, charge_occurrence_count: 3, recurrence: "monthly", ) expect(subscription.last_payment_option.installment_plan).to eq(installment_plan) visit purchase.receipt_url expect(page).to have_text("Installment plan initiated on #{subscription.created_at.to_fs(:formatted_date_abbrev_month)}.") travel_to(1.month.from_now) RecurringChargeWorker.new.perform(subscription.id) expect(subscription.purchases.successful.count).to eq(2) expect(subscription.purchases.successful.last).to have_attributes( price_cents: 333, is_installment_payment: true, is_original_subscription_purchase: false, ) end describe "custom fee" do before do product.user.update!(custom_fee_per_thousand: 50) end it "allows paying in installments and charges the correct custom fee set for the seller" do visit product.long_url expect(page).to have_text("First installment of $3.34, followed by 2 monthly installments of $3.33", normalize_ws: true) click_on "Pay in 3 installments" within_cart_item product.name do expect(page).to have_text("US$10 in 3 installments", normalize_ws: true) select_disclosure "Edit" do choose "Pay in full" click_on "Save changes" end end expect(page).to have_text("Subtotal US$10", normalize_ws: true) expect(page).to have_text("Total US$10", normalize_ws: true) expect(page).not_to have_text("Payment today", normalize_ws: true) expect(page).not_to have_text("Future installments", normalize_ws: true) within_cart_item product.name do expect(page).to_not have_text("in 3 installments") select_disclosure "Edit" do choose "Pay in 3 installments" click_on "Save changes" end end within_cart_item product.name do expect(page).to have_text("US$10 in 3 installments", normalize_ws: true) end expect(page).to have_text("Subtotal US$10", normalize_ws: true) expect(page).to have_text("Total US$10", normalize_ws: true) expect(page).to have_text("Payment today US$3.34", normalize_ws: true) expect(page).to have_text("Future installments US$6.66", normalize_ws: true) fill_checkout_form(product) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = product.sales.last subscription = purchase.subscription expect(purchase).to have_attributes( price_cents: 334, fee_cents: 106, # 5% of $3.34 + 50c + 2.9% of $3.34 + 30c is_installment_payment: true, is_original_subscription_purchase: true, ) expect(subscription).to have_attributes( is_installment_plan: true, charge_occurrence_count: 3, recurrence: "monthly", ) expect(subscription.last_payment_option.installment_plan).to eq(installment_plan) travel_to(1.month.from_now) RecurringChargeWorker.new.perform(subscription.id) expect(subscription.purchases.successful.count).to eq(2) expect(subscription.purchases.successful.last).to have_attributes( price_cents: 333, fee_cents: 106, # 5% of $3.34 + 50c + 2.9% of $3.34 + 30c is_installment_payment: true, is_original_subscription_purchase: false, ) end end it "does not change CTA buttons behavior when pay_in_installments parameter is present" do visit "#{product.long_url}?pay_in_installments=true" click_on "I want this!" within_cart_item product.name do expect(page).not_to have_text("in 3 installments") end visit "#{product.long_url}?pay_in_installments=true" click_on "Pay in 3 installments" within_cart_item product.name do expect(page).to have_text("in 3 installments") end end describe "gifting" do it "does not allow gifting when paying in installments" do visit product.long_url click_on "I want this!" expect(page).to have_field("Give as a gift") within_cart_item product.name do select_disclosure "Edit" do choose "Pay in 3 installments" click_on "Save changes" end end expect(page).not_to have_field("Give as a gift") end end describe "tips" do it "charges the full tip amount on the first payment" do visit product.long_url click_on "Pay in 3 installments" within_cart_item product.name do expect(page).to have_text("US$10 in 3 installments", normalize_ws: true) end expect(page).to have_text("Subtotal US$10", normalize_ws: true) expect(page).to have_text("Total US$10", normalize_ws: true) expect(page).to have_text("Payment today US$3.34", normalize_ws: true) expect(page).to have_text("Future installments US$6.66", normalize_ws: true) choose "10%" expect(page).to have_text("Subtotal US$10", normalize_ws: true) expect(page).to have_text("Tip US$1", normalize_ws: true) expect(page).to have_text("Total US$11", normalize_ws: true) expect(page).to have_text("Payment today US$4.34", normalize_ws: true) expect(page).to have_text("Future installments US$6.66", normalize_ws: true) fill_checkout_form(product) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = product.sales.last subscription = purchase.subscription expect(purchase).to have_attributes( price_cents: 434, is_installment_payment: true, is_original_subscription_purchase: true, ) expect(purchase.tip.value_cents).to eq(100) expect(subscription).to have_attributes( is_installment_plan: true, charge_occurrence_count: 3, recurrence: "monthly", ) travel_to(1.month.from_now) RecurringChargeWorker.new.perform(subscription.id) expect(subscription.purchases.successful.count).to eq(2) expect(subscription.purchases.successful.last).to have_attributes( price_cents: 333, is_installment_payment: true, is_original_subscription_purchase: false, ) expect(subscription.purchases.successful.last.tip).to be_nil end end describe "discounts" do before { product.update!(price_cents: 1100) } let!(:offer_code_valid_for_one_billing_cycle) { create(:universal_offer_code, user: seller, amount_cents: 100, duration_in_billing_cycles: 1) } it "applies the discount to all charges even if it's only for one memebership cycle" do visit product.long_url + "/" + offer_code_valid_for_one_billing_cycle.code expect(page).to have_text("First installment of $3.34, followed by 2 monthly installments of $3.33", normalize_ws: true) click_on "Pay in 3 installments" expect(page).to have_text("Subtotal US$11", normalize_ws: true) expect(page).to have_text("Discounts #{offer_code_valid_for_one_billing_cycle.code} US$-1", normalize_ws: true) expect(page).to have_text("Total US$10", normalize_ws: true) expect(page).to have_text("Payment today US$3.34", normalize_ws: true) expect(page).to have_text("Future installments US$6.66", normalize_ws: true) fill_checkout_form(product) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = product.sales.last subscription = purchase.subscription expect(purchase).to have_attributes( price_cents: 334, is_installment_payment: true, is_original_subscription_purchase: true, ) expect(subscription).to have_attributes( is_installment_plan: true, charge_occurrence_count: 3, recurrence: "monthly", ) expect(subscription.last_payment_option.installment_plan).to eq(installment_plan) travel_to(1.month.from_now) RecurringChargeWorker.new.perform(subscription.id) expect(subscription.purchases.successful.count).to eq(2) expect(subscription.purchases.successful.last).to have_attributes( price_cents: 333, is_installment_payment: true, is_original_subscription_purchase: false, ) end end describe "bundles" do let!(:course_product) { create(:product, native_type: Link::NATIVE_TYPE_COURSE, name: "Course Product", user: seller, price_cents: 500) } let!(:ebook_product) { create(:product, native_type: Link::NATIVE_TYPE_EBOOK, name: "Ebook Product", user: seller, price_cents: 500) } let!(:bundle) { create(:product, :bundle, name: "Awesome Bundle", user: seller, price_cents: 1000) } let!(:course_bundle_product) { create(:bundle_product, bundle:, product: course_product) } let!(:ebook_bundle_product) { create(:bundle_product, bundle:, product: ebook_product) } let!(:installment_plan) { create(:product_installment_plan, link: bundle, number_of_installments: 3) } it "allows paying for a bundle in installments" do visit bundle.long_url click_on "Pay in 3 installments" within_cart_item bundle.name do expect(page).to have_text("US$10 in 3 installments", normalize_ws: true) end expect(page).to have_text("Subtotal US$10", normalize_ws: true) expect(page).to have_text("Total US$10", normalize_ws: true) expect(page).to have_text("Payment today US$3.34", normalize_ws: true) expect(page).to have_text("Future installments US$6.66", normalize_ws: true) fill_checkout_form(bundle) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = bundle.sales.last subscription = purchase.subscription expect(purchase).to have_attributes( price_cents: 334, is_installment_payment: true, is_original_subscription_purchase: true, ) expect(subscription).to have_attributes( is_installment_plan: true, charge_occurrence_count: 3, recurrence: "monthly", ) expect(subscription.last_payment_option.installment_plan).to eq(installment_plan) travel_to(1.month.from_now) RecurringChargeWorker.new.perform(subscription.id) expect(subscription.purchases.successful.count).to eq(2) expect(subscription.purchases.successful.last).to have_attributes( price_cents: 333, is_installment_payment: true, is_original_subscription_purchase: false, ) end end describe "tax" do it "calculates and charges sales tax for all installment payments when applicable" do visit product.long_url click_on "Pay in 3 installments" fill_checkout_form(product, zip_code: "53703") expect(page).to have_text("Subtotal US$10", normalize_ws: true) expect(page).to have_text("Sales tax US$0.55", normalize_ws: true) expect(page).to have_text("Total US$10.55", normalize_ws: true) # TODO: This is a display-only issue that we include the full tax amount # into "Payment today". Addressing this requires overhualing how taxes is # calculated for display purposes at checkout. expect(page).to have_text("Payment today US$3.89", normalize_ws: true) expect(page).to have_text("Future installments US$6.66", normalize_ws: true) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = product.sales.last subscription = purchase.subscription expect(purchase).to have_attributes( price_cents: 334, gumroad_tax_cents: 18, is_installment_payment: true, is_original_subscription_purchase: true, ) expect(subscription).to have_attributes( is_installment_plan: true, charge_occurrence_count: 3, recurrence: "monthly", ) expect(subscription.last_payment_option.installment_plan).to eq(installment_plan) travel_to(1.month.from_now) RecurringChargeWorker.new.perform(subscription.id) expect(subscription.purchases.successful.count).to eq(2) expect(subscription.purchases.successful.last).to have_attributes( price_cents: 333, gumroad_tax_cents: 18, is_installment_payment: true, is_original_subscription_purchase: false, ) end end context "when the product is priced in non-USD currency" do let!(:product) { create(:product, name: "Awesome product in EUR", user: seller, price_cents: 149500, price_currency_type: Currency::EUR) } let!(:installment_plan) { create(:product_installment_plan, link: product, number_of_installments: 3) } before do allow_any_instance_of(CurrencyHelper).to receive(:get_rate).with("eur").and_return("0.86734042676") allow_any_instance_of(CurrencyHelper).to receive(:get_rate).with(:eur).and_return("0.86734042676") end it "displays and charges correct installment amounts in USD" do visit product.long_url expect(page).to have_text("First installment of €498.34, followed by 2 monthly installments of €498.33", normalize_ws: true) click_on "Pay in 3 installments" within_cart_item product.name do expect(page).to have_text("US$1,723.66 in 3 installments", normalize_ws: true) select_disclosure "Edit" do choose "Pay in full" click_on "Save changes" end end expect(page).to have_text("Subtotal US$1,723.66", normalize_ws: true) expect(page).to have_text("Total US$1,723.66", normalize_ws: true) expect(page).not_to have_text("Payment today", normalize_ws: true) expect(page).not_to have_text("Future installments", normalize_ws: true) within_cart_item product.name do expect(page).to_not have_text("in 3 installments") select_disclosure "Edit" do choose "Pay in 3 installments" click_on "Save changes" end end within_cart_item product.name do expect(page).to have_text("US$1,723.66 in 3 installments", normalize_ws: true) end expect(page).to have_text("Subtotal US$1,723.66", normalize_ws: true) expect(page).to have_text("Total US$1,723.66", normalize_ws: true) expect(page).to have_text("Payment today US$574.56", normalize_ws: true) expect(page).to have_text("Future installments US$1,149.10", normalize_ws: true) fill_checkout_form(product) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = product.sales.last subscription = purchase.subscription expect(purchase).to have_attributes( price_cents: 57456, displayed_price_cents: 49834, is_installment_payment: true, is_original_subscription_purchase: true, ) expect(subscription).to have_attributes( is_installment_plan: true, charge_occurrence_count: 3, recurrence: "monthly", ) expect(subscription.last_payment_option.installment_plan).to eq(installment_plan) travel_to(1.month.from_now) RecurringChargeWorker.new.perform(subscription.id) expect(subscription.purchases.successful.count).to eq(2) expect(subscription.purchases.successful.last).to have_attributes( price_cents: 57455, displayed_price_cents: 49833, is_installment_payment: true, is_original_subscription_purchase: false, ) end describe "with sales tax" do before do Feature.activate("collect_tax_in") allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("103.48.196.103") # India create(:zip_tax_rate, country: "IN", state: nil, zip_code: nil, combined_rate: 0.18, is_seller_responsible: false) create(:user_compliance_info_empty, user: product.user, first_name: "edgar", last_name: "gumstein", street_address: "123 main", city: "sf", state: "ca", zip_code: "94107", country: Compliance::Countries::USA.common_name) end it "displays and charges correct installment amounts in USD" do visit product.long_url expect(page).to have_text("First installment of €498.34, followed by 2 monthly installments of €498.33", normalize_ws: true) click_on "Pay in 3 installments" fill_checkout_form(product, country: "India", zip_code: nil) within_cart_item product.name do expect(page).to have_text("US$1,723.66 in 3 installments", normalize_ws: true) select_disclosure "Edit" do choose "Pay in full" click_on "Save changes" end end expect(page).to have_text("Subtotal US$1,723.66", normalize_ws: true) expect(page).to have_text("GST US$310.26", normalize_ws: true) expect(page).to have_text("Total US$2,033.92", normalize_ws: true) expect(page).not_to have_text("Payment today", normalize_ws: true) expect(page).not_to have_text("Future installments", normalize_ws: true) within_cart_item product.name do expect(page).to_not have_text("in 3 installments") select_disclosure "Edit" do choose "Pay in 3 installments" click_on "Save changes" end end within_cart_item product.name do expect(page).to have_text("US$1,723.66 in 3 installments", normalize_ws: true) end expect(page).to have_text("Subtotal US$1,723.66", normalize_ws: true) expect(page).to have_text("GST US$310.26", normalize_ws: true) expect(page).to have_text("Total US$2,033.92", normalize_ws: true) expect(page).to have_text("Payment today US$884.82", normalize_ws: true) expect(page).to have_text("Future installments US$1,149.10", normalize_ws: true) fill_checkout_form(product, zip_code: nil) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = product.sales.last subscription = purchase.subscription expect(purchase).to have_attributes( price_cents: 57456, displayed_price_cents: 49834, is_installment_payment: true, is_original_subscription_purchase: true, ) expect(subscription).to have_attributes( is_installment_plan: true, charge_occurrence_count: 3, recurrence: "monthly", ) expect(subscription.last_payment_option.installment_plan).to eq(installment_plan) travel_to(1.month.from_now) RecurringChargeWorker.new.perform(subscription.id) expect(subscription.purchases.successful.count).to eq(2) expect(subscription.purchases.successful.last).to have_attributes( price_cents: 57455, displayed_price_cents: 49833, is_installment_payment: true, is_original_subscription_purchase: 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/requests/purchases/product/upsell_spec.rb
spec/requests/purchases/product/upsell_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Product checkout with upsells", type: :system, js: true) do let(:seller) { create(:named_seller) } let(:upsell_product) { create(:product_with_digital_versions, name: "Upsell product", user: seller) } let!(:upsell) { create(:upsell, text: "Upsell", description: "Check out this awesome upsell at https://upsell.com!", seller:, product: upsell_product) } let!(:upsell_variant) { create(:upsell_variant, upsell:, selected_variant: upsell_product.alive_variants.first, offered_variant: upsell_product.alive_variants.second) } let(:selected_product) { create(:product, name: "Product", user: seller) } let(:product) { create(:product_with_digital_versions, name: "Offered product", user: seller) } let!(:cross_sell) { create(:upsell, text: "Cross-sell", description: "Check out this awesome cross-sell at https://cross-sell.com!", seller:, product:, variant: product.alive_variants.first, selected_products: [selected_product], offer_code: create(:offer_code, user: seller, products: [product]), cross_sell: true) } context "when the product has an upsell" do it "allows the buyer to accept the upsell at checkout" do visit upsell_product.long_url add_to_cart(upsell_product, option: "Untitled 1") fill_checkout_form(upsell_product) click_on "Pay" within_modal "Upsell" do expect(page).to have_text("Check out this awesome upsell at https://upsell.com!") link = find_link("https://upsell.com", href: "https://upsell.com", target: "_blank") expect(link["rel"]).to eq("noopener") expect(page).to have_radio_button("Untitled 2") click_on "Upgrade" end expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to_not have_text("Upsell product - Untitled 1") expect(page).to have_text("Upsell product - Untitled 2") purchase = Purchase.last expect(purchase.upsell_purchase.upsell).to eq(upsell) expect(purchase.upsell_purchase.selected_product).to eq(upsell_product) expect(purchase.upsell_purchase.upsell_variant).to eq(upsell_variant) expect(purchase.variant_attributes.first).to eq(upsell_product.alive_variants.second) end it "allows the buyer to decline the upsell at checkout" do visit upsell_product.long_url add_to_cart(upsell_product, option: "Untitled 1") fill_checkout_form(upsell_product) click_on "Pay" within_modal "Upsell" do expect(page).to have_text("Check out this awesome upsell at https://upsell.com!") expect(page).to have_radio_button("Untitled 2") click_on "Don't upgrade" end expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to have_text("Upsell product - Untitled 1") expect(page).to_not have_text("Upsell product - Untitled 2") purchase = Purchase.last expect(purchase.upsell_purchase).to be_nil expect(purchase.variant_attributes.first).to eq(upsell_product.alive_variants.first) end context "when the upsell is paused" do before { upsell.update!(paused: true) } it "doesn't offer the upsell at checkout" do visit upsell_product.long_url add_to_cart(upsell_product, option: "Untitled 1") check_out(upsell_product) end end end context "when the product has a cross-sell" do it "allows the buyer to accept the cross-sell at checkout" do visit selected_product.long_url add_to_cart(selected_product) fill_checkout_form(selected_product) click_on "Pay" within_modal "Cross-sell" do expect(page).to have_text("Check out this awesome cross-sell at https://cross-sell.com!") link = find_link("https://cross-sell.com", href: "https://cross-sell.com", target: "_blank") expect(link["rel"]).to eq("noopener") expect(page).to have_selector("[itemprop='price']", text: "$1 $0", normalize_ws: true) expect(page).to have_section("Offered product - Untitled 1") expect(page).to have_link(href: product.long_url) click_on "Add to cart" end expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to have_section("Product") expect(page).to have_section("Offered product - Untitled 1") purchase = Purchase.last expect(purchase.link).to eq(product) expect(purchase.variant_attributes.first).to eq(product.alive_variants.first) expect(purchase.upsell_purchase.upsell).to eq(cross_sell) expect(purchase.upsell_purchase.selected_product).to eq(selected_product) expect(purchase.offer_code).to eq(cross_sell.offer_code) end context "when the buyer tips" do before do seller.update!(tipping_enabled: true) product.update!(price_cents: 500) end it "allows the buyer to accept the cross-sell at checkout" do visit selected_product.long_url add_to_cart(selected_product) fill_checkout_form(selected_product) choose "20%" click_on "Pay" within_modal "Cross-sell" do click_on "Add to cart" end expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") cross_sell_purchase = Purchase.last expect(cross_sell_purchase.link).to eq(product) expect(cross_sell_purchase.variant_attributes.first).to eq(product.alive_variants.first) expect(cross_sell_purchase.upsell_purchase.upsell).to eq(cross_sell) expect(cross_sell_purchase.upsell_purchase.selected_product).to eq(selected_product) expect(cross_sell_purchase.offer_code).to eq(cross_sell.offer_code) expect(cross_sell_purchase.price_cents).to eq(480) expect(cross_sell_purchase.tip.value_cents).to eq(80) purchase = Purchase.second_to_last expect(purchase.link).to eq(selected_product) expect(purchase.price_cents).to eq(120) expect(purchase.tip.value_cents).to eq(20) end end it "allows the buyer to decline the cross-sell at checkout" do visit selected_product.long_url add_to_cart(selected_product) fill_checkout_form(selected_product) click_on "Pay" within_modal "Cross-sell" do expect(page).to have_text("Check out this awesome cross-sell at https://cross-sell.com!") expect(page).to have_selector("[itemprop='price']", text: "$1 $0", normalize_ws: true) expect(page).to have_section("Offered product - Untitled 1") expect(page).to have_link(href: product.long_url) click_on "Continue without adding" end expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to have_section("Product") expect(page).to_not have_section("Offered product - Untitled 1") purchase = Purchase.last expect(purchase.upsell_purchase).to be_nil expect(purchase.variant_attributes.first).to eq(selected_product.alive_variants.first) end context "when the cross-sell is paused" do before { cross_sell.update!(paused: true) } it "doesn't offer the cross-sell at checkout" do visit selected_product.long_url add_to_cart(selected_product) check_out(selected_product) end end context "when the buyer has a better discount code" do let!(:cross_sell) { nil } # Override global cross_sell to avoid conflicts let!(:additive_cross_sell) { create(:upsell, text: "Cross-sell", description: "Check out this awesome cross-sell!", seller:, product:, variant: product.alive_variants.first, selected_products: [selected_product], cross_sell: true, replace_selected_products: false) } let(:better_discount_code) { create(:offer_code, code: "betterdiscount", user: seller, universal: true, amount_cents: 100) } before do product.update!(price_cents: 400) selected_product.update!(price_cents: 200) end it "applies applicable discount codes to non-replacement cross-sells" do visit "#{selected_product.long_url}/#{better_discount_code.code}" add_to_cart(selected_product, offer_code: better_discount_code) fill_checkout_form(selected_product) click_on "Pay" within_modal "Cross-sell" do expect(page).to have_text("Check out this awesome cross-sell!") expect(page).to have_section("Offered product") # The modal shows the original discount applied to the cross-sell expect(page).to have_selector("[itemprop='price']", text: "$4 $3") click_on "Add to cart" end expect(page).to have_section("Offered product") expect(page).to have_section("Product") # Cart retains the original discount code and applies it to both products expect(page).to have_selector("[aria-label='Discount code']", text: better_discount_code.code) # $1 off each product expect(page).to have_text("US$-2") expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to have_section("Offered product") expect(page).to have_section("Product") selected_purchase = selected_product.sales.last offered_purchase = product.sales.last expect(selected_purchase.price_cents).to eq(100) # $200 - $100 discount expect(selected_purchase.offer_code).to eq(better_discount_code) expect(selected_purchase.upsell_purchase).to be_nil expect(offered_purchase.price_cents).to eq(300) # $400 - $100 discount expect(offered_purchase.offer_code).to eq(better_discount_code) expect(offered_purchase.upsell_purchase.selected_product).to eq(selected_product) expect(offered_purchase.upsell_purchase.upsell).to eq(additive_cross_sell) end end end context "when the product has a universal cross-sell" do let(:unassociated_product) { create(:product, user: seller, name: "Unassociated product") } let!(:universal_cross_sell) { create(:upsell, text: "Cross-sell", description: "Check out this awesome cross-sell!", seller:, product:, variant: product.alive_variants.first, selected_products: [], cross_sell: true, universal: true) } it "allows the buyer to accept the cross-sell at checkout" do visit unassociated_product.long_url add_to_cart(unassociated_product) fill_checkout_form(unassociated_product) click_on "Pay" within_modal "Cross-sell" do expect(page).to have_text("Check out this awesome cross-sell!") expect(page).to have_selector("[itemprop='price']", text: "$1", normalize_ws: true) expect(page).to have_section("Offered product - Untitled 1") expect(page).to have_link(href: product.long_url) click_on "Add to cart" end expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to have_section("Unassociated product") expect(page).to have_section("Offered product - Untitled 1") purchase = Purchase.last expect(purchase.link).to eq(product) expect(purchase.variant_attributes.first).to eq(product.alive_variants.first) expect(purchase.upsell_purchase.upsell).to eq(universal_cross_sell) expect(purchase.upsell_purchase.selected_product).to eq(unassociated_product) expect(purchase.offer_code).to eq(nil) end end context "when the product has a replacement cross-sell" do let(:product) { create(:product, user: seller, name: "Offered product", price_cents: 400) } let(:selected_product1) { create(:product, user: seller, name: "Selected product 1", price_cents: 200) } let(:selected_product2) { create(:product, user: seller, name: "Selected product 2", price_cents: 200) } let!(:replacement_cross_sell) { create(:upsell, text: "Replacement cross-sell", seller:, product:, variant: product.alive_variants.first, selected_products: [selected_product1, selected_product2], offer_code: build(:offer_code, user: seller, products: [product], amount_cents: 50), cross_sell: true, replace_selected_products: true) } it "removes the selected products when the buyer accepts the cross-sell" do visit selected_product1.long_url add_to_cart(selected_product1) visit selected_product2.long_url add_to_cart(selected_product2) fill_checkout_form(selected_product2) click_on "Pay" within_modal "Replacement cross-sell" do expect(page).to have_text("This offer will only last for a few weeks.") expect(page).to have_section("Offered product") expect(page).to have_selector("[itemprop='price']", text: "$4 $3.50") click_on "Upgrade" end expect(page).to have_section("Offered product") expect(page).to_not have_section("Selected product 1") expect(page).to_not have_section("Selected product 2") expect(page).to_not have_selector("[aria-label='Discount code']") expect(page).to have_text("US$-0.50") expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to have_section("Offered product") expect(page).to_not have_section("Selected product 1") expect(page).to_not have_section("Selected product 2") purchase = Purchase.last expect(purchase.link).to eq(product) expect(purchase.price_cents).to eq(350) expect(purchase.offer_code).to eq(replacement_cross_sell.offer_code) expect(purchase.upsell_purchase.selected_product).to eq(selected_product2) expect(purchase.upsell_purchase.upsell).to eq(replacement_cross_sell) end context "when the buyer has a better discount code" do let(:better_discount_code) { create(:offer_code, code: "betterdiscount", user: seller, universal: true, amount_cents: 100) } it "retains the original discount code if it's better than the replacement cross-sell discount" do visit "#{selected_product1.long_url}/#{better_discount_code.code}" add_to_cart(selected_product1, offer_code: better_discount_code) fill_checkout_form(selected_product1) click_on "Pay" within_modal "Replacement cross-sell" do expect(page).to have_text("This offer will only last for a few weeks.") expect(page).to have_section("Offered product") # The modal shows original discount that is better than the replacement # cross-sell discount. expect(page).to have_selector("[itemprop='price']", text: "$4 $3") click_on "Upgrade" end expect(page).to have_section("Offered product") expect(page).to_not have_section("Selected product 1") # Cart retains the original discount code after accepting the replacement # cross-sell. expect(page).to have_selector("[aria-label='Discount code']", text: better_discount_code.code) expect(page).to have_text("US$-1") expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to have_section("Offered product") expect(page).to_not have_section("Selected product 1") purchase = Purchase.last expect(purchase.link).to eq(product) expect(purchase.price_cents).to eq(300) expect(purchase.offer_code).to eq(better_discount_code) expect(purchase.upsell_purchase.selected_product).to eq(selected_product1) expect(purchase.upsell_purchase.upsell).to eq(replacement_cross_sell) end end context "selected product is free and offered product is paid" do before do selected_product1.update!(price_cents: 0) # Indian IP address so that the ZIP code field doesn't get the error instead of the card input allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("182.23.143.254") end it "marks the card input as invalid and doesn't show an error" do visit selected_product1.long_url add_to_cart(selected_product1, pwyw_price: 0) fill_checkout_form(selected_product1, is_free: true) click_on "Get" click_on "Upgrade" expect(page).to_not have_alert expect(page).to have_selector("[aria-label='Card information'][aria-invalid='true']") end end end context "when there are multiple upsells" do it "allows the buyer to accept each upsell at checkout" do visit upsell_product.long_url add_to_cart(upsell_product, option: "Untitled 1") visit selected_product.long_url add_to_cart(selected_product) fill_checkout_form(selected_product) click_on "Pay" within_modal "Cross-sell" do expect(page).to have_text("Check out this awesome cross-sell at https://cross-sell.com!") expect(page).to have_section("Offered product - Untitled 1") expect(page).to have_selector("[itemprop='price']", text: "$1 $0") expect(page).to have_link(href: product.long_url) click_on "Add to cart" end within_modal "Upsell" do expect(page).to have_text("Check out this awesome upsell at https://upsell.com!") expect(page).to have_radio_button("Untitled 2", text: "$1") click_on "Upgrade" end expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com") expect(page).to have_section("Product") expect(page).to have_section("Offered product - Untitled 1") expect(page).to have_section("Upsell product - Untitled 2") purchase1 = Purchase.second_to_last expect(purchase1.link).to eq(product) expect(purchase1.variant_attributes.first).to eq(product.alive_variants.first) expect(purchase1.upsell_purchase.upsell).to eq(cross_sell) expect(purchase1.upsell_purchase.selected_product).to eq(selected_product) expect(purchase1.offer_code).to eq(cross_sell.offer_code) purchase2 = Purchase.last expect(purchase2.upsell_purchase.upsell).to eq(upsell) expect(purchase2.upsell_purchase.selected_product).to eq(upsell_product) expect(purchase2.upsell_purchase.upsell_variant).to eq(upsell_variant) expect(purchase2.variant_attributes.first).to eq(upsell_product.alive_variants.second) end it "allows the buyer to decline each upsell at checkout" do visit upsell_product.long_url add_to_cart(upsell_product, option: "Untitled 1") visit selected_product.long_url add_to_cart(selected_product) fill_checkout_form(selected_product) click_on "Pay" within_modal "Cross-sell" do expect(page).to have_text("Check out this awesome cross-sell at https://cross-sell.com!") expect(page).to have_section("Offered product - Untitled 1") expect(page).to have_selector("[itemprop='price']", text: "$1 $0") expect(page).to have_link(href: product.long_url) click_on "Continue without adding" end within_modal "Upsell" do expect(page).to have_text("Check out this awesome upsell at https://upsell.com!") expect(page).to have_radio_button("Untitled 2", text: "$1") click_on "Don't upgrade" end expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com") purchase1 = Purchase.last expect(purchase1.upsell_purchase).to be_nil expect(purchase1.variant_attributes.first).to eq(upsell_product.alive_variants.first) purchase2 = Purchase.second_to_last expect(purchase2.upsell_purchase).to be_nil expect(purchase2.variant_attributes.first).to be_nil end end context "when the cross-sold products has additional required fields" do let!(:cross_sell) { create(:upsell, seller:, product: create(:product, :with_custom_fields, user: seller), selected_products: [selected_product], cross_sell: true) } it "validates those fields" do visit selected_product.long_url add_to_cart(selected_product) fill_checkout_form(selected_product) click_on "Pay" click_on "Add to cart" expect(find_field("Checkbox field")["aria-invalid"]).to eq("true") expect(find_field("I accept")["aria-invalid"]).to eq("true") end end context "when the upsell offered product/variant is already in the cart" do it "doesn't offer the upsell" do visit upsell_product.long_url add_to_cart(upsell_product, option: "Untitled 1") visit upsell_product.long_url add_to_cart(upsell_product, option: "Untitled 2") fill_checkout_form(upsell_product) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to have_section("Upsell product - Untitled 1") expect(page).to have_section("Upsell product - Untitled 2") end end context "when the cross-sell offered product is already in the cart" do it "doesn't offer the cross-sell" do visit product.long_url add_to_cart(product, option: "Untitled 1") visit selected_product.long_url add_to_cart(selected_product) check_out(selected_product) end end context "when the buyer has already purchased the offered product and variant" do let(:user) { create(:buyer_user) } let!(:purchase) { create(:purchase, link: product, variant_attributes: [product.alive_variants.first], purchaser: user) } it "doesn't offer the cross-sell" do login_as user visit selected_product.long_url add_to_cart(selected_product, logged_in_user: user) check_out(selected_product, logged_in_user: user) end context "when the buyer is the seller" do before do purchase.update!(purchaser: seller) end it "offers the cross-sell" do login_as seller visit selected_product.long_url add_to_cart(selected_product, logged_in_user: seller) fill_checkout_form(selected_product, logged_in_user: seller) click_on "Pay" within_modal "Cross-sell" do click_on "Add to cart" end expect(page).to have_text("Your purchase was successful!") within_section "Offered product (Untitled 1)" do expect(page).to have_text("This was a test purchase — you have not been charged (you are seeing this message because you are logged in as the creator).") end within_section "Product" do expect(page).to have_text("This was a test purchase — you have not been charged (you are seeing this message because you are logged in as the creator).") end end end end context "when the buyer has already purchased the offered variant" do let(:user) { create(:buyer_user) } let!(:purchase) { create(:purchase, link: upsell_product, variant_attributes: [upsell_product.alive_variants.second], purchaser: user) } it "doesn't offer the upsell" do login_as user visit upsell_product.long_url add_to_cart(upsell_product, option: "Untitled 1", logged_in_user: user) check_out(upsell_product, logged_in_user: user) end context "when the buyer is the seller" do before do purchase.update!(purchaser: seller) end it "offers the upsell" do login_as seller visit upsell_product.long_url add_to_cart(upsell_product, option: "Untitled 1", logged_in_user: seller) fill_checkout_form(upsell_product, logged_in_user: seller) click_on "Pay" within_modal "Upsell" do click_on "Upgrade" end expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to #{seller.email}") expect(page).to have_text("Upsell product - Untitled 2") end end end context "when the upsell has been deleted" do it "displays an error and allows the buyer to purchase without the upsell" do visit selected_product.long_url add_to_cart(selected_product) cross_sell.mark_deleted! fill_checkout_form(selected_product) click_on "Pay" expect do within_modal "Cross-sell" do click_on "Add to cart" end expect(page).to have_text("We charged your card and sent a receipt to test@gumroad.com") end.to change { Purchase.count }.by(1) purchase = Purchase.last expect(page).to have_link("View content", href: purchase.url_redirect.download_page_url) expect(page).to have_alert(text: "Sorry, this offer is no longer available.") expect(purchase.link).to eq(selected_product) visit checkout_index_path expect { check_out(product) }.to change { Purchase.count }.by(1) purchase = Purchase.last expect(purchase.link).to eq(product) expect(purchase.upsell_purchase).to be_nil end end context "when the buyer removes the cross-sell triggering product from the cart" do it "removes the cross-sell from the cart" do visit selected_product.long_url add_to_cart(selected_product) fill_checkout_form(selected_product) click_on "Pay" within_modal "Cross-sell" do click_on "Add to cart" end visit checkout_index_path expect(page).to have_text("Discounts US$-1", normalize_ws: true) within_cart_item "Product" do click_on "Remove" end check_out(product) purchase = Purchase.last expect(purchase.upsell_purchase).to be_nil expect(purchase.offer_code).to be_nil expect(purchase.price_cents).to eq(100) end end context "when the product has a content upsell" do it "allows checking out with the upsell product" do login_as seller product = create(:product, user: seller, name: "Sample product", price_cents: 1000) create(:purchase, :with_review, link: product) visit edit_link_path(product.unique_permalink) select_disclosure "Insert" do click_on "Upsell" end select_combo_box_option search: "Sample product", from: "Product" check "Add a discount to the offered product" choose "Fixed amount" fill_in "Fixed amount", with: "1" click_on "Insert" click_on "Save" expect(page).to have_alert(text: "Changes saved!") upsell = Upsell.last expect(upsell.product_id).to eq(product.id) expect(upsell.is_content_upsell).to be(true) expect(upsell.cross_sell).to be(true) expect(upsell.name).to eq(nil) expect(upsell.description).to eq(nil) expect(upsell.offer_code.amount_cents).to eq(100) expect(upsell.offer_code.amount_percentage).to be_nil expect(upsell.offer_code.universal).to be(false) expect(upsell.offer_code.product_ids).to eq([product.id]) logout visit product.long_url click_on "Sample product" fill_checkout_form(product) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = Purchase.last expect(purchase.link).to eq(product) expect(purchase.price_cents).to eq(900) expect(purchase.offer_code).to eq(upsell.offer_code) expect(purchase.offer_code.amount_cents).to eq(100) expect(purchase.upsell_purchase.upsell).to eq(upsell) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/affiliates_spec.rb
spec/requests/purchases/product/affiliates_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Product checkout - with affiliate", type: :system, js: true) do def set_affiliate_cookie browser = Capybara.current_session.driver.browser browser.manage.add_cookie(name: CGI.escape(affiliate.cookie_key), value: { value: Time.current.to_i, expires: affiliate.class.cookie_lifetime.from_now, httponly: true, domain: :all }.to_json) end shared_examples "credits the affiliate via a query param in the URL" do it "credits the affiliate for an eligible product purchase" do visit short_link_path(product.unique_permalink, param_name => affiliate.external_id_numeric) complete_purchase(product) purchase = Purchase.last expect(purchase.affiliate).to eq affiliate expect(purchase.affiliate_credit_cents).to eq 79 end it "adds the affiliate's cookie and links to the cart product if the affiliate is alive" do visit short_link_path(product.unique_permalink, param_name => affiliate.external_id_numeric) affiliate_cookie = Capybara.current_session.driver.browser.manage.all_cookies.find do |cookie| cookie[:name] == CGI.escape(affiliate.cookie_key) end expect(affiliate_cookie).to be_present add_to_cart(product) Selenium::WebDriver::Wait.new.until { Cart.alive.one? } expect(Cart.first.cart_products.first).to have_attributes(product:, affiliate:) end it "does not add the affiliate's cookie if the affiliate is deleted" do affiliate.mark_deleted! visit short_link_path(product.unique_permalink, param_name => affiliate.external_id_numeric) affiliate_cookie = Capybara.current_session.driver.browser.manage.all_cookies.find do |cookie| cookie[:name] == CGI.escape(affiliate.cookie_key) end expect(affiliate_cookie).not_to be_present end it "does not credit the affiliate for an ineligible product purchase" do visit short_link_path(ineligible_product.unique_permalink, param_name => affiliate.external_id_numeric) complete_purchase(ineligible_product) purchase = Purchase.last expect(purchase.affiliate).to eq nil expect(purchase.affiliate_credit_cents).to eq 0 end end shared_examples "credits the affiliate via query params in the URL" do context "`affiliate_id` query param" do it_behaves_like "credits the affiliate via a query param in the URL" do subject(:param_name) { "affiliate_id" } end end context "`a` query param" do it_behaves_like "credits the affiliate via a query param in the URL" do subject(:param_name) { "a" } end end end shared_examples "credits the affiliate via their affiliate referral URL" do it "credits the affiliate for an eligible product purchase" do visit affiliate.referral_url_for_product(product) complete_purchase(product) purchase = Purchase.last expect(purchase.affiliate).to eq affiliate expect(purchase.affiliate_credit_cents).to eq 79 end it "adds the affiliate's cookie if the affiliate is alive" do visit affiliate.referral_url_for_product(product) affiliate_cookie = Capybara.current_session.driver.browser.manage.all_cookies.find do |cookie| cookie[:name] == CGI.escape(affiliate.cookie_key) end expect(affiliate_cookie).to be_present expect(affiliate_cookie[:expires]).to be_within(5.minutes).of(cookie_expiry) end it "does not add the affiliate's cookie if the affiliate is deleted" do affiliate.mark_deleted! visit affiliate.referral_url_for_product(product) affiliate_cookie = Capybara.current_session.driver.browser.manage.all_cookies.find do |cookie| cookie[:name] == CGI.escape(affiliate.cookie_key) end expect(affiliate_cookie).not_to be_present end end shared_examples "credits the affiliate via affiliate cookie" do it "credits the affiliate for an eligible product purchase" do visit short_link_path(product.unique_permalink) add_to_cart(product) set_affiliate_cookie check_out(product) purchase = Purchase.last expect(purchase.affiliate).to eq affiliate expect(purchase.affiliate_credit_cents).to eq 79 end it "does not credit the affiliate for an ineligible product purchase" do visit short_link_path(ineligible_product.unique_permalink) add_to_cart(ineligible_product) set_affiliate_cookie check_out(ineligible_product) purchase = Purchase.last expect(purchase.affiliate).to eq nil expect(purchase.affiliate_credit_cents).to eq 0 end end let(:product) { create(:product, :recommendable, price_cents: 1000) } let(:seller) { product.user } context "for a direct affiliate" do let(:ineligible_product) { create(:product, user: seller, price_cents: 2000) } let(:affiliate) { create(:direct_affiliate, seller:, products: [product], affiliate_basis_points: 1000) } let(:cookie_expiry) { 30.days.from_now.to_datetime } it_behaves_like "credits the affiliate via affiliate cookie" it_behaves_like "credits the affiliate via query params in the URL" it_behaves_like "credits the affiliate via their affiliate referral URL" it "redirects the user to an eligible product page from an ineligible product referral URL" do visit affiliate.referral_url_for_product(ineligible_product) expect(current_path).to eq short_link_path(product) end end context "for a global affiliate" do let(:ineligible_product) { create(:product, price_cents: 2000) } let(:affiliate) { create(:user).global_affiliate } let(:cookie_expiry) { 7.days.from_now.to_datetime } it_behaves_like "credits the affiliate via affiliate cookie" it_behaves_like "credits the affiliate via query params in the URL" it_behaves_like "credits the affiliate via their affiliate referral URL" it "does not credit the affiliate for an ineligible product purchase via the affiliate referral URL" do visit affiliate.referral_url_for_product(ineligible_product) complete_purchase(ineligible_product) purchase = Purchase.last expect(purchase.affiliate).to eq nil expect(purchase.affiliate_credit_cents).to eq 0 end it "associates the affiliate with the product" do expect do visit affiliate.referral_url_for_product(product) complete_purchase(product) end.to change { product.reload.global_affiliates.where(id: affiliate.id).count }.from(0).to(1) end it "does not associate the affiliate with the product if it is already associated" do product.affiliates << affiliate expect do visit affiliate.referral_url_for_product(product) complete_purchase(product) end.not_to change { product.reload.global_affiliates.where(id: affiliate.id).count } end context "when purchase is made via Discover" do it "credits the affiliate if the seller participates in Discover" do visit short_link_path(product.unique_permalink, affiliate_id: affiliate.external_id_numeric, recommended_by: "discover") complete_purchase(product, recommended_by: "discover", affiliate_id: affiliate.external_id_numeric) purchase = Purchase.last expect(purchase.affiliate).to eq affiliate expect(purchase.affiliate_credit_cents).to eq 70 end it "does not credit the affiliate if the seller has opted out of Discover" do visit short_link_path(ineligible_product.unique_permalink, affiliate_id: affiliate.external_id_numeric, recommended_by: "discover") complete_purchase(ineligible_product, recommended_by: "discover", affiliate_id: affiliate.external_id_numeric) purchase = Purchase.last expect(purchase.affiliate).to eq nil end end end context "with multiple affiliate cookies" do it "credits the latest eligible affiliate" do product = create(:product, :recommendable, user: seller, price_cents: 1000) last_affiliate = create(:direct_affiliate, seller: product.user) create(:product_affiliate, product:, affiliate: last_affiliate, affiliate_basis_points: 2000) travel_to 2.days.ago do visit short_link_path(product.unique_permalink, affiliate_id: create(:direct_affiliate, seller:, products: [product]).external_id_numeric) end travel_to 1.day.ago do visit short_link_path(product.unique_permalink, affiliate_id: last_affiliate.external_id_numeric) end visit short_link_path(product.unique_permalink, affiliate_id: create(:direct_affiliate).external_id_numeric) complete_purchase(product) purchase = Purchase.last expect(purchase.affiliate_id).to eq last_affiliate.id expect(purchase.affiliate_credit_cents).to eq 158 end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/subscription_purchases_spec.rb
spec/requests/purchases/product/subscription_purchases_spec.rb
# frozen_string_literal: true require("spec_helper") require "timeout" describe("Subscription Purchases from the product page", type: :system, js: true) do context "purchasing memberships with multiple tiers" do before do @membership_product = create(:membership_product_with_preset_tiered_pricing) tier_category = @membership_product.tier_category @first_tier = tier_category.variants.first @second_tier = tier_category.variants.last @second_tier.update!(max_purchase_count: 1) end it "allows the user to purchase a tier" do visit "/l/#{@membership_product.unique_permalink}" expect(page).to have_radio_button("Second Tier", text: "1 left") add_to_cart(@membership_product, option: "Second Tier") check_out(@membership_product) end context "with multiple recurrences" do before do @first_tier.save_recurring_prices!("monthly" => { enabled: true, price: 2 }, "yearly" => { enabled: true, price: 10 }) @second_tier.save_recurring_prices!("monthly" => { enabled: true, price: 3 }, "yearly" => { enabled: true, price: 14 }) end it "allows to switch the recurrence and shows tiers' prices for that recurrence" do visit "/l/#{@membership_product.unique_permalink}" select "Yearly", from: "Recurrence" expect(page).to have_radio_button("First Tier", text: "$10") expect(page).to have_radio_button("Second Tier", text: "$14") select "Monthly", from: "Recurrence" expect(page).to have_radio_button("First Tier", text: "$2") expect(page).to have_radio_button("Second Tier", text: "$3") end it "proceeds with the purchase successfully after making a recurrence and tier selection" do visit "/l/#{@membership_product.unique_permalink}" select "Yearly", from: "Recurrence" expect(page).to have_radio_button("First Tier", text: "$10") expect(page).to have_radio_button("Second Tier", text: "$14") add_to_cart(@membership_product, option: "Second Tier") expect(page).to have_text("Total US$14", normalize_ws: true) check_out(@membership_product) purchase = Purchase.successful.last expect(purchase.subscription.price).to eq @membership_product.prices.find_by!(recurrence: BasePrice::Recurrence::YEARLY) expect(purchase.variant_attributes.map(&:id)).to eq [@second_tier.id] expect(purchase.custom_fee_per_thousand).to be_nil expect(purchase.fee_cents).to eq(261) # 10% of $14 + 50c + 2.9% of $14 + 30c @membership_product.user.update!(custom_fee_per_thousand: 25) travel_to(1.year.from_now) expect(purchase.seller.reload.custom_fee_per_thousand).to eq(25) RecurringChargeWorker.new.perform(purchase.subscription.id) recurring_charge = purchase.subscription.purchases.successful.last expect(purchase.subscription.purchases.successful.count).to eq(2) expect(recurring_charge.custom_fee_per_thousand).to be_nil expect(recurring_charge.fee_cents).to eq(261) end it "charges custom Gumroad fee if custom fee is set for the seller" do @membership_product.user.update!(custom_fee_per_thousand: 50) visit "/l/#{@membership_product.unique_permalink}" select "Yearly", from: "Recurrence" expect(page).to have_radio_button("First Tier", text: "$10") expect(page).to have_radio_button("Second Tier", text: "$14") add_to_cart(@membership_product, option: "Second Tier") expect(page).to have_text("Total US$14", normalize_ws: true) check_out(@membership_product) purchase = Purchase.successful.last expect(purchase.subscription.price).to eq @membership_product.prices.find_by!(recurrence: BasePrice::Recurrence::YEARLY) expect(purchase.variant_attributes.map(&:id)).to eq [@second_tier.id] expect(purchase.custom_fee_per_thousand).to eq(50) expect(purchase.fee_cents).to eq(191) # 5% of $14 + 50c + 2.9% of $14 + 30c @membership_product.user.update!(custom_fee_per_thousand: 25) travel_to(1.year.from_now) expect(purchase.seller.reload.custom_fee_per_thousand).to eq(25) RecurringChargeWorker.new.perform(purchase.subscription.id) recurring_charge = purchase.subscription.purchases.successful.last expect(purchase.subscription.purchases.successful.count).to eq(2) expect(recurring_charge.custom_fee_per_thousand).to eq(50) expect(recurring_charge.fee_cents).to eq(191) end context "when a tier has pay-what-you-want enabled" do before do @second_tier.update!(customizable_price: true) @second_tier.save_recurring_prices!("monthly" => { enabled: true, price: 3, suggested_price: 5 }, "yearly" => { enabled: true, price: 14, suggested_price: 20 }) end it "reflects PWYW-ability in the price tag of that tier (and that tier only)" do visit "/l/#{@membership_product.unique_permalink}" expect(page).to have_radio_button("First Tier", text: "$2") expect(page).to have_radio_button("Second Tier", text: "$3+") select "Yearly", from: "Recurrence" expect(page).to have_radio_button("First Tier", text: "$10") expect(page).to have_radio_button("Second Tier", text: "$14+") end it "shows the PWYW input when selecting that tier with an appropriate suggested price for the current recurrence" do visit "/l/#{@membership_product.unique_permalink}" expect(page).not_to have_field("Name a fair price") choose "Second Tier" expect(page).to have_field("Name a fair price", placeholder: "5+", with: "") select "Yearly", from: "Recurrence" expect(page).to have_field("Name a fair price", placeholder: "20+", with: "") end it "does not allow the user to proceed with a price lower than the tier's minimum price for the current recurrence" do visit "/l/#{@membership_product.unique_permalink}" expect(page).not_to have_field("Name a fair price") choose "Second Tier" expect(page).to have_field("Name a fair price", placeholder: "5+", with: "") fill_in "Name a fair price", with: "2" click_on "Subscribe" expect(find_field("Name a fair price")["aria-invalid"]).to eq("true") add_to_cart(@membership_product, pwyw_price: 3, option: "Second Tier") expect(page).to have_text("Total US$3", normalize_ws: true) visit "/l/#{@membership_product.unique_permalink}" expect(page).not_to have_field("Name a fair price") choose "Second Tier" select "Yearly", from: "Recurrence" expect(page).to have_field("Name a fair price", placeholder: "20+", with: "") fill_in "Name a fair price", with: "10" click_on "Subscribe" expect(find_field("Name a fair price")["aria-invalid"]).to eq("true") add_to_cart(@membership_product, pwyw_price: 20, option: "Second Tier") expect(page).to have_text("Total US$20", normalize_ws: true) end it "proceeds with the purchase successfully when a valid custom price is entered" do visit "/l/#{@membership_product.unique_permalink}" expect(page).not_to have_field("Name a fair price") add_to_cart(@membership_product, option: "Second Tier", recurrence: "Yearly", pwyw_price: 20) expect(page).to have_text("Total US$20", normalize_ws: true) check_out(@membership_product) purchase = Purchase.successful.last expect(purchase.price_cents).to eq 20_00 expect(purchase.subscription.price).to eq @membership_product.prices.find_by!(recurrence: BasePrice::Recurrence::YEARLY) expect(purchase.variant_attributes.map(&:id)).to eq [@second_tier.id] end it "hides the PWYW input when selecting a tier with no PWYW option" do visit "/l/#{@membership_product.unique_permalink}" expect(page).not_to have_field("Name a fair price") choose "Second Tier" expect(page).to have_field("Name a fair price") choose "First Tier" expect(page).not_to have_field("Name a fair price") end end end context "when a tier has hit the active subscriber limit" do it "does not allow the user to purchase that tier" do create(:purchase, link: @membership_product, variant_attributes: [@second_tier]) visit "/l/#{@membership_product.unique_permalink}" expect(page).to have_radio_button("Second Tier", disabled: true) end end end it "assigns license keys to subscription purchases" do link = create(:product, is_recurring_billing: true, is_licensed: true, subscription_duration: :monthly) visit("/l/#{link.unique_permalink}") add_to_cart(link) check_out(link) purchase = Purchase.last expect(purchase.link).to eq link expect(purchase.license).to_not be(nil) expect(purchase.link.licenses.count).to eq 1 end describe "purchasing memberships with free trials" do before do @membership_product = create(:membership_product_with_preset_tiered_pricing, free_trial_enabled: true, free_trial_duration_amount: 1, free_trial_duration_unit: :week) end it "does not immediately charge the user" do visit "/l/#{@membership_product.unique_permalink}" add_to_cart(@membership_product, option: "First Tier") expect(page).to have_text("one week free") expect(page).to have_text("$3 monthly after") check_out(@membership_product) expect(page).not_to have_content "We charged your card" expect(page).to have_content "We sent a receipt to test@gumroad.com" purchase = Purchase.last expect(purchase.purchase_state).to eq "not_charged" expect(purchase.displayed_price_cents).to eq 300 expect(purchase.stripe_transaction_id).to be_nil expect(purchase.subscription).to be_alive expect(purchase.should_exclude_product_review?).to eq true end context "with an SCA-enabled card" do it "succeeds and does not immediately charge the user" do visit @membership_product.long_url add_to_cart(@membership_product, option: "First Tier") expect(page).to have_text("one week free") expect(page).to have_text("$3 monthly after") check_out(@membership_product, credit_card: { number: CardParamsSpecHelper.card_number(:success_with_sca) }, sca: true) expect(page).not_to have_content "We charged your card" expect(page).to have_content "We sent a receipt to test@gumroad.com" purchase = Purchase.last expect(purchase.purchase_state).to eq "not_charged" expect(purchase.displayed_price_cents).to eq 300 expect(purchase.stripe_transaction_id).to be_nil expect(purchase.subscription).to be_alive end end context "when the purchaser has already purchased the product and is ineligible for a free trial" do it "displays an error message" do email = generate(:email) purchaser = create(:user, email:) create(:free_trial_membership_purchase, link: @membership_product, email:, purchaser:, succeeded_at: 2.months.ago) visit "/l/#{@membership_product.unique_permalink}" expect do add_to_cart(@membership_product, option: "First Tier") expect(page).to have_text("one week free") expect(page).to have_text("$3 monthly after") check_out(@membership_product, email:, error: true) expect(page).to have_alert "You've already purchased this product and are ineligible for a free trial" end.not_to change { Purchase.count } end end end describe "gifting a subscription" do let(:giftee_email) { "giftee@example.com" } let(:membership_product) { create(:membership_product_with_preset_tiered_pricing) } context "when it does not offer a trial" do it "complete purchase, gift the subscription and prevents recurring billing" do visit "/l/#{membership_product.unique_permalink}" add_to_cart(membership_product, option: "First Tier") expect do check_out(membership_product, gift: { email: giftee_email, note: "Gifting from product page!" }) end.to change { Subscription.count }.by(1) expect(Purchase.all_success_states.count).to eq 2 fill_in "Password", with: "password" click_button "Sign up" expect(page).to have_text("Done! Your account has been created.") subscription = Subscription.last expect(subscription.gift?).to eq true expect(subscription.user).to be_nil expect(subscription.email).to eq giftee_email expect(subscription.credit_card).to be_nil expect do travel_to(subscription.end_time_of_subscription + 1.day) do subscription.charge! end end.to change { subscription.purchases.successful.count }.by(0) purchase = subscription.purchases.last expect(purchase.purchase_state).to eq "failed" expect(purchase.error_code).to eq "credit_card_not_provided" end end context "when it offers a trial" do let(:membership_product) { create(:membership_product_with_preset_tiered_pricing, free_trial_enabled: true, free_trial_duration_amount: 1, free_trial_duration_unit: :week) } it "imediately charges the gifter and gifts the subscription" do visit "/l/#{membership_product.unique_permalink}" add_to_cart(membership_product, option: "First Tier") expect(page).to have_text("one week free") expect(page).to have_text("$3 monthly after") expect(page).to have_text("Total US$0", normalize_ws: true) expect(page).to_not have_text("1 month") check "Give as a gift" expect(page).to_not have_text("one week free") expect(page).to_not have_text("$3 monthly after") expect(page).to have_text("1 month") expect(page).to have_text("Total US$3", normalize_ws: true) uncheck "Give as a gift" expect(page).to have_text("one week free") expect(page).to have_text("$3 monthly after") expect do check_out(membership_product, gift: { email: giftee_email, note: "Gifting from product page!" }) end.to change { Subscription.count }.by(1) expect(Purchase.all_success_states.count).to eq 2 subscription = Subscription.last expect(subscription.credit_card).to be_nil expect(subscription.gift?).to eq true expect(subscription.user).to be_nil purchase = subscription.original_purchase expect(purchase.purchase_state).to eq "successful" expect(purchase.is_gift_sender_purchase).to eq true expect(purchase.email).to eq "test@gumroad.com" expect(purchase.gift).to have_attributes( link: membership_product, gift_note: "Gifting from product page!" ) expect(purchase.gift.giftee_purchase).to have_attributes( email: giftee_email, is_original_subscription_purchase: 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/requests/purchases/product/purchasing_power_parity_spec.rb
spec/requests/purchases/product/purchasing_power_parity_spec.rb
# frozen_string_literal: true require("spec_helper") describe "Purchasing power parity", type: :system, js: true do before do @user = create(:user, purchasing_power_parity_enabled: true, display_offer_code_field: true) @product = create(:product, price_cents: 999, user: @user) @membership = create(:membership_product_with_preset_tiered_pricing, user: @user) PurchasingPowerParityService.new.set_factor("LV", 0.49) allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("109.110.31.255") end describe "classic product" do context "when the product has purchasing_power_parity_disabled" do before do @product.update! purchasing_power_parity_disabled: true end it "doesn't apply the PPP discount" do visit @product.long_url expect(page).to_not have_selector("[itemprop='price']", text: "$4.90") expect(page).to_not have_selector("[role='status']", text: "This product supports purchasing power parity.") add_to_cart(@product) check_out(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(999) expect(purchase.is_purchasing_power_parity_discounted).to eq(false) end end context "when the card country matches the IP country" do it "applies the PPP discount" do visit @product.long_url expect(page).to have_selector("[itemprop='price']", text: "$9.99 $4.90") expect(page).to have_selector("[role='status']", text: "This product supports purchasing power parity. Because you're located in Latvia, the price has been discounted by 51% to $4.90.") add_to_cart(@product) check_out(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(490) expect(purchase.is_purchasing_power_parity_discounted).to eq(true) end end context "when the card country doesn't match the IP country" do it "doesn't apply the PPP discount" do visit @product.long_url expect(page).to have_selector("[itemprop='price']", text: "$9.99 $4.90") expect(page).to have_selector("[role='status']", text: "This product supports purchasing power parity. Because you're located in Latvia, the price has been discounted by 51% to $4.90.") add_to_cart(@product) check_out(@product, zip_code: nil, error: "In order to apply a purchasing power parity discount, you must use a card issued in the country you are in. Please try again with a local card, or remove the discount during checkout.") visit checkout_index_path ppp_pill = find_button("Purchasing power parity discount") ppp_pill.hover expect(ppp_pill).to have_tooltip(text: "This discount is applied based on the cost of living in your country.") ppp_pill.click check_out(@product, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(999) expect(purchase.is_purchasing_power_parity_discounted).to eq(false) # Test that the discount is reset after purchase and when a new item is added to the cart visit @product.long_url add_to_cart(@product) click_on "Purchasing power parity discount" visit @product.long_url add_to_cart(@product) expect(page).to have_button("Purchasing power parity discount") end end context "when the price gets discounted below the currency's minimum" do it "rounds the price up to the minimum" do @product.update!(price_cents: 100) visit @product.long_url expect(page).to have_selector("[itemprop='price']", text: "$1 $0.99") expect(page).to have_selector("[role='status']", text: "This product supports purchasing power parity. Because you're located in Latvia, the price has been discounted by 1% to $0.99.") add_to_cart(@product) check_out(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(99) expect(purchase.is_purchasing_power_parity_discounted).to eq(true) end end context "when the seller has set a limit to the PPP discount" do it "caps the PPP discount at the limit" do @user.update!(purchasing_power_parity_limit: 30) visit @product.long_url expect(page).to have_selector("[itemprop='price']", text: "$9.99 $6.99") expect(page).to have_selector("[role='status']", text: "This product supports purchasing power parity. Because you're located in Latvia, the price has been discounted by 30% to $6.99.") add_to_cart(@product) check_out(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(699) expect(purchase.is_purchasing_power_parity_discounted).to eq(true) end end end describe "PWYW product" do context "when the product has purchasing_power_parity_disabled" do before do @product.update!(purchasing_power_parity_disabled: true, customizable_price: true) end it "doesn't apply the PPP discount" do visit @product.long_url expect(page).to_not have_selector("[itemprop='price']", text: "$4.90+") expect(page).to_not have_selector("[role='status']", text: "This product supports purchasing power parity.") add_to_cart(@product, pwyw_price: 12.00) check_out(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(1200) expect(purchase.is_purchasing_power_parity_discounted).to eq(false) end end it "applies the PPP discount" do @product.update!(customizable_price: true) visit @product.long_url expect(page).to have_selector("[itemprop='price']", text: "$9.99 $4.90+") expect(page).to have_selector("[role='status']", text: "This product supports purchasing power parity. Because you're located in Latvia, the price has been discounted by 51% to $4.90.") add_to_cart(@product, pwyw_price: 5.44, ppp_factor: 0.49) check_out(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(544) expect(purchase.is_purchasing_power_parity_discounted).to eq(true) end end describe "membership product" do context "when the product has purchasing_power_parity_disabled" do before do @membership.update!(purchasing_power_parity_disabled: true) end it "doesn't apply the PPP discount" do visit @membership.long_url expect(page).to_not have_selector("[role='status']", text: "This product supports purchasing power parity.") expect(page).to_not have_radio_button("First Tier", text: "$1.47 a month") expect(page).to_not have_radio_button("Second Tier", text: "$2.45 a month") add_to_cart(@membership, option: "First Tier") check_out(@membership, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(300) expect(purchase.is_purchasing_power_parity_discounted).to eq(false) select_disclosure "Membership" do click_on "Manage" end expect(page).to have_current_path(magic_link_subscription_path(purchase.subscription.external_id)) expect(page).to have_text "Send magic link" click_on "Send magic link" expect(page).to have_current_path(magic_link_subscription_path(purchase.subscription.external_id)) expect(page).to have_text "We've sent a link to" visit manage_subscription_path(purchase.subscription.external_id, token: purchase.reload.subscription.token) expect(page).to have_radio_button("First Tier", text: "$3 a month") end end it "applies the PPP discount" do visit @membership.long_url expect(page).to have_selector("[role='status']", text: "This product supports purchasing power parity. Because you're located in Latvia, the price has been discounted by 51% to $1.47.") expect(page).to have_radio_button("First Tier", text: /\$3\s+\$1\.47 a month/) expect(page).to have_radio_button("Second Tier", text: /\$5\s+\$2\.45 a month/) add_to_cart(@membership, option: "First Tier") check_out(@membership, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(147) expect(purchase.is_purchasing_power_parity_discounted).to eq(true) select_disclosure "Membership" do click_on "Manage" end expect(page).to have_current_path(magic_link_subscription_path(purchase.subscription.external_id)) expect(page).to have_text "Send magic link" click_on "Send magic link" expect(page).to have_current_path(magic_link_subscription_path(purchase.subscription.external_id)) expect(page).to have_text "We've sent a link to" visit manage_subscription_path(purchase.subscription.external_id, token: purchase.reload.subscription.token) expect(page).to have_radio_button("First Tier", text: "$1.47 a month") end end describe "discounted product" do context "when the offer code provides a lesser discount than PPP" do before do @offer_code = create(:offer_code, products: [@product]) end context "when the product has purchasing_power_parity_disabled" do before do @product.update!(purchasing_power_parity_disabled: true) end it "applies the offer code but not the PPP discount" do visit "#{@product.long_url}/#{@offer_code.code}" expect(page).to_not have_selector("[itemprop='price']", text: "$4.90") expect(page).to_not have_selector("[role='status']", text: "This product supports purchasing power parity.") add_to_cart(@product, offer_code: @offer_code) fill_in "Discount code", with: @offer_code.code click_on "Apply" expect(page).to_not have_alert(text: "The offer code will not be applied because the purchasing power parity discount is greater than the offer code discount for all products.") expect(page).to have_selector("[aria-label='Discount code']", text: @offer_code.code) check_out(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(899) expect(purchase.is_purchasing_power_parity_discounted).to eq(false) end end it "applies the PPP discount" do visit "#{@product.long_url}/#{@offer_code.code}" expect(page).to have_selector("[itemprop='price']", text: "$9.99 $4.90") expect(page).to have_selector("[role='status']", text: "This product supports purchasing power parity. Because you're located in Latvia, the price has been discounted by 51% to $4.90. This discount will be applied because it is greater than the offer code discount.") add_to_cart(@product) fill_in "Discount code", with: @offer_code.code click_on "Apply" expect(page).to have_alert(text: "The offer code will not be applied because the purchasing power parity discount is greater than the offer code discount for all products.") expect(page).to_not have_selector("[aria-label='Discount code']", text: @offer_code.code) check_out(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(490) expect(purchase.is_purchasing_power_parity_discounted).to eq(true) end end context "when the offer code provides a greater discount than PPP for some but not all products" do before do @product2 = create(:product, price_cents: 1000) @offer_code = create(:offer_code, products: [@product]) @offer_code2 = create(:offer_code, code: @offer_code.code, amount_cents: 900, products: [@product2]) end it "only applies the PPP discount to the product for which the offer code discount is less" do visit @product.long_url add_to_cart(@product) visit @product2.long_url add_to_cart(@product2) fill_in "Discount code", with: @offer_code.code click_on "Apply" expect(page).to have_alert(text: "The offer code will not be applied to some products for which the purchasing power parity discount is greater than the offer code discount.") expect(page).to have_selector("[aria-label='Discount code']", text: @offer_code.code) expect(page).to have_text("Discounts Purchasing power parity discount #{@offer_code.code} US$-14.09", normalize_ws: true) check_out(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) first_purchase = Purchase.second_to_last second_purchase = Purchase.last expect(first_purchase.price_cents).to eq(100) expect(first_purchase.is_purchasing_power_parity_discounted).to eq(false) expect(second_purchase.price_cents).to eq(490) expect(second_purchase.is_purchasing_power_parity_discounted).to eq(true) end end context "when the offer code provides a greater discount than PPP" do before do @offer_code = create(:offer_code, amount_cents: 900, products: [@product]) end it "doesn't apply the PPP discount" do visit "#{@product.long_url}/#{@offer_code.code}" expect(page).to have_selector("[itemprop='price']", text: "$9.99 $0.99") expect(page).to have_selector("[role='status']", text: "$9 off will be applied at checkout (Code #{@offer_code.code.upcase})") expect(page).to_not have_selector("[role='status']", text: "This product supports purchasing power parity.") add_to_cart(@product, offer_code: @offer_code) check_out(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(99) expect(purchase.is_purchasing_power_parity_discounted).to eq(false) end end end describe "free product" do before do @product.update(customizable_price: true, price_cents: 0) end it "does not apply the PPP discount" do visit @product.long_url expect(page).to have_selector("[itemprop='price']", text: "$0") expect(page).to_not have_selector("[role='status']", text: "This product supports purchasing power parity.") add_to_cart(@product, pwyw_price: 0) check_out(@product, is_free: true) purchase = Purchase.last expect(purchase.price_cents).to eq(0) expect(purchase.is_purchasing_power_parity_discounted).to eq(false) end end describe "cross-sell product with discount" do before do @cross_sell_product = create(:product, name: "Cross-sell product", user: @user, price_cents: 1000) @cross_sell = create(:upsell, seller: @user, product: @cross_sell_product, selected_products: [@product], offer_code: create(:offer_code, user: @user, products: [@cross_sell_product]), cross_sell: true) end it "doesn't apply the PPP discount" do visit @product.long_url expect(page).to have_selector("[itemprop='price']", text: "$9.99 $4.90") expect(page).to have_selector("[role='status']", text: "This product supports purchasing power parity. Because you're located in Latvia, the price has been discounted by 51% to $4.90.") add_to_cart(@product) fill_checkout_form(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) click_on "Pay" within_modal "Take advantage of this excellent offer!" do click_on "Add to cart" end expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = Purchase.second_to_last expect(purchase.price_cents).to eq(490) expect(purchase.is_purchasing_power_parity_discounted).to eq(true) cross_sell_purchase = Purchase.last expect(cross_sell_purchase.purchase_state).to eq("successful") expect(cross_sell_purchase.displayed_price_cents).to eq(900) expect(cross_sell_purchase.offer_code).to eq(@cross_sell.offer_code) expect(cross_sell_purchase.upsell_purchase.selected_product).to eq(@product) expect(cross_sell_purchase.upsell_purchase.upsell).to eq(@cross_sell) end end context "when payment verification is disabled" do before do @user.update!(purchasing_power_parity_payment_verification_disabled: true) end it "doesn't require the customer's payment method to match their country" do visit @product.long_url expect(page).to have_selector("[itemprop='price']", text: "$9.99 $4.90") expect(page).to have_selector("[role='status']", text: "This product supports purchasing power parity. Because you're located in Latvia, the price has been discounted by 51% to $4.90.") add_to_cart(@product) check_out(@product, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(490) expect(purchase.is_purchasing_power_parity_discounted).to eq(true) end context "when the product has purchasing_power_parity_disabled" do before do @product.update! purchasing_power_parity_disabled: true end it "doesn't apply the PPP discount" do visit @product.long_url expect(page).to_not have_selector("[itemprop='price']", text: "$4.90") expect(page).to_not have_selector("[role='status']", text: "This product supports purchasing power parity.") add_to_cart(@product) check_out(@product, credit_card: { number: "4000004280000005" }, zip_code: nil) purchase = Purchase.last expect(purchase.price_cents).to eq(999) expect(purchase.is_purchasing_power_parity_discounted).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/requests/purchases/product/collaborators_spec.rb
spec/requests/purchases/product/collaborators_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Product checkout - with collaborator", type: :system, js: true) do let(:product) { create(:product, :recommendable, price_cents: 20_00) } let!(:collaborator) { create(:collaborator, affiliate_basis_points: 50_00, products: [product]) } it "credits the collaborator if the product has a collaborator" do visit short_link_path(product.unique_permalink) complete_purchase(product) purchase = Purchase.last expect(purchase.affiliate).to eq collaborator expect(purchase.affiliate_credit_cents).to eq 10_00 - (purchase.fee_cents * 0.5) end context "when an affiliate is set" do it "ignores the affiliate" do affiliate = create(:user).global_affiliate # products with collaborators can't have direct affiliates visit affiliate.referral_url_for_product(product) complete_purchase(product) purchase = Purchase.last expect(purchase.affiliate).to eq collaborator expect(purchase.affiliate_credit_cents).to eq 10_00 - (purchase.fee_cents * 0.5) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/offer_codes_spec.rb
spec/requests/purchases/product/offer_codes_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Offer-code usage from product page", type: :system, js: true) do it "accepts an offer code that's larger than the price of the product" do product = create(:product, price_cents: 300) offer_code = create(:offer_code, products: [product], amount_cents: 500) visit URI::DEFAULT_PARSER.escape("/l/#{product.unique_permalink}/#{offer_code.code}") add_to_cart(product, offer_code:) check_out(product, is_free: true) purchase = Purchase.last discount = purchase.purchase_offer_code_discount expect(purchase.price_cents).to eq 0 expect(purchase.offer_code).to eq offer_code expect(discount.offer_code_amount).to eq 500 expect(discount.offer_code_is_percent).to eq false expect(discount.pre_discount_minimum_price_cents).to eq 300 end it "accepts a non-ascii offer code from a shared URL" do product = create(:product, price_cents: 350) variant_category_1 = create(:variant_category, link: product) %w[Base Premium].each_with_index { |name, index| create(:variant, name:, variant_category: variant_category_1, price_difference_cents: 100 * index) } offer_code = create(:offer_code, products: [product], amount_cents: 350, name: "ÕËëæç") visit URI::DEFAULT_PARSER.escape("/l/#{product.unique_permalink}/#{offer_code.code}") expect(page).to have_selector("[itemprop='price']", text: "$3.50 $0", visible: false) expect(page).to have_selector("[role='status']", text: "$3.50 off will be applied at checkout (Code #{offer_code.code.upcase})") expect(page).to have_radio_button("Base", text: /\$3\.50\s+\$0/) expect(page).to have_radio_button("Premium", text: /\$4\.50\s+\$1/) add_to_cart(product, offer_code:, option: "Base") check_out(product, is_free: true) expect(Purchase.last.price_cents).to eq 0 end it "recognizes a plain ascii offer code from a shared URL" do product = create(:product, price_cents: 300) offer_code = create(:offer_code, products: [product], amount_cents: 100, name: "boringcode") visit "/l/#{product.unique_permalink}/#{offer_code.code}" add_to_cart(product, offer_code:) check_out(product) expect(Purchase.last.price_cents).to eq 200 expect(Purchase.last.total_transaction_cents).to eq 200 end it "does not treat a trailing slash in the URL as an offer code" do link = create(:product, price_cents: 300) visit "/l/#{link.unique_permalink}/" add_to_cart(link) check_out(link) expect(Purchase.last.price_cents).to eq 300 expect(Purchase.last.total_transaction_cents).to eq 300 end it "recognizes a universal offer code from a shared URL" do link = create(:product, price_cents: 300) offer_code = create(:universal_offer_code, user: link.user, amount_cents: 150, name: "universalcode") visit "/l/#{link.unique_permalink}/#{offer_code.code}" add_to_cart(link, offer_code:) check_out(link) expect(Purchase.last.price_cents).to eq(150) expect(Purchase.last.total_transaction_cents).to eq(150) end it "recognizes a universal offer code from a username.gumroad.com based share URL" do link = create(:product, price_cents: 300) offer_code = create(:universal_offer_code, user: link.user, amount_cents: 150, name: "universalcode") visit "#{link.user.subdomain_with_protocol}/l/#{link.unique_permalink}/#{offer_code.code}" add_to_cart(link, offer_code:) check_out(link) expect(Purchase.last.price_cents).to eq(150) expect(Purchase.last.total_transaction_cents).to eq(150) end it "calculates percentage discounts from non-even amounts properly and goes through" do product = create(:product, price_cents: 4999) offer_code = create(:percentage_offer_code, products: [product], amount_percentage: 50) visit URI::DEFAULT_PARSER.escape("/l/#{product.unique_permalink}/#{offer_code.code}") add_to_cart(product, offer_code:) expect(page).to have_text("Total US$24.99", normalize_ws: true) check_out(product) purchase = Purchase.last discount = purchase.purchase_offer_code_discount expect(purchase).to be_successful expect(purchase.price_cents).to eq 2499 expect(purchase.offer_code).to eq offer_code expect(discount.offer_code_amount).to eq 50 expect(discount.offer_code_is_percent).to eq true expect(discount.pre_discount_minimum_price_cents).to eq 4999 end it "handles rounding edge cases properly" do product = create(:product, price_cents: 1395) offer_code = create(:percentage_offer_code, products: [product], amount_percentage: 70) visit URI::DEFAULT_PARSER.escape("/l/#{product.unique_permalink}/#{offer_code.code}") add_to_cart(product, offer_code:) expect(page).to have_text("Total US$4.19", normalize_ws: true) check_out(product) purchase = Purchase.last expect(purchase.price_cents).to eq 419 expect(purchase.offer_code).to eq offer_code end it "doesn't render the offer code status for $0 offer codes" do product = create(:product, price_cents: 300) offer_code = create(:offer_code, products: [product], amount_cents: 0) visit "#{product.long_url}/#{offer_code.code}" expect(page).not_to have_selector("[role='status']") end it "removes existing discount codes that only apply to the same products as the new discount code" do seller = create(:user, display_offer_code_field: true) product1 = create(:product, user: seller) product2 = create(:product, user: seller) product3 = create(:product, user: seller) offer_code1 = create(:offer_code, code: "code1", products: [product1, product3]) offer_code2 = create(:offer_code, code: "code2", products: [product1, product2]) visit "#{product1.long_url}/#{offer_code1.code}" add_to_cart(product1, offer_code: offer_code1) visit product2.long_url add_to_cart(product2) fill_in "Discount code", with: offer_code2.code click_on "Apply" expect(page).to_not have_selector("[aria-label='Discount code']", text: offer_code1.code) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code2.code) visit product3.long_url add_to_cart(product3) fill_in "Discount code", with: offer_code1.code click_on "Apply" expect(page).to have_selector("[aria-label='Discount code']", text: offer_code1.code) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code2.code) end context "when the product has quantity enabled" do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller, price_cents: 1000, quantity_enabled: true) } let(:offer_code) { create(:offer_code, user: seller, products: [product]) } it "applies the offer code" do visit "#{product.long_url}/#{offer_code.code}?quantity=2" expect(page).to have_field("Quantity", with: "2") fill_in "Quantity", with: 3 expect(page).to have_field("Quantity", with: "3") add_to_cart(product, offer_code:, quantity: 3) check_out(product) purchase = Purchase.last expect(purchase.quantity).to eq(3) expect(purchase.price_cents).to eq(2700) end end context "when an offer code changes after it has been applied to the cart" do it "fails the purchase but updates the offer code" do product = create(:product, price_cents: 1000) offer_code = create(:offer_code, products: [product]) visit "#{product.long_url}/#{offer_code.code}" add_to_cart(product, offer_code:) offer_code.update!(amount_cents: 200) check_out(product, error: "The price just changed! Refresh the page for the updated price.") visit checkout_index_path check_out(product) end end context "when an offer code is removed after it has been applied to the cart" do it "fails the purchase but removes the offer code" do product = create(:product, price_cents: 1000) offer_code = create(:offer_code, products: [product]) visit "#{product.long_url}/#{offer_code.code}" add_to_cart(product, offer_code:) offer_code.mark_deleted! check_out(product, error: "Sorry, the discount code you wish to use is invalid.") visit checkout_index_path expect(page).to_not have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Total US$10", normalize_ws: true) check_out(product) expect(Purchase.last.price_cents).to eq(1000) end end context "when the product is PWYW" do before do @product = create(:product, price_cents: 2000, customizable_price: true) end context "absolute offer code" do before do @offer_code = create(:offer_code, products: [@product], amount_cents: 1000) end it "accepts the offer code and takes the PWYW price as the post-discount price" do visit "#{@product.long_url}/#{@offer_code.code}" add_to_cart(@product, pwyw_price: 10.44, offer_code: @offer_code) check_out(@product) end end context "percentage offer code" do before do @offer_code = create(:percentage_offer_code, products: [@product], amount_percentage: 20) end it "accepts the offer code and takes the PWYW price as the post-discount price" do visit "#{@product.long_url}/#{@offer_code.code}" add_to_cart(@product, pwyw_price: 16.44, offer_code: @offer_code) check_out(@product) end end end context "when purchasing a product with a quantity larger than 1" do it "displays the correct discount and the purchase succeeds" do product = create(:product, price_cents: 1000, quantity_enabled: true) offer_code = create(:offer_code, products: [product]) visit "#{product.long_url}/#{offer_code.code}" add_to_cart(product, offer_code:, quantity: 2) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Discounts #{offer_code.code} US$-2", normalize_ws: true) expect(page).to have_text("Total US$18", normalize_ws: true) check_out(product) expect(Purchase.last.price_cents).to eq(1800) end end describe "offer code validity" do let(:seller) { create(:named_seller, display_offer_code_field: true) } let(:product) { create(:product, user: seller) } context "when the offer code is not yet valid" do let!(:offer_code) { create(:offer_code, user: seller, products: [product], valid_at: 1.year.from_now) } it "displays error messages" do visit "#{product.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "Sorry, the discount code you wish to use is inactive.") add_to_cart(product) fill_in "Discount code", with: offer_code.code click_on "Apply" expect(page).to have_alert(text: "Sorry, the discount code you wish to use is inactive.") offer_code.update!(valid_at: nil) click_on "Apply" expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) offer_code.update!(valid_at: 1.year.from_now) fill_checkout_form(product, is_free: true) click_on "Get" expect(page).to have_alert(text: "Sorry, the discount code you wish to use is inactive.") end end context "when the offer code is expired" do let!(:offer_code) { create(:offer_code, user: seller, products: [product], valid_at: 2.years.ago, expires_at: 1.year.ago) } it "displays error messages" do visit "#{product.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "Sorry, the discount code you wish to use is inactive.") add_to_cart(product) fill_in "Discount code", with: offer_code.code click_on "Apply" expect(page).to have_alert(text: "Sorry, the discount code you wish to use is inactive.") offer_code.update!(expires_at: nil) click_on "Apply" expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) offer_code.update!(valid_at: 1.year.ago) fill_checkout_form(product, is_free: true) click_on "Get" expect(page).to have_alert(text: "Sorry, the discount code you wish to use is inactive.") end end context "when the offer code's minimum quantity is not met" do let!(:offer_code) { create(:offer_code, user: seller, products: [product], minimum_quantity: 2) } it "displays error messages" do visit "#{product.long_url}/#{offer_code.code}" add_to_cart(product) fill_in "Discount code", with: offer_code.code click_on "Apply" expect(page).to have_alert(text: "Sorry, the discount code you wish to use has an unmet minimum quantity.") offer_code.update!(minimum_quantity: nil) click_on "Apply" expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) offer_code.update!(minimum_quantity: 2) fill_checkout_form(product, is_free: true) click_on "Get" expect(page).to have_alert(text: "Sorry, the discount code you wish to use has an unmet minimum quantity.") end end end describe "offer code with duration" do context "when the product is a tiered membership" do let(:product) { create(:membership_product_with_preset_tiered_pricing) } let(:offer_code) { create(:offer_code, products: [product], duration_in_billing_cycles: 1) } it "displays the duration notice and the purchase succeeds" do visit "#{product.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", exact_text: "$1 off will be applied at checkout (Code SXSW) This discount will only apply to the first payment of your subscription.", normalize_ws: true) add_to_cart(product, option: "First Tier", offer_code:) check_out(product) purchase = Purchase.last expect(purchase.price_cents).to eq(200) expect(purchase.offer_code).to eq(offer_code) purchase_offer_code_discount = purchase.purchase_offer_code_discount expect(purchase_offer_code_discount.offer_code_amount).to eq(100) expect(purchase_offer_code_discount.duration_in_billing_cycles).to eq(1) expect(purchase_offer_code_discount.offer_code_is_percent).to eq(false) end end context "when the product is not a tiered membership" do let(:product) { create(:product, price_cents: 200) } let(:offer_code) { create(:offer_code, products: [product], duration_in_billing_cycles: 1) } it "doesn't display the duration notice and the purchase succeeds" do visit "#{product.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", exact_text: "$1 off will be applied at checkout (Code SXSW)", normalize_ws: true) add_to_cart(product, offer_code:) check_out(product) purchase = Purchase.last expect(purchase.offer_code).to eq(offer_code) expect(purchase.purchase_offer_code_discount.duration_in_billing_cycles).to eq(nil) end end end describe "offer code with minimum amount" do let(:seller) { create(:named_seller) } let(:product1) { create(:product, name: "Product 1", user: seller) } let(:product2) { create(:product, name: "Product 2", user: seller) } let(:product3) { create(:product, name: "Product 3", user: seller) } let(:offer_code) { create(:offer_code, user: seller, products: [product1, product3], minimum_amount_cents: 200) } context "when the cart has an insufficient amount" do it "doesn't apply the discount" do visit "#{product1.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "$1 off will be applied at checkout (Code SXSW) This discount will apply when you spend $2 or more in selected products.", normalize_ws: true) add_to_cart(product1, offer_code:) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Total US$1", normalize_ws: true) check_out(product1) purchase = Purchase.last expect(purchase.price_cents).to eq(100) expect(purchase.offer_code).to eq(nil) end end context "when the cart has a sufficient amount" do it "applies the discount" do visit "#{product1.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "$1 off will be applied at checkout (Code SXSW) This discount will apply when you spend $2 or more in selected products.", normalize_ws: true) add_to_cart(product1, offer_code:) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Total US$1", normalize_ws: true) visit product2.long_url add_to_cart(product2) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Total US$2", normalize_ws: true) visit "#{product3.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "$1 off will be applied at checkout (Code SXSW) This discount will apply when you spend $2 or more in selected products.", normalize_ws: true) add_to_cart(product3, offer_code:) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Total US$1", normalize_ws: true) check_out(product3) purchase1 = Purchase.last expect(purchase1.price_cents).to eq(0) expect(purchase1.offer_code).to eq(offer_code) purchase2 = Purchase.second_to_last expect(purchase2.price_cents).to eq(100) expect(purchase2.offer_code).to eq(nil) purchase3 = Purchase.third_to_last expect(purchase3.price_cents).to eq(0) expect(purchase3.offer_code).to eq(offer_code) end context "when a product in the cart has a quantity greater than 1" do before { product1.update!(quantity_enabled: true) } it "applies the discount" do visit "#{product1.long_url}/#{offer_code.code}" add_to_cart(product1, offer_code:) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Total US$1", normalize_ws: true) visit "#{product1.long_url}/#{offer_code.code}" add_to_cart(product1, offer_code:, quantity: 2) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Total US$0", normalize_ws: true) check_out(product1, is_free: true) purchase = Purchase.last expect(purchase.price_cents).to eq(0) expect(purchase.quantity).to eq(2) expect(purchase.offer_code).to eq(offer_code) end end end context "when the offer code is universal" do before do offer_code.update!(universal: true, products: []) end context "when the cart has an insufficient amount" do it "doesn't apply the discount" do visit "#{product1.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "$1 off will be applied at checkout (Code SXSW) This discount will apply when you spend $2 or more in Seller's products.", normalize_ws: true) add_to_cart(product1, offer_code:) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Total US$1", normalize_ws: true) check_out(product1) purchase = Purchase.last expect(purchase.price_cents).to eq(100) expect(purchase.offer_code).to eq(nil) end end context "when the cart has a sufficient amount" do it "applies the discount" do visit "#{product1.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "$1 off will be applied at checkout (Code SXSW) This discount will apply when you spend $2 or more in Seller's products.", normalize_ws: true) add_to_cart(product1, offer_code:) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Total US$1", normalize_ws: true) visit "#{product2.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "$1 off will be applied at checkout (Code SXSW) This discount will apply when you spend $2 or more in Seller's products.", normalize_ws: true) add_to_cart(product2, offer_code:) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Total US$0", normalize_ws: true) visit "#{product3.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "$1 off will be applied at checkout (Code SXSW) This discount will apply when you spend $2 or more in Seller's products.", normalize_ws: true) add_to_cart(product3, offer_code:) expect(page).to have_selector("[aria-label='Discount code']", text: offer_code.code) expect(page).to have_text("Total US$0", normalize_ws: true) check_out(product3, is_free: true) purchase1 = Purchase.last expect(purchase1.price_cents).to eq(0) expect(purchase1.offer_code).to eq(offer_code) purchase2 = Purchase.second_to_last expect(purchase2.price_cents).to eq(0) expect(purchase2.offer_code).to eq(offer_code) purchase3 = Purchase.third_to_last expect(purchase3.price_cents).to eq(0) expect(purchase3.offer_code).to eq(offer_code) end end end context "when the offer code only applies to one product" do before do offer_code.update!(products: [product1]) end it "displays the correct notice" do visit "#{product1.long_url}/#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "$1 off will be applied at checkout (Code SXSW) This discount will apply when you spend $2 or more.", normalize_ws: true) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/legacy_cards_spec.rb
spec/requests/purchases/product/legacy_cards_spec.rb
# frozen_string_literal: true require("spec_helper") require "timeout" # In March 2021 we migrated from Stripe's Charges API to Payment Intents API. # Many customers have stored their credit cards on file using the old Charges API (via a credit card token). # This spec ensures that those legacy credit cards keep working under the new Payment Intents API. describe("Purchase using a saved card created under the old Charges API", type: :system, js: true) do before do @creator = create(:named_user) # We create a card via a CC token which is how things were done under the legacy Charges API legacy_credit_card = create(:credit_card, chargeable: build(:cc_token_chargeable, card: CardParamsSpecHelper.success)) @user = create(:user, credit_card: legacy_credit_card) login_as @user end it "allows to purchase a classic product" do classic_product = create(:product, user: @creator) visit "#{classic_product.user.subdomain_with_protocol}/l/#{classic_product.unique_permalink}" add_to_cart(classic_product) check_out(classic_product, logged_in_user: @user) end it "allows to purchase a subscription product" do membership_product = create(:membership_product) visit "#{membership_product.user.subdomain_with_protocol}/l/#{membership_product.unique_permalink}" add_to_cart(membership_product, option: "Untitled") check_out(membership_product, logged_in_user: @user) travel_to 1.month.from_now expect do membership_product.subscriptions.last.charge! end.to change { membership_product.sales.successful.count }.by(1) end it "allows to pre-order a product" do product = create(:product_with_files, 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_product = create(:preorder_link, link: product, release_at: 25.hours.from_now) visit "#{product.user.subdomain_with_protocol}/l/#{product.unique_permalink}" add_to_cart(product) check_out(product, logged_in_user: @user) travel_to 25.hours.from_now index_model_records(Purchase) expect do Sidekiq::Testing.inline! do preorder_product.release! end end.to change { product.sales.successful.count }.by(1) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/call_spec.rb
spec/requests/purchases/product/call_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Call", type: :system, js: true do let!(:seller) { create(:named_seller, :eligible_for_service_products) } let!(:call) do create( :call_product, :available_for_a_year, name: "Call me!", description: "Call me for business advices.", user: seller, price_cents: 10_00, durations: [] ) end let!(:call_limitation_info) { create(:call_limitation_info, call:, minimum_notice_in_minutes: 0, maximum_calls_per_day: 10) } let!(:long_availability) { create(:call_availability, call:, start_time: Time.current, end_time: 2.months.from_now) } let!(:variant_category) { call.variant_categories.first } let(:client_time_zone) { ActiveSupport::TimeZone.new("UTC") } let(:first_day_of_next_month) { client_time_zone.now.next_month.beginning_of_month } around do |example| travel_to Time.zone.local(2024, 9, 15) do example.run end end context "one duration" do let!(:duration_30) { create(:variant, name: "30 minutes", variant_category:, price_difference_cents: 0, duration_in_minutes: 30) } it "allows selecting from the available dates and times" do visit call.long_url expect(page).to have_radio_button("$10", checked: true) wait_for_ajax within_section "Select a date" do expect(page).to have_text("September 2024") click_on "Next Month" expect(page).to have_text("October 2024") click_on "1", match: :first end within_section "Select a time" do choose "01:00 PM" end expect(page).to have_text("You selected Tuesday, October 1 at 01:00 PM") scroll_to first("footer") click_on "I want this!" expect(page).to have_current_path("/checkout") within_cart_item "Call me!" do expect(page).to have_text("Duration: 30 minutes") expect(page).to have_text("Tuesday, October 1 at 01:00 PM UTC") end fill_checkout_form(call) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = Purchase.last expect(purchase).to be_successful expect(purchase.price_cents).to eq(10_00) expect(purchase.link).to eq(call) expect(purchase.variant_attributes).to eq([duration_30]) start_time = Time.zone.local(2024, 10, 1, 13, 0) expect(purchase.call.start_time).to eq(start_time) expect(purchase.call.end_time).to eq(start_time + 30.minutes) end end context "multiple durations" do let!(:duration_30) { create(:variant, name: "30 minutes", variant_category:, price_difference_cents: 0, duration_in_minutes: 30) } let!(:duration_60) { create(:variant, name: "60 minutes", variant_category:, price_difference_cents: 10_00, duration_in_minutes: 60) } it "allows selecting a duration and changing it during checkout" do visit call.long_url expect(page).to have_radio_button("$10", checked: true) expect(page).to have_radio_button("$20", checked: false) wait_for_ajax choose "$10" scroll_to first("footer") click_on "I want this!" expect(page).to have_current_path("/checkout") within_cart_item "Call me!" do expect(page).to have_text("Duration: 30 minutes") select_disclosure "Edit" do choose "$20" click_on "Next Month" click_on "1", match: :first choose "01:00 PM" expect(page).to have_text("You selected Tuesday, October 1 at 01:00 PM") click_on "Save changes" end end within_cart_item "Call me!" do expect(page).to have_text("Duration: 60 minutes") end fill_checkout_form(call) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") purchase = Purchase.last expect(purchase).to be_successful expect(purchase.price_cents).to eq(20_00) expect(purchase.link).to eq(call) expect(purchase.variant_attributes).to eq([duration_60]) expect(purchase.call).to be_present start_time = Time.zone.local(2024, 10, 1, 13, 0) expect(purchase.call.start_time).to eq(start_time) expect(purchase.call.end_time).to eq(start_time + 60.minutes) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false