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/requests/purchases/product/invalid_offer_codes_spec.rb
spec/requests/purchases/product/invalid_offer_codes_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Invalid offer-code usage from product page", type: :system, js: true) do describe "manually entered" do it "shows an error message when entering an invalid offer code and prevents purchase" do product = create(:product, price_cents: 300, user: create(:user, display_offer_code_field: true)) create(:offer_code, products: [product], amount_cents: 300) visit "/l/#{product.unique_permalink}" add_to_cart(product) fill_in "Discount code", with: "invalid offer code" click_on "Apply" expect(page).to have_alert(text: "Sorry, the discount code you wish to use is invalid.") end it "shows an error message when entering a deleted offer code and prevents purchase" do product = create(:product, price_cents: 300, user: create(:user, display_offer_code_field: true)) create(:offer_code, products: [product], amount_cents: 20, code: "unused_offer") offer_code = create(:offer_code, products: [product], amount_cents: 10) offer_code.mark_deleted! visit "/l/#{product.unique_permalink}" 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 invalid.") end it "shows an error message when entering a sold out code and prevents 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: 10, max_purchase_count: 0) visit "/l/#{product.unique_permalink}" 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 expired.") end end describe "set via URL" do it "ignores a deleted offer code and allows purchase" do product = create(:product, price_cents: 300) offer_code = create(:offer_code, products: [product], amount_cents: 100) offer_code.mark_deleted! visit "/l/#{product.unique_permalink}/#{offer_code.code}" add_to_cart(product) wait_for_ajax expect(page).to(have_selector("[role='listitem'] [aria-label='Price']", text: "$3")) check_out(product) expect(Purchase.last.price_cents).to eq 300 end it "ignores a sold out offer code and allows purchase" do product = create(:product, price_cents: 300) offer_code = create(:offer_code, products: [product], amount_cents: 10, max_purchase_count: 0) visit "/l/#{product.unique_permalink}/#{offer_code.code}" expect(page).to have_selector("[role='status']", text: "Sorry, the discount code you wish to use has expired.") add_to_cart(product) check_out(product) expect(Purchase.last.price_cents).to eq 300 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/stripejs_purchase_spec.rb
spec/requests/purchases/product/stripejs_purchase_spec.rb
# frozen_string_literal: true require("spec_helper") require "timeout" describe("PurchaseScenario using StripeJs", type: :system, js: true) do it "uses a users saved cc if they have one" do previous_successful_sales_count = Purchase.successful.count link = create(:product, price_cents: 200) user = create(:user) credit_card = create(:credit_card) credit_card.users << user login_as user visit "#{link.user.subdomain_with_protocol}/l/#{link.unique_permalink}" add_to_cart(link) check_out(link, logged_in_user: user) expect(Purchase.successful.count).to eq previous_successful_sales_count + 1 end it("allows the buyer to pay with a new credit card") do link = create(:product_with_pdf_file, user: create(:user)) visit("/l/#{link.unique_permalink}") expect(Stripe::PaymentMethod).to receive(:retrieve).and_call_original expect(Stripe::PaymentIntent).to receive(:create).and_call_original add_to_cart(link) check_out(link) new_purchase = Purchase.last expect(new_purchase.stripe_transaction_id).to match(/\Ach_/) expect(new_purchase.stripe_fingerprint).to_not be(nil) expect(new_purchase.card_type).to eq "visa" expect(new_purchase.card_country).to eq "US" expect(new_purchase.card_country_source).to eq Purchase::CardCountrySource::STRIPE expect(new_purchase.card_visual).to eq "**** **** **** 4242" expect(new_purchase.card_expiry_month).to eq StripePaymentMethodHelper::EXPIRY_MM.to_i expect(new_purchase.card_expiry_year).to eq StripePaymentMethodHelper::EXPIRY_YYYY.to_i expect(new_purchase.successful?).to be(true) end describe "save credit card payment" do before :each do @buyer = create(:user) login_as(@buyer) @product = create(:product) end it "saves when opted" do visit "#{@product.user.subdomain_with_protocol}/l/#{@product.unique_permalink}" add_to_cart(@product) expect(page).to have_checked_field("Save card") check_out(@product, logged_in_user: @buyer) purchase = Purchase.last expect(purchase.purchase_state).to eq("successful") expect(purchase.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id) expect(purchase.card_type).to eq "visa" expect(purchase.card_country).to eq "US" expect(purchase.card_country_source).to eq Purchase::CardCountrySource::STRIPE expect(purchase.card_visual).to eq "**** **** **** 4242" credit_card = @buyer.reload.credit_card expect(CreditCard.last).to eq(credit_card) expect(credit_card.card_type).to eq(CardType::VISA) expect(credit_card.visual).to eq("**** **** **** 4242") end it "does not save the card when opted out" do visit "#{@product.user.subdomain_with_protocol}/l/#{@product.unique_permalink}" add_to_cart(@product) expect(page).to have_checked_field("Save card") uncheck "Save card" check_out(@product, logged_in_user: @buyer) purchase = Purchase.last expect(purchase.card_type).to eq "visa" expect(purchase.card_country).to eq "US" expect(purchase.card_country_source).to eq Purchase::CardCountrySource::STRIPE expect(purchase.card_visual).to eq "**** **** **** 4242" expect(@buyer.reload.credit_card).to be(nil) end end describe "pay what you want" do before do @pwyw_product = create(:product) end describe "paid, untaxed purchase without shipping" do before do @pwyw_product.price_range = "30+" @pwyw_product.customizable_price = true @pwyw_product.save! end it "shows the payment blurb" do visit "/l/#{@pwyw_product.unique_permalink}" add_to_cart(@pwyw_product, pwyw_price: 35) expect(page).to have_text("Total US$35", normalize_ws: true) end end describe "multiple variants: 0+ and non-0+" do before do @pwyw_product.price_range = "0+" @pwyw_product.customizable_price = true @pwyw_product.save! @variant_category = create(:variant_category, link: @pwyw_product, title: "type") @var_zero_plus = create(:variant, variant_category: @variant_category, name: "Zero-plus", price_difference_cents: 0) @var_paid = create(:variant, variant_category: @variant_category, name: "Paid", price_difference_cents: 500) end it "lets to purchase the zero-plus variant for free" do visit "/l/#{@pwyw_product.unique_permalink}" add_to_cart(@pwyw_product, pwyw_price: 0, option: "Zero-plus") check_out(@pwyw_product, is_free: true) end it "does not let to purchase the paid variant for free, shows PWYW error instead of going to CC form" do visit "/l/#{@pwyw_product.unique_permalink}" choose "Paid" fill_in "Name a fair price", with: 0 click_on "I want this!" expect(find_field("Name a fair price")["aria-invalid"]).to eq("true") expect(page).not_to have_button("Pay") fill_in "Name a fair price", with: 4 click_on "I want this!" expect(find_field("Name a fair price")["aria-invalid"]).to eq("true") expect(page).not_to have_button("Pay") add_to_cart(@pwyw_product, pwyw_price: 6, option: "Paid") expect(page).to have_button("Pay") expect(page).to have_text("Total US$6", normalize_ws: true) check_out(@pwyw_product) purchase = Purchase.last expect(purchase.card_type).to eq "visa" expect(purchase.card_country).to eq "US" expect(purchase.card_country_source).to eq Purchase::CardCountrySource::STRIPE expect(purchase.card_visual).to eq "**** **** **** 4242" expect(purchase.price_cents).to eq(6_00) end end describe "free purchase" do before do @pwyw_product.price_range = "0+" @pwyw_product.customizable_price = true @pwyw_product.save! end it "does not show the payment blurb nor 'charged your card' message" do visit "/l/#{@pwyw_product.unique_permalink}" add_to_cart(@pwyw_product, pwyw_price: 0) check_out(@pwyw_product, is_free: true) end describe "processes an EU style formatted PWYW input" do it "parses and charges the right amount" do visit "/l/#{@pwyw_product.unique_permalink}" add_to_cart(@pwyw_product, pwyw_price: 1000.50) expect(page).to have_text("Total US$1,000.50", normalize_ws: true) check_out(@pwyw_product, is_free: false) purchase = Purchase.last expect(purchase.card_type).to eq "visa" expect(purchase.card_country).to eq "US" expect(purchase.card_country_source).to eq Purchase::CardCountrySource::STRIPE expect(purchase.card_visual).to eq "**** **** **** 4242" expect(purchase.price_cents).to eq(100050) 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/purchases/product/payment_blurb_spec.rb
spec/requests/purchases/product/payment_blurb_spec.rb
# frozen_string_literal: true require("spec_helper") require "timeout" describe("Payment Blurb for Purchases from the product page", type: :system, js: true) do before do @user = create(:user) $currency_namespace = Redis::Namespace.new(:currencies, redis: $redis) $currency_namespace.set("GBP", 0.2) end after do $currency_namespace.set("GBP", nil) if $currency_namespace end it "converts the currency based on the exchange rate" do link = create(:product, user: @user, price_cents: 1_00, price_currency_type: "gbp") visit "/l/#{link.unique_permalink}" click_on("I want this!") expect(page).to have_text("Total US$5", normalize_ws: true) end end describe "payment blurb with merchant account hides merchant account currency with merchant migration disabled", type: :system, js: true do before do @user = create(:user) @merchant_account = create(:merchant_account, user: @user) Feature.deactivate_user(:merchant_migration, @user) end after do @merchant_account.country = "US" @merchant_account.currency = "usd" @merchant_account.save! end it "does not convert to GBP" do @merchant_account.country = "UK" @merchant_account.currency = "gbp" @merchant_account.save! link = create(:product, user: @user, price_cents: 1_00, price_currency_type: "usd") visit "/l/#{link.unique_permalink}" click_on("I want this!") expect(page).to have_text("Total US$1", normalize_ws: true) end it "does not convert to SGP" do @merchant_account.country = "Singapore" @merchant_account.currency = "sgd" @merchant_account.save! link = create(:product, user: @user, price_cents: 1_00, price_currency_type: "usd") visit "/l/#{link.unique_permalink}" click_on("I want this!") expect(page).to have_text("Total US$1", 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/purchases/product/quantities_spec.rb
spec/requests/purchases/product/quantities_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Multiple quantity purchases from product page", type: :system, js: true) do describe "multiple quantities" do before do @product = create(:physical_product, price_cents: 200) end it "charges the correct amount for PWYW products" do @product.price_range = "3+" @product.customizable_price = true @product.save visit "/l/#{@product.unique_permalink}" add_to_cart(@product, quantity: 2, pwyw_price: 10) check_out(@product) expect(Purchase.last.price_cents).to eq 2000 expect(Purchase.last.fee_cents).to eq 338 expect(Purchase.last.quantity).to eq 2 end it "does not complete the purchase if amount is less than minimum for PWYW product" do @product.price_range = "3+" @product.customizable_price = true @product.save visit "/l/#{@product.unique_permalink}" fill_in "Name a fair price:", with: "1" click_on("I want this!") expect(find_field("Name a fair price")["aria-invalid"]).to eq("true") end it "works with multiple quantities" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product, quantity: 2) check_out(@product) expect(Purchase.last.price_cents).to eq 400 expect(Purchase.last.fee_cents).to eq 132 expect(Purchase.last.quantity).to eq 2 end it "does not process payment if not enough variants available" do variant_category = create(:variant_category, link: @product, title: "type") variants = [["type 1", 150], ["type 2", 200], ["type 3", 300]] variants.each do |name, price_difference_cents| create(:variant, variant_category:, name:, price_difference_cents:, max_purchase_count: 2) end Product::SkusUpdaterService.new(product: @product).perform visit "/l/#{@product.unique_permalink}" add_to_cart(@product, quantity: 2, option: "type 1") Sku.not_is_default_sku.first.update_attribute(:max_purchase_count, 1) check_out(@product, error: "You have chosen a quantity that exceeds what is available") end it "displays and successfully charges the correct amount after offer code, mimicking backend's quantity x offer code application" do @offer_code = create(:percentage_offer_code, products: [@product], amount_percentage: 15) @product.update!(price_cents: 29_95) @product.user.update!(display_offer_code_field: true) visit "/l/#{@product.unique_permalink}" add_to_cart(@product, quantity: 7) fill_in "Discount code", with: @offer_code.code click_on "Apply" wait_for_ajax expect(page).to have_text("Total US$178.22", normalize_ws: true) check_out(@product) end it "does not process the payment if not enough offer codes available" do offer_code = create(:percentage_offer_code, products: [@product], amount_percentage: 50, max_purchase_count: 3) @product.save @product.user.update!(display_offer_code_field: true) visit "/l/#{@product.unique_permalink}" add_to_cart(@product, quantity: 2) offer_code.update_attribute(:max_purchase_count, 1) fill_in "Discount code", with: offer_code.code click_on "Apply" expect(page).to have_alert("Sorry, the discount code you are using is invalid for the quantity you have selected.") end it "does not process payment if not enough products available" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product, quantity: 2) @product.update_attribute(:max_purchase_count, 1) check_out(@product, error: "You have chosen a quantity that exceeds what is available.") 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/payment_errors_spec.rb
spec/requests/purchases/product/payment_errors_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Purchase from a product page", type: :system, js: true) do before do @creator = create(:named_user) @product = create(:product, user: @creator) end it "displays card expired error if input card is expired as per stripe" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, credit_card: { number: "4000000000000069" }, error: "Your card has expired.") expect(Purchase.last.stripe_error_code).to eq("expired_card") end it "displays insufficient funds error if input card does not have sufficient funds as per stripe" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, credit_card: { number: "4000000000009995" }, error: "Your card has insufficient funds.") expect(Purchase.last.stripe_error_code).to eq("card_declined_insufficient_funds") end it "displays incorrect cvc error if input cvc is incorrect as per stripe" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, credit_card: { number: "4000000000000127" }, error: "Your card's security code is incorrect.") expect(Purchase.last.stripe_error_code).to eq("incorrect_cvc") end it "displays card processing error if stripe reports a processing error" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, credit_card: { number: "4000000000000119" }, error: "An error occurred while processing your card. Try again in a little bit.") expect(Purchase.last.stripe_error_code).to eq("processing_error") end it "lets use a different card after first having used an invalid card" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, credit_card: { number: "4000000000009995" }, error: "Your card has insufficient funds.") expect(Purchase.last.stripe_error_code).to eq("card_declined_insufficient_funds") visit current_path check_out(@product) expect(page).not_to have_alert end it "doesn't allow purchase when the card information is incomplete" do visit @product.long_url add_to_cart(@product) fill_in "ZIP code", with: "94107" fill_in_credit_card(number: "", expiry: "", cvc: "") click_on "Pay" expect(page).to have_selector("[aria-label='Card information'][aria-invalid='true']") fill_in_credit_card(expiry: "", cvc: "") click_on "Pay" expect(page).to have_selector("[aria-label='Card information'][aria-invalid='true']") fill_in_credit_card(cvc: "") click_on "Pay" expect(page).to have_selector("[aria-label='Card information'][aria-invalid='true']") check_out(@product) end context "when the price changes while the product is in the cart" do it "fails the purchase but updates the product data" do visit @product.long_url add_to_cart(@product) @product.price_cents += 100 check_out(@product, error: "The price just changed! Refresh the page for the updated price.") visit checkout_index_path check_out(@product) expect(Purchase.last.price_cents).to eq(200) expect(Purchase.last.was_product_recommended).to eq(false) end end it "focuses the correct fields with errors" do product = create(:physical_product, user: @creator) # Pass-through the params to bypass address verification allow_any_instance_of(ShipmentsController).to receive(:verify_shipping_address) do |controller| controller.render json: { success: true, **controller.params.permit! } end visit product.long_url add_to_cart(product) click_on "Pay" within_fieldset "Card information" do within_frame { expect_focused find_field("Card number") } end fill_in_credit_card(expiry: nil, cvc: nil) click_on "Pay" within_fieldset "Card information" do within_frame { expect_focused find_field("MM / YY") } end fill_in_credit_card(cvc: nil) click_on "Pay" within_fieldset "Card information" do within_frame { expect_focused find_field("CVC") } end fill_in_credit_card click_on "Pay" expect_focused find_field("Your email address") fill_in "Your email address", with: "gumroad@example.com" click_on "Pay" expect_focused find_field("Full name") fill_in "Full name", with: "G McGumroadson" click_on "Pay" expect_focused find_field("Street address") fill_in "Street address", with: "123 Main St" click_on "Pay" expect_focused find_field("City") fill_in "City", with: "San Francisco" click_on "Pay" expect_focused find_field("ZIP code") 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_tiered_membership_spec.rb
spec/requests/purchases/product/offer_codes_tiered_membership_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Offer-code usage from product page for tiered membership", type: :system, js: true) do let(:product) { create(:membership_product_with_preset_tiered_pricing, user: create(:user, display_offer_code_field: true)) } let!(:offer_code) { create(:offer_code, products: [product], amount_cents: 4_00) } it "allows the user to redeem an offer code" do visit "/l/#{product.unique_permalink}" add_to_cart(product, option: "Second Tier") fill_in "Discount code", with: offer_code.code click_on "Apply" wait_for_ajax expect(page).to have_text("Total US$1", normalize_ws: true) check_out(product) end context "with one tier" do before do tier_category = product.tier_category @first_tier = tier_category.variants.first @first_tier.save_recurring_prices!("monthly" => { enabled: true, price: 2 }, "yearly" => { enabled: true, price: 10 }) @second_tier = tier_category.variants.last @second_tier.mark_deleted end it "displays recurrences as options, shows original and discounted price for each" do visit URI::DEFAULT_PARSER.escape("/l/#{product.unique_permalink}/#{offer_code.code}") expect(page).to have_selector("[itemprop='price']", text: "$2 $0 a month", visible: false) add_to_cart(product, recurrence: "Yearly", offer_code:, option: @first_tier.name) check_out(product) Timeout.timeout(Capybara.default_max_wait_time) do loop until Purchase.successful.count == 1 end purchase = Purchase.successful.last expect(purchase.subscription.price).to eq product.prices.find_by!(recurrence: BasePrice::Recurrence::YEARLY) expect(purchase.variant_attributes.map(&:id)).to eq [@first_tier.id] end end context "with a free trial" do it "doesn't require payment info for products that are discounted to free" do product.update!(free_trial_enabled: true, free_trial_duration_amount: 1, free_trial_duration_unit: "month") visit "#{product.long_url}/#{offer_code.code}" add_to_cart(product, option: "First Tier", offer_code:) expect(page).to have_text("Subtotal US$0", normalize_ws: true) expect(page).to have_text("Total US$0", normalize_ws: true) expect(page).to_not have_selector(:fieldset, "Card information") check_out(product, is_free: 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/coffee_spec.rb
spec/requests/purchases/product/coffee_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Coffee", type: :system, js: true do let(:seller) { create(:named_seller, :eligible_for_service_products) } let(:coffee) do create( :product, name: "Buy me a coffee!", description: "Please give me money. Pretty please! I really need it.", user: seller, native_type: Link::NATIVE_TYPE_COFFEE, ) end context "one suggested amount" do it "shows the custom price input filled with that amount and allows purchase" do visit coffee.long_url expect(page).to have_selector("h1", text: "Buy me a coffee!") expect(page).to have_selector("h3", text: "Please give me money. Pretty please! I really need it.") expect(page).to_not have_radio_button expect(page).to have_field("Price", with: "1") click_on "Donate" expect(page).to have_current_path("/checkout") within_cart_item "Buy me a coffee!" do expect(page).to have_text("US$1") select_disclosure "Edit" do fill_in "Price", with: "" click_on "Save changes" expect(find_field("Price")["aria-invalid"]).to eq("true") fill_in "Price", with: "2" click_on "Save changes" end expect(page).to have_text("US$2") end fill_checkout_form(coffee) click_on "Pay" wait_for_ajax expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(current_url).to eq(custom_domain_coffee_url(host: coffee.user.subdomain_with_protocol)) purchase = Purchase.last expect(purchase).to be_successful expect(purchase.price_cents).to eq(200) expect(purchase.link).to eq(coffee) expect(purchase.variant_attributes).to eq([]) end it "rejects zero price" do visit coffee.long_url fill_in "Price", with: "0" click_on "Donate" expect(find_field("Price")["aria-invalid"]).to eq("true") end end context "multiple suggested amounts" do before do create(:variant, name: "", variant_category: coffee.variant_categories_alive.first, price_difference_cents: 200) create(:variant, name: "", variant_category: coffee.variant_categories_alive.first, price_difference_cents: 300) coffee.save_custom_button_text_option("tip_prompt") end it "shows radio buttons and allows purchase" do visit coffee.long_url expect(page).to have_radio_button("$1", checked: true) expect(page).to have_radio_button("$2", checked: false) expect(page).to have_radio_button("$3", checked: false) expect(page).to have_radio_button("Other", checked: false) expect(page).to_not have_field("Price") choose "$2" click_on "Tip" within_cart_item "Buy me a coffee!" do select_disclosure "Edit" do choose "$3" click_on "Save changes" end end fill_checkout_form(coffee) 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(300) expect(purchase.link).to eq(coffee) expect(purchase.variant_attributes).to eq([coffee.alive_variants.third]) end it "allows custom amount purchases" do visit coffee.long_url choose "Other" fill_in "Price", with: "100" click_on "Tip" fill_checkout_form(coffee) 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(10000) expect(purchase.link).to eq(coffee) expect(purchase.variant_attributes).to eq([]) end end context "email formatting in body text" do let(:coffee_with_email) do create( :product, name: "Buy me a coffee!", description: "Contact me at test@example.com for questions.", user: seller, native_type: Link::NATIVE_TYPE_COFFEE, ) end it "displays email addresses as clickable links" do visit coffee_with_email.long_url expect(page).to have_selector("h1", text: "Buy me a coffee!") expect(page).to have_link("test@example.com", href: "mailto:test@example.com") expect(page).not_to have_text('<a href="mailto:test@example.com"') 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_price_protection_spec.rb
spec/requests/purchases/product/installment_plan_price_protection_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Installment plan price protection" do let(:seller) { create(:user) } let(:product) { create(:product, user: seller, price_cents: 14700) } let(:installment_plan) { create(:product_installment_plan, link: product, number_of_installments: 3, recurrence: "monthly") } let(:subscription) { create(:subscription, link: product, user: seller) } let(:payment_option) { create(:payment_option, subscription: subscription, installment_plan: installment_plan) } describe "price change protection" do let!(:snapshot) do create(:installment_plan_snapshot, payment_option: payment_option, number_of_installments: 3, recurrence: "monthly", total_price_cents: 14700) end context "when product price increases" do it "protects existing customers from price increases" do expect(snapshot.total_price_cents).to eq(14700) expect(snapshot.number_of_installments).to eq(3) product.update!(price_cents: 19700) installment_plan.reload snapshot.reload expect(snapshot.total_price_cents).to eq(14700) expect(snapshot.number_of_installments).to eq(3) payments = snapshot.calculate_installment_payment_price_cents expect(payments).to eq([4900, 4900, 4900]) expect(payments.sum).to eq(14700) end end context "when product price decreases" do it "maintains original pricing for existing customers" do product.update!(price_cents: 10000) installment_plan.reload snapshot.reload expect(snapshot.total_price_cents).to eq(14700) payments = snapshot.calculate_installment_payment_price_cents expect(payments).to eq([4900, 4900, 4900]) expect(payments.sum).to eq(14700) end end end describe "installment configuration protection" do let!(:snapshot) do create(:installment_plan_snapshot, payment_option: payment_option, number_of_installments: 3, recurrence: "monthly", total_price_cents: 14700) end context "when installment count changes" do it "protects existing customers when count decreases from 3 to 2" do installment_plan.update!(number_of_installments: 2) snapshot.reload expect(snapshot.number_of_installments).to eq(3) expect(installment_plan.reload.number_of_installments).to eq(2) payments = snapshot.calculate_installment_payment_price_cents expect(payments.length).to eq(3) expect(payments).to eq([4900, 4900, 4900]) end it "protects existing customers when count increases from 3 to 5" do installment_plan.update!(number_of_installments: 5) snapshot.reload expect(snapshot.number_of_installments).to eq(3) expect(installment_plan.reload.number_of_installments).to eq(5) payments = snapshot.calculate_installment_payment_price_cents expect(payments.length).to eq(3) expect(payments).to eq([4900, 4900, 4900]) 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/rentals_spec.rb
spec/requests/purchases/product/rentals_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Rentals from product page", type: :system, js: true) do describe "rentals" do before do @product = create(:product_with_video_file, purchase_type: :buy_and_rent, price_cents: 500, rental_price_cents: 200, name: "rental test") end it "allows the product to be bought" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product) expect(Purchase.last.price_cents).to eq 500 end it "allows the product to be rented" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product, rent: true) check_out(@product) expect(Purchase.last.price_cents).to eq 200 expect(Purchase.last.is_rental).to be(true) expect(UrlRedirect.last.is_rental).to be(true) end it "allows the product to be rented for free if the rental price is 0" do @product.update!(rental_price_cents: 0) visit "/l/#{@product.unique_permalink}" add_to_cart(@product, rent: true) check_out(@product, is_free: true) expect(Purchase.last.price_cents).to eq 0 expect(Purchase.last.is_rental).to be(true) expect(UrlRedirect.last.is_rental).to be(true) end it "allows the product to be rented for free with an offer code" do offer_code = create(:offer_code, products: [@product], amount_cents: 500) visit URI::DEFAULT_PARSER.escape("/l/#{@product.unique_permalink}/#{offer_code.code}") choose "Rent" expect(page).to have_selector("[role='status']", text: "$5 off will be applied at checkout (Code #{offer_code.code.upcase})") expect(page).to have_radio_button("Rent", text: /\$2\s+\$0/) expect(page).to have_radio_button("Buy", text: /\$5\s+\$0/) add_to_cart(@product, rent: true, offer_code:) check_out(@product, is_free: true) expect(Purchase.last.price_cents).to eq 0 expect(Purchase.last.is_rental).to be(true) expect(UrlRedirect.last.is_rental).to be(true) end it "allows the product to be bought for free with an offer code" do 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) expect(Purchase.last.price_cents).to eq 0 expect(Purchase.last.is_rental).to be(false) expect(UrlRedirect.last.is_rental).to be(false) end it "allows the product to be rented for free with an offer code that would only make rental free" do offer_code = create(:offer_code, products: [@product], amount_cents: 200) visit URI::DEFAULT_PARSER.escape("/l/#{@product.unique_permalink}/#{offer_code.code}") wait_for_ajax add_to_cart(@product, rent: true, offer_code:) check_out(@product, is_free: true) expect(Purchase.last.price_cents).to eq 0 expect(Purchase.last.is_rental).to be(true) expect(UrlRedirect.last.is_rental).to be(true) end it "allows the PWYW product to be rented for free with an offer code that would only make rental free" do @product.customizable_price = true @product.save! offer_code = create(:offer_code, products: [@product], amount_cents: 200) visit URI::DEFAULT_PARSER.escape("/l/#{@product.unique_permalink}/#{offer_code.code}") wait_for_ajax add_to_cart(@product, rent: true, pwyw_price: 0, offer_code:) check_out(@product, is_free: true) expect(Purchase.last.price_cents).to eq 0 expect(Purchase.last.is_rental).to be(true) expect(UrlRedirect.last.is_rental).to be(true) end it "allows the product to be rented if it's rent-only" do @product.update!(purchase_type: :rent_only) visit "/l/#{@product.unique_permalink}" add_to_cart(@product, rent: true) check_out(@product) expect(Purchase.last.price_cents).to eq 200 expect(Purchase.last.is_rental).to be(true) expect(UrlRedirect.last.is_rental).to be(true) end describe "rentals and vat" do before do allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("2.47.255.255") # Italy allow_any_instance_of(Chargeable).to receive(:country) { "IT" } create(:zip_tax_rate, country: "IT", zip_code: nil, state: nil, combined_rate: 0.22, is_seller_responsible: false) end it "shows the price without the decimal part if the price is a whole number" do ZipTaxRate.destroy_all create(:zip_tax_rate, country: "IT", zip_code: nil, state: nil, combined_rate: 1, is_seller_responsible: false) visit "/l/#{@product.unique_permalink}" wait_for_ajax add_to_cart(@product) wait_for_ajax expect(page).to have_text("VAT US$5", normalize_ws: true) expect(page).to have_text("Total US$10", normalize_ws: true) click_on "Remove" visit("/l/#{@product.unique_permalink}") wait_for_ajax add_to_cart(@product, rent: true) expect(page).to have_text("VAT US$2", normalize_ws: true) expect(page).to have_text("Total US$4", normalize_ws: true) end it "charges the right VAT amount on rental purchase" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product, rent: true) expect(page).to have_text("VAT US$0.44", normalize_ws: true) expect(page).to have_text("Total US$2.44", normalize_ws: true) check_out(@product, zip_code: nil) expect(Purchase.last.price_cents).to eq 200 expect(Purchase.last.total_transaction_cents).to be(244) expect(Purchase.last.gumroad_tax_cents).to be(44) expect(Purchase.last.was_purchase_taxable).to be(true) expect(UrlRedirect.last.is_rental).to be(true) end end describe "with options" do before do variant_category = create(:variant_category, link: @product, title: "type") create(:variant, variant_category:, name: "Option A", price_difference_cents: 1_00) create(:variant, variant_category:, name: "Option B", price_difference_cents: 5_00) end it "shows appropriate price tags in options, that take rent/buy selection into account" do visit "/l/#{@product.unique_permalink}" choose "Buy" expect(page).to have_radio_button(text: "$6\nOption A") expect(page).to have_radio_button(text: "$10\nOption B") choose "Rent" expect(page).to have_radio_button(text: "$3\nOption A") expect(page).to have_radio_button(text: "$7\nOption B") end it "checks out buy + option successfully" do visit "/l/#{@product.unique_permalink}" choose "Buy" choose "Option B" expect(page).to have_radio_button(text: "$10\nOption B") add_to_cart(@product, option: "Option B") check_out(@product) expect(Purchase.last.price_cents).to eq 10_00 end it "checks out rent + option successfully" do visit "/l/#{@product.unique_permalink}" choose "Rent" choose "Option A" expect(page).to have_radio_button(text: "$3\nOption A") add_to_cart(@product, rent: true, option: "Option A") check_out(@product) expect(Purchase.last.price_cents).to eq 3_00 expect(Purchase.last.is_rental).to be(true) expect(UrlRedirect.last.is_rental).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/requests/purchases/product/gift_purchases_spec.rb
spec/requests/purchases/product/gift_purchases_spec.rb
# frozen_string_literal: true require("spec_helper") require "timeout" describe("Gift purchases from the product page", type: :system, js: true) do before do @user = create(:named_user) @product = create(:product, user: @user, custom_receipt: "<h1>Hello</h1>") end describe "gift purchases" do let(:giftee_email) { "giftee@gumroad.com" } it "allows gift purchase if product can be gifted" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, gift: { email: giftee_email, note: "Gifting from product page!" }) expect(Purchase.all_success_states.count).to eq 2 expect(Gift.successful.where(link_id: @product.id, gifter_email: "test@gumroad.com", giftee_email:).count).to eq 1 end it "prevents the user from gifting to an invalid giftee address" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, gift: { email: "bad", note: "" }, error: true) expect(find_field("Recipient email")["aria-invalid"]).to eq("true") expect(Purchase.all_success_states.count).to eq 0 expect(Gift.count).to eq 0 check_out(@product, gift: { email: giftee_email, note: "" }) expect(Purchase.all_success_states.count).to eq 2 expect(Gift.successful.where(link_id: @product.id, gifter_email: "test@gumroad.com", giftee_email:).count).to eq 1 end it "only generates license key for giftee when purchasing licensed product as gift" do licensed_product = create(:product, user: @user, is_licensed: true) visit "/l/#{licensed_product.unique_permalink}" add_to_cart(licensed_product) check_out(licensed_product, gift: { email: giftee_email, note: "Gifting licensed product!" }) expect(Purchase.all_success_states.count).to eq 2 expect(Gift.successful.where(link_id: licensed_product.id, gifter_email: "test@gumroad.com", giftee_email:).count).to eq 1 gifter_purchase = licensed_product.sales.is_gift_sender_purchase.sole giftee_purchase = licensed_product.sales.is_gift_receiver_purchase.sole expect(gifter_purchase.license).to be_nil expect(giftee_purchase.license).to_not be_nil expect(giftee_purchase.license_key).to be_present end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/sca/indian_card_mandates_spec.rb
spec/requests/purchases/product/sca/indian_card_mandates_spec.rb
# frozen_string_literal: true require("spec_helper") require "timeout" describe("Successful purchases from a product page with SCA and mandate creation for Indian cards", type: :system, js: true) do let(:creator) { create(:named_user) } let(:product) { create(:product, user: creator) } let(:membership_product) { create(:membership_product_with_preset_tiered_pricing, user: creator) } let(:free_trial_membership_product) { create(:membership_product_with_preset_tiered_pricing, :with_free_trial_enabled, user: creator) } let(:preorder_product) { create(:preorder_link, link: create(:product, is_in_preorder_state: true)).link } it "allows making a regular product purchase and does not set up a mandate on Stripe" do visit product.long_url add_to_cart(product) check_out(product, credit_card: { number: "4000003560000123" }, sca: true) purchase = Purchase.last expect(purchase.successful?).to be true expect(purchase.stripe_transaction_id).to be_present expect(purchase.processor_payment_intent_id).to be_present expect(purchase.processor_payment_intent).to be_present expect(purchase.credit_card).to be nil stripe_payment_intent = Stripe::PaymentIntent.retrieve(purchase.processor_payment_intent_id) stripe_charge = Stripe::Charge.retrieve(stripe_payment_intent.latest_charge) expect(stripe_charge.payment_method_details.card.mandate).to be nil end it "allows making a membership purchase and creates a mandate on Stripe for future off-session charges" do visit membership_product.long_url add_to_cart(membership_product, option: "Second Tier") check_out(membership_product, credit_card: { number: "4000003560000123" }, sca: true) purchase = Purchase.last expect(purchase.successful?).to be true expect(purchase.stripe_transaction_id).to be_present expect(purchase.processor_payment_intent_id).to be_present expect(purchase.processor_payment_intent).to be_present expect(purchase.credit_card.stripe_payment_intent_id).to be_present stripe_payment_intent = Stripe::PaymentIntent.retrieve(purchase.credit_card.stripe_payment_intent_id) stripe_charge = Stripe::Charge.retrieve(stripe_payment_intent.latest_charge) expect(stripe_charge.payment_method_details.card.mandate).to be_present end it "allows making a membership purchase and creates a mandate for future off-session charges with a card that cancels the mandate" do visit membership_product.long_url add_to_cart(membership_product, option: "Second Tier") check_out(membership_product, credit_card: { number: "4000003560000263" }, sca: true) purchase = Purchase.last expect(purchase.successful?).to be true expect(purchase.stripe_transaction_id).to be_present expect(purchase.processor_payment_intent_id).to be_present expect(purchase.processor_payment_intent).to be_present expect(purchase.credit_card.stripe_payment_intent_id).to be_present stripe_payment_intent = Stripe::PaymentIntent.retrieve(purchase.credit_card.stripe_payment_intent_id) stripe_charge = Stripe::Charge.retrieve(stripe_payment_intent.latest_charge) expect(stripe_charge.payment_method_details.card.mandate).to be_present end it "allows making a free-trial membership purchase and creates a mandate on Stripe for future off-session charges" do visit free_trial_membership_product.long_url add_to_cart(free_trial_membership_product, option: "Second Tier") check_out(free_trial_membership_product, credit_card: { number: "4000003560000123" }, sca: true) purchase = Purchase.last expect(purchase.not_charged?).to be true expect(purchase.stripe_transaction_id).not_to be_present expect(purchase.processor_setup_intent_id).to be_present expect(purchase.credit_card.stripe_setup_intent_id).to be_present expect(Stripe::SetupIntent.retrieve(purchase.credit_card.stripe_setup_intent_id).mandate).to be_present end it "allows making a pre-order purchase and creates a mandate on Stripe for future off-session charges" do preorder_product = create(:product, is_in_preorder_state: true) create(:preorder_link, link: preorder_product) visit "/l/#{preorder_product.unique_permalink}" add_to_cart(preorder_product) check_out(preorder_product, credit_card: { number: "4000003560000123" }, sca: true) expect(page).to have_content("We sent a receipt to test@gumroad.com") expect(page).to have_text("$1") purchase = Purchase.last expect(purchase.preorder_authorization_successful?).to be true expect(purchase.stripe_transaction_id).not_to be_present expect(purchase.processor_setup_intent_id).to be_present expect(purchase.credit_card.stripe_setup_intent_id).to be_present expect(Stripe::SetupIntent.retrieve(purchase.credit_card.stripe_setup_intent_id).mandate).to be_present end context "via stripe connect" do before { allow_any_instance_of(User).to receive(:check_merchant_account_is_linked).and_return(true) } let!(:stripe_connect_account) { create(:merchant_account_stripe_connect, charge_processor_merchant_id: "acct_1SOb0DEwFhlcVS6d", user: creator) } it "allows making a regular product purchase and does not set up a mandate on Stripe" do visit product.long_url add_to_cart(product) check_out(product, credit_card: { number: "4000003560000123" }, sca: true) purchase = Purchase.last expect(purchase.successful?).to be true expect(purchase.stripe_transaction_id).to be_present expect(purchase.processor_payment_intent_id).to be_present expect(purchase.processor_payment_intent).to be_present expect(purchase.credit_card).to be nil expect(purchase.merchant_account).to eq(stripe_connect_account) stripe_payment_intent = Stripe::PaymentIntent.retrieve(purchase.processor_payment_intent_id, { stripe_account: stripe_connect_account.charge_processor_merchant_id }) stripe_charge = Stripe::Charge.retrieve(stripe_payment_intent.latest_charge, { stripe_account: stripe_connect_account.charge_processor_merchant_id }) expect(stripe_charge.payment_method_details.card.mandate).to be nil end it "allows making a membership purchase and sets up the mandate properly" do visit membership_product.long_url add_to_cart(membership_product, option: "Second Tier") check_out(membership_product, credit_card: { number: "4000003560000123" }, sca: true) purchase = Purchase.last expect(purchase.successful?).to be true expect(purchase.stripe_transaction_id).to be_present expect(purchase.processor_payment_intent_id).to be_present expect(purchase.processor_payment_intent).to be_present expect(purchase.credit_card.stripe_payment_intent_id).to be_present expect(purchase.merchant_account).to eq(stripe_connect_account) stripe_payment_intent = Stripe::PaymentIntent.retrieve(purchase.credit_card.stripe_payment_intent_id, { stripe_account: stripe_connect_account.charge_processor_merchant_id }) stripe_charge = Stripe::Charge.retrieve(stripe_payment_intent.latest_charge, { stripe_account: stripe_connect_account.charge_processor_merchant_id }) expect(stripe_charge.payment_method_details.card.mandate).to be_present end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/sca/sca_spec.rb
spec/requests/purchases/product/sca/sca_spec.rb
# frozen_string_literal: true require("spec_helper") require "timeout" describe("Purchase from a product page with SCA (Strong Customer Authentication)", type: :system, js: true) do before do @creator = create(:named_user) @product = create(:product, user: @creator) end context "as a logged in user" do before do @user = create(:user) login_as @user end context "when SCA fails" do it "creates a failed purchase for a classic product" do visit "#{@product.user.subdomain_with_protocol}/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, logged_in_user: @user, credit_card: { number: "4000002500003155" }, sca: false, error: "We are unable to authenticate your payment method. Please choose a different payment method and try again.") end it "creates a failed purchase for 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, credit_card: { number: "4000002500003155" }, sca: false, error: "We are unable to authenticate your payment method. Please choose a different payment method and try again.") end it "creates a failed purchase for a pre-order product" do product = create(:product_with_files, is_in_preorder_state: true) preorder_product = create(:preorder_link, link: product, release_at: 25.hours.from_now) visit "#{product.user.subdomain_with_protocol}/l/#{product.unique_permalink}" expect do add_to_cart(product) check_out(product, logged_in_user: @user, credit_card: { number: "4000002500003155" }, sca: false, error: "We are unable to authenticate your payment method. Please choose a different payment method and try again.") end.to change { preorder_product.preorders.authorization_failed.count }.by(1) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/sca/sca_success_spec.rb
spec/requests/purchases/product/sca/sca_success_spec.rb
# frozen_string_literal: true require("spec_helper") require "timeout" describe("Successful purchases from a product page with SCA (Strong Customer Authentication)", type: :system, js: true) do before do @creator = create(:named_user) @product = create(:product, user: @creator) end context "as a guest user" do it "allows to make a classic purchase" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, credit_card: { number: "4000002500003155" }, sca: true) end it "allows to purchase a classic product via stripe connect account" do allow_any_instance_of(User).to receive(:check_merchant_account_is_linked).and_return(true) stripe_connect_account = create(:merchant_account_stripe_connect, charge_processor_merchant_id: "acct_1SOb0DEwFhlcVS6d", user: @product.user) visit @product.long_url add_to_cart(@product) check_out(@product, credit_card: { number: "4000002500003155" }, sca: true) expect(Purchase.last.successful?).to be true expect(Purchase.last.stripe_transaction_id).to be_present expect(Purchase.last.merchant_account).to eq(stripe_connect_account) end end context "as a logged in user" do before do @user = create(:user) login_as @user end it "allows to purchase a classic product" do visit "#{@product.user.subdomain_with_protocol}/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, credit_card: { number: "4000002500003155" }, sca: true, logged_in_user: @user) end it "allows to purchase a classic product via stripe connect account" do allow_any_instance_of(User).to receive(:check_merchant_account_is_linked).and_return(true) stripe_connect_account = create(:merchant_account_stripe_connect, charge_processor_merchant_id: "acct_1SOb0DEwFhlcVS6d", user: @product.user) visit @product.long_url add_to_cart(@product) check_out(@product, credit_card: { number: "4000002500003155" }, sca: true, logged_in_user: @user) expect(Purchase.last.successful?).to be true expect(Purchase.last.stripe_transaction_id).to be_present expect(Purchase.last.merchant_account).to eq(stripe_connect_account) 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/purchase/purchase_spec.rb
spec/requests/purchases/product/purchase/purchase_spec.rb
# frozen_string_literal: true require("spec_helper") require "timeout" describe("Purchases from the product page", type: :system, js: true) do before do @user = create(:named_user) @product = create(:product, user: @user, custom_receipt: "<h1>Hello</h1>") end it "shows quantity selector only when quantity of the link is greater than 1" do physical_link = create(:physical_product, max_purchase_count: 1) visit "/l/#{physical_link.unique_permalink}" expect(page).not_to have_field("Quantity") physical_link.update_attribute(:max_purchase_count, 2) visit "/l/#{physical_link.unique_permalink}" expect(page).to have_field("Quantity") end describe "already bought notice" do it "shows already bought notice if so" do @product = create(:product_with_pdf_file) @user = create(:user, email: "bought@gumroad.com") @purchase = create(:purchase, link: @product, email: "bought@gumroad.com", purchaser: @user) @url_redirect = create(:url_redirect, purchase: @purchase) login_as @user visit "#{@product.user.subdomain_with_protocol}/l/#{@product.unique_permalink}" expect(page).to have_link("View content", href: @url_redirect.download_page_url) end it "shows custom view content text for already bought notice" do @product = create(:product_with_pdf_file) @product.custom_view_content_button_text = "Custom Text" @product.save! @user = create(:user, email: "bought@gumroad.com") @purchase = create(:purchase, link: @product, email: "bought@gumroad.com", purchaser: @user) @url_redirect = create(:url_redirect, purchase: @purchase) login_as @user visit "#{@product.user.subdomain_with_protocol}/l/#{@product.unique_permalink}" expect(page).to have_link("Custom Text", href: @url_redirect.download_page_url) end it "shows already bought notice and 'View content' button even when there are no files" do @user = create(:user, email: "bought@gumroad.com") @purchase = create(:purchase, link: @product, purchaser: @user) @url_redirect = create(:url_redirect, purchase: @purchase) login_as @user visit @product.long_url expect(page).to have_text("You've purchased this product") expect(page).to have_text("View content") end describe "autofilling email address" do context "when buyer is logged in" do before do @buyer = create(:user) login_as @buyer end context "and has an email address" do it "autofills the buyer's email address and prevents editing" do visit @product.long_url click_on "I want this!" expect(page).to have_field("Email address", with: @buyer.email, disabled: true) end end context "and doesn't have an email address" do it "doesn't autofill the email address or prevent editing" do @buyer.email = nil @buyer.save!(validate: false) visit @product.long_url click_on "I want this!" expect(page).to have_field("Email address", with: "", disabled: false) end end end context "when buyer is not logged in" do it "doesn't autofill the email address" do visit @product.long_url click_on "I want this!" expect(page).to have_field("Email address", with: "") end end end context "for a membership" do before do user = create(:user) @purchase = create(:membership_purchase, email: user.email, purchaser: user) @manage_membership_url = Rails.application.routes.url_helpers.manage_subscription_url(@purchase.subscription.external_id, host: "#{PROTOCOL}://#{DOMAIN}") @product = @purchase.link login_as user end it "shows manage membership button for an active membership" do visit "#{@product.user.subdomain_with_protocol}/l/#{@product.unique_permalink}" expect(page).to have_link "Manage membership", href: @manage_membership_url end it "shows restart membership button for an inactive membership" do @purchase.subscription.update!(cancelled_at: 1.minute.ago) visit "#{@product.user.subdomain_with_protocol}/l/#{@product.unique_permalink}" expect(page).to have_link "Restart membership", href: @manage_membership_url end end end it "allows test purchase for creators" do creator = create(:user) link = create(:product, user: creator, price_cents: 200) login_as(creator) visit "#{link.user.subdomain_with_protocol}/l/#{link.unique_permalink}" add_to_cart(link) check_out(link, logged_in_user: creator) end it "allows test purchase for creators with auto-filled full name" do creator = create(:named_user) link = create(:product, user: creator, price_cents: 200) login_as(creator) visit "#{link.user.subdomain_with_protocol}/l/#{link.unique_permalink}" add_to_cart(link) check_out(link, logged_in_user: creator) end it "displays and saves the full name field if the user is not the product owner" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product) expect(Purchase.last.full_name).to eq "Gumhead Moneybags" end it "sends customer email and name to Stripe for fraud detection" do product = create(:product, price_cents: 2500) visit product.long_url add_to_cart(product) check_out(product, email: "test+stripe@gumroad.com") stripe_billing_details = Stripe::PaymentMethod.retrieve(Purchase.last.stripe_card_id).billing_details expect(stripe_billing_details.email).to eq "test+stripe@gumroad.com" expect(stripe_billing_details.name).to eq "Gumhead Moneybags" end context "when an active account already exists for the purchase email" do before do @purchase_email = "test@gumroad.com" create(:user, email: @purchase_email) end it "does not show sign up form on the checkout receipt" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, email: @purchase_email) end end it "has correct recommendation info when bought via receipt" do allow_any_instance_of(Link).to receive(:recommendable?).and_return(true) visit "/l/#{@product.unique_permalink}?recommended_by=receipt" expect do add_to_cart(@product, recommended_by: "receipt") check_out(@product) end.to change { @product.sales.successful.select(&:was_discover_fee_charged?).count }.by(1) .and change { @product.sales.successful.select(&:was_product_recommended?).count }.by(1) .and change { RecommendedPurchaseInfo.where(recommendation_type: "receipt").count }.by(1) end it "retrieves the url parameters from the query string, strips out reserved url parameters and queues endpoint notification job" do user = create(:user, notification_endpoint: "http://www.notification_endpoint.com") link = create(:product, user:) visit("/l/#{link.unique_permalink}?source_url=http://nathanbarry.com/authority&first_param=testparam&second_param=testparamagain&code=blah") add_to_cart(link) check_out(link) # `"code" => "blah"` should not be considered a URL parameter because 'code' is a reserved word. expected_job_args = [ Purchase.last.id, { "first_param" => "testparam", "second_param" => "testparamagain", "source_url" => "http://nathanbarry.com/authority" } ] expect(PostToPingEndpointsWorker).to have_enqueued_sidekiq_job(*expected_job_args) end it "shows the quick purchase form for a plain vanilla product with a saved CC" do link = create(:product, price_cents: 200) user = create(:user, credit_card: create(:credit_card)) login_as(user) visit "#{link.user.subdomain_with_protocol}/l/#{link.unique_permalink}" add_to_cart(link) check_out(link, logged_in_user: user) end it "shows default view content button text on receipt after successful purchase" do product = create(:product_with_files) product2 = create(:product) expect(product.custom_view_content_button_text.blank?).to be(true) visit "#{product.user.subdomain_with_protocol}/l/#{product.unique_permalink}" 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_link("View content") end it "shows the view content button on the purchase receipt for a product having rich content" 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.") expect(page).to have_link("View content") # Should see 'View content' button on the canonical purchase receipt page visit receipt_purchase_url(Purchase.last.external_id, email: Purchase.last.email, host: "#{PROTOCOL}://#{DOMAIN}") expect(page).to have_link("View content") # Should see 'View content' button on the product page itself once purchased visit "#{product.user.subdomain_with_protocol}/l/#{product.unique_permalink}" expect(page).to have_text("You've purchased this product") expect(page).to have_link("View content") end describe "discord integration" do let(:integration) { create(:discord_integration) } let(:product) { create(:product, price_range: "0+", customizable_price: true) } def buy_product(product) visit "#{product.user.subdomain_with_protocol}/l/#{product.unique_permalink}" add_to_cart(product, pwyw_price: 0) check_out(product, is_free: true) end describe "Join Discord" do it "shows the join discord button if integration is present on purchased product" do product.active_integrations << integration buy_product(product) 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 buy_product(product) expect(page).to_not have_button "Join Discord" end end end it "shows custom view content button text on receipt after successful purchase" do product = create(:product_with_files) product2 = create(:product) product.custom_view_content_button_text = "Custom Text" product.save! 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_link("Custom Text") end it "records product events correctly for a product with custom permalink" do product = create(:product_with_pdf_file, custom_permalink: "custom", description: Faker::Lorem.paragraphs(number: 100).join(" ")) product2 = create(:product) user = create(:user, credit_card: create(:credit_card)) login_as(user) visit product.long_url scroll_to first("footer") click_on "I want this!", match: :first Timeout.timeout(Capybara.default_max_wait_time) do until Event.where(event_name: "i_want_this", link_id: product.id).count == 1 do sleep 0.5 end end visit product2.long_url add_to_cart(product2) Timeout.timeout(Capybara.default_max_wait_time) do until Event.where(event_name: "i_want_this", link_id: product2.id).count == 1 do sleep 0.5 end end product2.update!(price_cents: 500) check_out(product2, logged_in_user: user, error: "The price just changed! Refresh the page for the updated price.") Timeout.timeout(Capybara.default_max_wait_time) do until Event.where(event_name: "process_payment", link_id: product.id).count == 1 do sleep 0.5 end end click_on "View content" Timeout.timeout(Capybara.default_max_wait_time) do until Event.where(event_name: "receipt_view_content", link_id: product.id).count == 1 do sleep 0.5 end end visit product.long_url click_on "View content" Timeout.timeout(Capybara.default_max_wait_time) do until Event.where(event_name: "product_information_view_product", link_id: product.id).count == 1 do sleep 0.5 end end end it "allows the purchase for a zip code plus 4" do creator = create(:user) link = create(:product, price_cents: 200, user: creator) visit "/l/#{link.unique_permalink}" add_to_cart(link) check_out(link, zip_code: "94104-5401") purchase = Purchase.last expect(purchase.successful?).to be true expect(purchase.zip_code).to eq "94104-5401" end it "ignores native paypal card and allows purchase" do customer = create(:user) native_paypal_card = create(:credit_card, chargeable: create(:native_paypal_chargeable), user: customer) customer.credit_card = native_paypal_card customer.save! creator = create(:user) link = create(:product, price_cents: 200, user: creator) # Creator adds support for native paypal payments create(:merchant_account_paypal, user: creator, charge_processor_merchant_id: "CJS32DZ7NDN5L", currency: "gbp") login_as(customer) visit "/l/#{link.unique_permalink}" add_to_cart(link) uncheck "Save card" check_out(link, logged_in_user: customer) purchase = Purchase.last expect(purchase.successful?).to be true expect(purchase.charge_processor_id).to eq(StripeChargeProcessor.charge_processor_id) expect(purchase.credit_card).to be_nil end it "changes email to lowercase before purchase" do email = "test@gumroad.com" visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, email: email.upcase) expect(Purchase.last.email).to eq email.downcase end it "stores a purchase event" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product) purchase = Purchase.last! event = Event.purchase.last! expect(event.purchase_id).to eq(purchase.id) expect(event.browser).to match(/Mozilla/) end it "assigns a license key to a purchase if the link supports it" do link = create(:product, user: create(:user)) link.is_licensed = true link.save! visit("/l/#{link.unique_permalink}") add_to_cart(link) check_out(link) purchase = Purchase.last expect(purchase.license).to_not be(nil) expect(purchase.link.licenses.count).to eq 1 end it "does not show the 'charged your card' message when purchasing a pre-order product" do preorder_product = create(:product, is_in_preorder_state: true) create(:preorder_link, link: preorder_product) visit "/l/#{preorder_product.unique_permalink}" add_to_cart(preorder_product) check_out(preorder_product) expect(page).to have_content("We sent a receipt to test@gumroad.com") expect(page).to have_text("$1") end describe "not for sale" do it "shows an alert and doesn't allow purchase when product is sold out" do @product = create(:product, max_purchase_count: 0) visit @product.long_url expect(page).to have_text("Sold out, please go back and pick another option.") expect(page).not_to have_text("I want this!") end it "shows an alert and doesn't allow purchase when product is unpublished" do @product = create(:product_with_pdf_file) @product.publish! @product.unpublish! visit @product.long_url expect(page).to have_text("This product is not currently for sale.") expect(page).not_to have_text("I want this!") end it "doesn't show an alert and allows purchase when product is a draft" do @product = create(:product) visit @product.long_url expect(page).not_to have_text("This product is not currently for sale.") expect(page).to have_text("I want this!") end end describe "analytics" do before do @product2 = create(:product) end context "when there is only one purchase" do it "doesn't mark the purchase as a bundle purchase" do visit @product.long_url add_to_cart(@product) check_out(@product) expect(Purchase.last.is_multi_buy).to eq(false) end end context "when there is more than one purchase" do it "marks the purchases as a bundle purchase" do visit @product.long_url add_to_cart(@product) visit @product2.long_url add_to_cart(@product2) check_out(@product2) expect(Purchase.last.is_multi_buy).to eq(true) expect(Purchase.second_to_last.is_multi_buy).to eq(true) end end it "sets the referrer correctly for all cart items" do @product3 = create(:product) visit "#{@product.long_url}?referrer=#{CGI.escape("https://product.com?size=M&color=red+guava")}" add_to_cart(@product) visit "#{@product2.long_url}?referrer=https://product2.com" add_to_cart(@product2) visit @product3.long_url add_to_cart(@product3) check_out(@product3) expect(Purchase.last.referrer).to eq("https://product.com?size=M&color=red+guava") expect(Purchase.second_to_last.referrer).to eq("https://product2.com") expect(Purchase.third_to_last.referrer).to eq("direct") expect(Event.last.referrer_domain).to eq("product.com") expect(Event.second_to_last.referrer_domain).to eq("product2.com") expect(Event.third_to_last.referrer_domain).to eq("direct") end end context "when an authenticated buyer purchases multiple products" do before do @product1 = create(:product, name: "Product 1") @product2 = create(:product, name: "Product 2") @user = create(:user) login_as(@user) end it "redirects to the library page on purchase success" do visit @product1.long_url add_to_cart(@product1) visit @product2.long_url add_to_cart(@product2) check_out(@product2, logged_in_user: @user) expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to #{@user.email}.") expect(page.current_path).to eq("/library") expect(page).to have_section(@product1.name) expect(page).to have_section(@product2.name) end end context "when an unauthenticated buyer purchases multiple products" do before do @product1 = create(:product, name: "Product 1") @product2 = create(:product_with_digital_versions, name: "Product 2") end it "redirects to the library page on purchase success" do visit @product1.long_url add_to_cart(@product1) visit @product2.long_url add_to_cart(@product2, option: "Untitled 1") check_out(@product2) expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to have_link(@product1.name, href: Purchase.last.url_redirect.download_page_url) expect(page).to have_link("#{@product2.name} - Untitled 1", href: Purchase.second_to_last.url_redirect.download_page_url) expect(page).to have_text("Create an account to access all of your purchases in one place") expect(page).to have_field("Email", with: "test@gumroad.com") end end describe "with combined_charge feature enabled" do before do @seller = create(:user) @product1 = create(:product, name: "Product 1", user: @seller) @product2 = create(:product, name: "Product 2", user: @seller) @product3 = create(:product_with_digital_versions, name: "Product 3", user: @seller) @seller2 = create(:user) @product4 = create(:product, name: "Product 4", user: @seller2) @product5 = create(:product, name: "Product 5", user: @seller2) @product6 = create(:product_with_digital_versions, name: "Product 6", user: @seller2) @buyer = create(:user) expect_any_instance_of(OrdersController).to receive(:create).and_call_original expect(PurchasesController).not_to receive(:create) end context "when an authenticated buyer purchases multiple products from different sellers" do before do login_as(@buyer) end it "redirects to the library page on purchase success" do visit @product1.long_url add_to_cart(@product1) visit @product2.long_url add_to_cart(@product2) visit @product4.long_url add_to_cart(@product4) visit @product5.long_url add_to_cart(@product5) check_out(@product5, logged_in_user: @buyer) expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to #{@buyer.email}.") expect(page.current_path).to eq("/library") expect(page).to have_section(@product1.name) expect(page).to have_section(@product2.name) expect(page).to have_section(@product4.name) expect(page).to have_section(@product5.name) end end context "when an unauthenticated buyer purchases multiple products from different sellers" do it "redirects to the library page on purchase success" do visit @product1.long_url add_to_cart(@product1) visit @product3.long_url add_to_cart(@product3, option: "Untitled 1") visit @product4.long_url add_to_cart(@product4) visit @product6.long_url add_to_cart(@product6, option: "Untitled 1") check_out(@product6) expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to have_link(@product1.name, href: Purchase.last.url_redirect.download_page_url) expect(page).to have_link("#{@product3.name} - Untitled 1", href: Purchase.second_to_last.url_redirect.download_page_url) expect(page).to have_link(@product4.name, href: Purchase.last(3).first.url_redirect.download_page_url) expect(page).to have_link("#{@product6.name} - Untitled 1", href: Purchase.last(4).first.url_redirect.download_page_url) expect(page).to have_text("Create an account to access all of your purchases in one place") expect(page).to have_field("Email", with: "test@gumroad.com") end end context "when an authenticated buyer purchases multiple products from same seller" do before do login_as(@buyer) end it "redirects to the library page on purchase success" do visit @product1.long_url add_to_cart(@product1) visit @product2.long_url add_to_cart(@product2) check_out(@product2, logged_in_user: @buyer) expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to #{@buyer.email}.") expect(page.current_path).to eq("/library") expect(page).to have_section(@product1.name) expect(page).to have_section(@product2.name) end end context "when an unauthenticated buyer purchases multiple products from same seller" do it "redirects to the library page on purchase success" do visit @product1.long_url add_to_cart(@product1) visit @product3.long_url add_to_cart(@product3, option: "Untitled 1") check_out(@product3) expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to test@gumroad.com.") expect(page).to have_link(@product1.name, href: Purchase.last.url_redirect.download_page_url) expect(page).to have_link("#{@product3.name} - Untitled 1", href: Purchase.second_to_last.url_redirect.download_page_url) expect(page).to have_text("Create an account to access all of your purchases in one place") expect(page).to have_field("Email", with: "test@gumroad.com") end end end describe "customer moderation" do context "when buyer's email is blocked by seller" do before do BlockedCustomerObject.block_email!(email: "test@gumroad.com", seller_id: @user.id) @buyer = create(:user, email: "test@gumroad.com") login_as @buyer end context "when the product is free" do before do @product.update!(price_cents: 0) end it "fails the purchase with an error" do visit @product.long_url add_to_cart(@product, pwyw_price: 0) expect do check_out(@product, logged_in_user: @buyer, is_free: true, error: "Your card was not charged, as the creator has prevented you from purchasing this item. Please contact them for more information.") end.to change { Purchase.count }.by(1) .and change { @user.blocked_customer_objects.active.count }.by(0) purchase = Purchase.last expect(purchase.successful?).to be(false) expect(purchase.email).to eq(@buyer.email) expect(purchase.error_code).to eq(PurchaseErrorCode::BLOCKED_CUSTOMER_EMAIL_ADDRESS) expect(@user.blocked_customer_objects.active.pluck(:object_type, :object_value, :buyer_email)).to match_array([["email", "test@gumroad.com", nil]]) end end end context "when buyer's email is unblocked by seller" do before do BlockedCustomerObject.block_email!(email: "test@gumroad.com", seller_id: @user.id) @user.blocked_customer_objects.active.find_each(&:unblock!) end it "succeeds the purchase" do visit @product.long_url add_to_cart(@product) expect do check_out(@product, email: "test@gumroad.com") end.to change { Purchase.count }.by(1) .and change { @user.blocked_customer_objects.active.count }.by(0) purchase = Purchase.last expect(purchase.successful?).to be(true) expect(purchase.email).to eq("test@gumroad.com") 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/purchase/purchase_variants_spec.rb
spec/requests/purchases/product/purchase/purchase_variants_spec.rb
# frozen_string_literal: true require("spec_helper") require "timeout" describe("Variant Purchases from product page", type: :system, js: true) do before do @user = create(:named_user) @product = create(:product, user: @user, custom_receipt: "<h1>Hello</h1>") end it "initializes variants from legacy query params" do variant_category = create(:variant_category, link: @product, title: "type") variants = [["default", 0], ["type 1 (test)", 150], ["type 2, extra", 200], ["type 3 (test, extra) + x", 300]] variants.each do |name, price_difference_cents| create(:variant, variant_category:, name:, price_difference_cents:) end # paren in option name should work fine, if escaped visit "/l/#{@product.unique_permalink}?variant=#{js_style_encode_uri_component("type 1 (test)")}" expect(page).to have_radio_button("type 1 (test)", checked: true) # comma in option name should work fine, if escaped visit "/l/#{@product.unique_permalink}?variant=#{js_style_encode_uri_component("type 2, extra")}" expect(page).to have_radio_button("type 2, extra", checked: true) # comma and parens together and a plus sign visit "/l/#{@product.unique_permalink}?variant=#{js_style_encode_uri_component("type 3 (test, extra) + x")}" expect(page).to have_radio_button("type 3 (test, extra) + x", checked: true) end it "displays variant select with product name if only tier is untitled" do link = create(:product, name: "Membership", is_recurring_billing: true, subscription_duration: :monthly, price_cents: 0) variant_category = create(:variant_category, link:, title: "Tier") create(:variant, variant_category:, name: "Untitled") visit("/l/#{link.unique_permalink}") expect(page).to_not have_radio_button("Untitled") expect(page).to have_radio_button("Membership") end it "displays the right suggested amount per variant for PWYW products" do @product.price_range = "3+" @product.customizable_price = true @product.save variant_category = create(:variant_category, link: @product, title: "type") [["default", 0], ["type 1 (test)", 150]].each do |name, price_difference_cents| create(:variant, variant_category:, name:, price_difference_cents:) end visit short_link_url(host: @user.subdomain_with_protocol, id: @product.unique_permalink, option: variant_category.variants[0].external_id) expect(page).to(have_field("Name a fair price:", placeholder: "3+")) choose "type 1 (test)" expect(page).to(have_field("Name a fair price:", placeholder: "4.50+")) fill_in "Name a fair price", with: "4" click_on "I want this!" expect(find_field("Name a fair price")["aria-invalid"]).to eq("true") add_to_cart(@product, option: "type 1 (test)", pwyw_price: 5) 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/shipping/shipping_address_verification_spec.rb
spec/requests/purchases/product/shipping/shipping_address_verification_spec.rb
# frozen_string_literal: true describe("Product Page - Shipping Scenarios Address verification", type: :system, js: true) do describe "US address" do before do @user = create(:user) @product = create(:physical_product, user: @user, require_shipping: true, price_cents: 100_00) @product.shipping_destinations << ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2, one_item_rate_cents: 2000, multiple_items_rate_cents: 1000) @product.save! end it "shows that the address is not valid but will let the purchase through if user says yes" do # have to mock EasyPost calls because the timeout throws before EasyPost responds in testing exception = EasyPost::Errors::EasyPostError.new expect_any_instance_of(EasyPost::Services::Address).to receive(:create).and_raise(exception) visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, should_verify_address: true) purchase = Purchase.last expect(purchase.street_address).to eq("1640 17th St") expect(purchase.city).to eq("San Francisco") expect(purchase.state).to eq("CA") expect(purchase.zip_code).to eq("94107") end it "shows that the address is missing some information" do # have to mock EasyPost calls because the timeout throws before EasyPost responds in testing easy_post = EasyPost::Client.new(api_key: GlobalConfig.get("EASYPOST_API_KEY")) address = easy_post.address.create( verify: ["delivery"], street1: "255 Nonexistent St", city: "San Francisco", state: "CA", zip: "94107", country: "US" ) verified_address = easy_post.address.create( verify: ["delivery"], street1: "255 King St Apt 602", city: "San Francisco", state: "CA", zip: "94107", country: "US" ) allow_any_instance_of(EasyPost::Services::Address).to receive(:create).and_return(address) visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, error: true) expect(page).to have_text("We are unable to verify your shipping address. Is your address correct?") click_on "No" expect_any_instance_of(EasyPost::Services::Address).to receive(:create).and_return(verified_address) check_out(@product, address: { street: "255 King St Apt 602" }) purchase = Purchase.last expect(purchase.street_address).to eq("255 KING ST APT 602") expect(purchase.city).to eq("SAN FRANCISCO") expect(purchase.state).to eq("CA") expect(purchase.zip_code).to eq("94107") end it "lets purchase with valid address through" do # have to mock EasyPost calls because the timeout throws before EasyPost responds in testing easy_post = EasyPost::Client.new(api_key: GlobalConfig.get("EASYPOST_API_KEY")) address = easy_post.address.create( verify: ["delivery"], street1: "1640 17th St", city: "San Francisco", state: "CA", zip: "94107", country: "US" ) expect_any_instance_of(EasyPost::Services::Address).to receive(:create).and_return(address) visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product) expect(page).not_to have_text("We are unable to verify your shipping address. Is your address correct?") purchase = Purchase.last expect(purchase.street_address).to eq("1640 17TH ST") expect(purchase.city).to eq("SAN FRANCISCO") expect(purchase.state).to eq("CA") expect(purchase.zip_code).to eq("94107") end describe "address verification confirmation prompt" do it "lets a buyer choose to use a verified address to complete their purchase" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, address: { street: "255 King St #602" }, error: true) expect(page).to(have_content("You entered this address:\n255 King St #602, San Francisco, CA, 94107")) expect(page).to(have_content("We recommend using this format:\n255 King St Apt 602, San Francisco, CA, 94107")) click_on "Yes, update" expect(page).to have_alert("Your purchase was successful!") purchase = Purchase.last expect(purchase.street_address).to eq("255 KING ST APT 602") expect(purchase.city).to eq("SAN FRANCISCO") expect(purchase.state).to eq("CA") expect(purchase.zip_code).to eq("94107") end it "lets a buyer choose not to use a verified address to complete their purchase" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, address: { street: "255 King St #602" }, error: true) expect(page).to(have_content("You entered this address:\n255 King St #602, San Francisco, CA, 94107")) expect(page).to(have_content("We recommend using this format:\n255 King St Apt 602, San Francisco, CA, 94107")) click_on "No, continue" expect(page).to have_alert("Your purchase was successful!") purchase = Purchase.last expect(purchase.street_address).to eq("255 King St #602") expect(purchase.city).to eq("San Francisco") expect(purchase.state).to eq("CA") expect(purchase.zip_code).to eq("94107") end it "does not allow the purchase if the buyer chooses not to use a verified address and the zip code is wrong for a taxable product" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, address: { street: "255 King St #602", zip_code: "invalid" }, error: true) expect(page).to(have_content("You entered this address:\n255 King St #602, San Francisco, CA, inval")) expect(page).to(have_content("We recommend using this format:\n255 King St Apt 602, San Francisco, CA, 94107")) click_on "No, continue" expect(page).to(have_alert("You entered a ZIP Code that doesn't exist within your country.")) expect(Purchase.count).to eq(0) end end end describe "international address" do it "shows that the address is not valid but will let the purchase through if user says yes" do @user = create(:user) @product = create(:physical_product, user: @user, require_shipping: true, price_cents: 100_00) @product.shipping_destinations << ShippingDestination.new(country_code: "CA", one_item_rate_cents: 2000, multiple_items_rate_cents: 1000) @product.save! # have to mock EasyPost calls because the timeout throws before EasyPost responds in testing exception = EasyPost::Errors::EasyPostError.new expect_any_instance_of(EasyPost::Services::Address).to receive(:create).and_raise(exception) visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, address: { city: "Burnaby", state: "BC", zip_code: "V3N 4H4" }, country: "Canada", should_verify_address: true) expect(page).to have_alert("Your purchase was successful!") purchase = Purchase.last expect(purchase.street_address).to eq("1640 17th St") expect(purchase.city).to eq("Burnaby") expect(purchase.state).to eq("BC") expect(purchase.zip_code).to eq("V3N 4H4") expect(purchase.country).to eq("Canada") end it "lets purchase with valid address through" do # have to mock EasyPost calls because the timeout throws before EasyPost responds in testing easy_post = EasyPost::Client.new(api_key: GlobalConfig.get("EASYPOST_API_KEY")) address = easy_post.address.create( verify: ["delivery"], street1: "9384 Cardston Ct", city: "Burnaby", state: "BC", zip: "V3N 4H4", country: "CA" ) expect_any_instance_of(EasyPost::Services::Address).to receive(:create).and_return(address) @user = create(:user) @product = create(:physical_product, user: @user, require_shipping: true, price_cents: 100_00) @product.shipping_destinations << ShippingDestination.new(country_code: "US", one_item_rate_cents: 2000, multiple_items_rate_cents: 1000) @product.save! visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, address: { street: "9384 Cardston Ct", city: "Burnaby", state: "BC", zip_code: "V3N 4H4" }, country: "Canada") expect(page).not_to have_text("We are unable to verify your shipping address. Is your address correct?") expect(page).to have_alert("Your purchase was successful!") purchase = Purchase.last expect(purchase.street_address).to eq("9384 CARDSTON CT") expect(purchase.city).to eq("BURNABY") expect(purchase.state).to eq("BC") expect(purchase.zip_code).to eq("V3N 4H4") expect(purchase.country).to eq("Canada") 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/shipping/shipping_physical_preorder_spec.rb
spec/requests/purchases/product/shipping/shipping_physical_preorder_spec.rb
# frozen_string_literal: true describe("Product Page - Shipping physical preoder", type: :system, js: true, shipping: true) do before do @creator = create(:user_with_compliance_info) @product = create(:physical_product, user: @creator, name: "physical preorder", price_cents: 16_00, require_shipping: true, is_in_preorder_state: true) @product.shipping_destinations << ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2, one_item_rate_cents: 4_00, multiple_items_rate_cents: 1_00) @product.save! @preorder_link = create(:preorder_link, link: @product) end it "charges the proper amount and stores shipping without taxes" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, should_verify_address: true) do expect(page).to have_text("Shipping rate US$4", normalize_ws: true) expect(page).to have_text("Total US$20", normalize_ws: true) end expect(page.all(:css, ".receipt-price")[0].text).to eq("$16") expect(page.all(:css, ".product-name")[1].text).to eq("Shipping") expect(page.all(:css, ".receipt-price")[1].text).to eq("$4") purchase = Purchase.last preorder = Preorder.last expect(purchase.total_transaction_cents).to eq(20_00) expect(purchase.price_cents).to eq(20_00) expect(purchase.shipping_cents).to eq(4_00) expect(purchase.purchase_state).to eq("preorder_authorization_successful") expect(purchase.email).to eq("test@gumroad.com") expect(purchase.link).to eq(@product) expect(purchase.street_address.downcase).to eq("1640 17th st") expect(purchase.city.downcase).to eq("san francisco") expect(purchase.state).to eq("CA") expect(purchase.zip_code).to eq("94107") expect(preorder.preorder_link).to eq(@preorder_link) expect(preorder.seller).to eq(@creator) expect(preorder.state).to eq("authorization_successful") end it "allows a free preorder purchase" do @product.shipping_destinations.last.update!(one_item_rate_cents: 0, multiple_items_rate_cents: 0) offer_code = create(:offer_code, products: [@product], amount_cents: 16_00) visit "/l/#{@product.unique_permalink}/#{offer_code.code}" add_to_cart(@product, offer_code:) check_out(@product, is_free: true, should_verify_address: true) expect(page).to have_text("Your purchase was successful!") expect(page).to have_text("physical preorder $0", normalize_ws: true) purchase = Purchase.last preorder = Preorder.last expect(purchase.total_transaction_cents).to eq(0) expect(purchase.price_cents).to eq(0) expect(purchase.shipping_cents).to eq(0) expect(purchase.purchase_state).to eq("preorder_authorization_successful") expect(purchase.email).to eq("test@gumroad.com") expect(purchase.link).to eq(@product) expect(purchase.street_address.downcase).to eq("1640 17th st") expect(purchase.city.downcase).to eq("san francisco") expect(purchase.state).to eq("CA") expect(purchase.zip_code).to eq("94107") expect(preorder.preorder_link).to eq(@preorder_link) expect(preorder.seller).to eq(@creator) expect(preorder.state).to eq("authorization_successful") end it "charges the proper amount with taxes for preorder" 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" }, should_verify_address: true) do expect(page).to have_text("Subtotal US$16", normalize_ws: true) expect(page).to have_text("Sales tax US$1.07", normalize_ws: true) expect(page).to have_text("Shipping rate US$4", normalize_ws: true) expect(page).to have_text("Total US$21.07", normalize_ws: true) end expect(page).to have_text("Your purchase was successful!") expect(page).to have_text("physical preorder $16", normalize_ws: true) expect(page).to have_text("Shipping $4", normalize_ws: true) expect(page).to have_text("Sales tax $1.07", normalize_ws: true) purchase = Purchase.last preorder = Preorder.last expect(purchase.total_transaction_cents).to eq(21_07) expect(purchase.price_cents).to eq(20_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(1_07) expect(purchase.shipping_cents).to eq(4_00) expect(purchase.purchase_state).to eq("preorder_authorization_successful") expect(purchase.email).to eq("test@gumroad.com") expect(purchase.link).to eq(@product) expect(purchase.street_address.downcase).to eq("3029 w sherman rd") expect(purchase.city.downcase).to eq("san tan valley") expect(purchase.state).to eq("AZ") expect(purchase.zip_code).to eq("85144") expect(preorder.preorder_link).to eq(@preorder_link) expect(preorder.seller).to eq(@creator) expect(preorder.state).to eq("authorization_successful") end it "charges the proper shipping amount for 2x quantity" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product, quantity: 2) check_out(@product, should_verify_address: true) do expect(page).to have_text("Shipping rate US$5", normalize_ws: true) expect(page).to have_text("Total US$37", normalize_ws: true) end expect(page.all(:css, ".receipt-price")[0].text).to eq("$32") expect(page.all(:css, ".product-name")[1].text).to eq("Shipping") expect(page.all(:css, ".receipt-price")[1].text).to eq("$5") purchase = Purchase.last preorder = Preorder.last expect(purchase.total_transaction_cents).to eq(37_00) expect(purchase.price_cents).to eq(37_00) expect(purchase.shipping_cents).to eq(5_00) expect(purchase.purchase_state).to eq("preorder_authorization_successful") expect(purchase.quantity).to eq(2) expect(purchase.email).to eq("test@gumroad.com") expect(purchase.link).to eq(@product) expect(purchase.street_address.downcase).to eq("1640 17th st") expect(purchase.city.downcase).to eq("san francisco") expect(purchase.state).to eq("CA") expect(purchase.zip_code).to eq("94107") expect(preorder.preorder_link).to eq(@preorder_link) expect(preorder.seller).to eq(@creator) expect(preorder.state).to eq("authorization_successful") 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/shipping/shipping_offer_codes_spec.rb
spec/requests/purchases/product/shipping/shipping_offer_codes_spec.rb
# frozen_string_literal: true describe("Product Page - Shipping with offer codes", type: :system, js: true, shipping: true) do it "allows the 50% offer code to only affect the product cost and not the shipping in USD" do @product = create(:product, user: create(:user), require_shipping: true, price_cents: 100_00) @offer_code = create(:percentage_offer_code, products: [@product], amount_percentage: 50, user: @product.user) @product.is_physical = true @product.price_currency_type = "usd" @product.shipping_destinations << ShippingDestination.new(country_code: "US", one_item_rate_cents: 2000, multiple_items_rate_cents: 1000) @product.save! visit "/l/#{@product.unique_permalink}/#{@offer_code.code}" add_to_cart(@product, offer_code: @offer_code) check_out(@product, should_verify_address: true) do expect(page).to have_text("Shipping rate US$20", normalize_ws: true) end expect(page).to have_alert("Your purchase was successful!") expect(Purchase.last.price_cents).to eq(7000) expect(Purchase.last.shipping_cents).to eq(2000) end it "allows the 100% offer code to affect only the product cost and not the shipping in USD" do @product = create(:product, user: create(:user, display_offer_code_field: true), require_shipping: true, price_cents: 100_00) @offer_code = create(:percentage_offer_code, products: [@product], amount_percentage: 100, user: @product.user) @product.is_physical = true @product.price_currency_type = "usd" @product.shipping_destinations << ShippingDestination.new(country_code: "US", one_item_rate_cents: 2000, multiple_items_rate_cents: 1000) @product.save! visit "/l/#{@product.unique_permalink}/#{@offer_code.code}" add_to_cart(@product, offer_code: @offer_code) check_out(@product, offer_code: @offer_code.code, should_verify_address: true) do expect(page).to have_text("Shipping rate US$20", normalize_ws: true) end expect(page).to have_alert("Your purchase was successful!") expect(Purchase.last.price_cents).to eq(2000) expect(Purchase.last.shipping_cents).to eq(2000) end it "only has the $50 offer code affect the product and not shipping and taxes" do @user = create(:user_with_compliance_info) @product = create( :product, user: @user, require_shipping: true, price_cents: 100_00, price_currency_type: "gbp", is_physical: true ) @product.shipping_destinations << ShippingDestination.new(country_code: "US", one_item_rate_cents: 2000, multiple_items_rate_cents: 1000) @product.save! @offer_code = create(:offer_code, products: [@product], currency_type: "gbp", amount_cents: 50_00, user: @product.user) visit "/l/#{@product.unique_permalink}/#{@offer_code.code}" add_to_cart(@product, offer_code: @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("Subtotal US$153.24", normalize_ws: true) expect(page).to have_text("Sales tax US$5.13", normalize_ws: true) expect(page).to have_text("Shipping rate US$30.65", normalize_ws: true) expect(page).to have_text("Total US$112.40", normalize_ws: true) end expect(page).to have_alert("Your purchase was successful!") expect(page).to have_text(@product.name) expect(Purchase.last.price_cents).to eq(10727) expect(Purchase.last.shipping_cents).to eq(3065) expect(Purchase.last.gumroad_tax_cents).to eq(513) end context "with a 100% offer code and free shipping" do before do @product = create(:product, require_shipping: true, price_cents: 1000, is_physical: true, shipping_destinations: [ShippingDestination.new(country_code: "US", one_item_rate_cents: 0, multiple_items_rate_cents: 0)], user: create(:user, display_offer_code_field: true)) @offer_code = create(:percentage_offer_code, products: [@product], amount_percentage: 100) end it "allows purchase" do visit "#{@product.long_url}/#{@offer_code.code}" add_to_cart(@product, offer_code: @offer_code) check_out(@product, offer_code: @offer_code.code, is_free: true, should_verify_address: true) expect(Purchase.last.price_cents).to eq(0) expect(Purchase.last.shipping_cents).to eq(0) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/purchases/product/shipping/shipping_physical_subscription_spec.rb
spec/requests/purchases/product/shipping/shipping_physical_subscription_spec.rb
# frozen_string_literal: true describe("Product Page - Shipping physical subscription", type: :system, js: true, shipping: true) do before do @creator = create(:user_with_compliance_info) Feature.deactivate_user(:merchant_migration, @creator) @sub_link = create(:physical_product, user: @creator, name: "physical subscription", price_cents: 16_00, is_recurring_billing: true, subscription_duration: :monthly, require_shipping: true) @sub_link.shipping_destinations << ShippingDestination.new(country_code: Compliance::Countries::USA.alpha2, one_item_rate_cents: 4_00, multiple_items_rate_cents: 1_00) @sub_link.save! end it "charges the proper amount and stores shipping without taxes" do visit "/l/#{@sub_link.unique_permalink}" add_to_cart(@sub_link) check_out(@sub_link, should_verify_address: true) do expect(page).to have_text("Shipping rate US$4", normalize_ws: true) expect(page).to have_text("Total US$20", normalize_ws: true) end expect(page).to have_alert("Your purchase was successful!") purchase = Purchase.last subscription = Subscription.last expect(purchase.total_transaction_cents).to eq(20_00) expect(purchase.price_cents).to eq(20_00) expect(purchase.shipping_cents).to eq(4_00) expect(purchase.subscription).to eq(subscription) expect(purchase.is_original_subscription_purchase).to eq(true) expect(purchase.link).to eq(@sub_link) expect(purchase.street_address.downcase).to eq("1640 17th st") expect(purchase.city.downcase).to eq("san francisco") expect(purchase.state).to eq("CA") expect(purchase.zip_code).to eq("94107") expect(subscription.email).to eq("test@gumroad.com") end it "charges the proper amount with taxes for subscription" do visit "/l/#{@sub_link.unique_permalink}" add_to_cart(@sub_link) check_out(@sub_link, 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$16", normalize_ws: true) expect(page).to have_text("Sales tax US$1.07", normalize_ws: true) expect(page).to have_text("Shipping rate US$4", normalize_ws: true) expect(page).to have_text("Total US$21.07", normalize_ws: true) end expect(page).to have_alert("Your purchase was successful!") purchase = Purchase.last subscription = Subscription.last expect(purchase.total_transaction_cents).to eq(21_07) expect(purchase.price_cents).to eq(20_00) expect(purchase.tax_cents).to eq(0) expect(purchase.gumroad_tax_cents).to eq(1_07) expect(purchase.shipping_cents).to eq(4_00) expect(purchase.subscription).to eq(subscription) expect(purchase.is_original_subscription_purchase).to eq(true) expect(purchase.link).to eq(@sub_link) expect(purchase.street_address.downcase).to eq("3029 w sherman rd") expect(purchase.city.downcase).to eq("san tan valley") expect(purchase.state).to eq("AZ") expect(purchase.zip_code).to eq("85144") expect(subscription.email).to eq("test@gumroad.com") end it "charges the proper shipping amount for 2x quantity" do visit "/l/#{@sub_link.unique_permalink}" add_to_cart(@sub_link, quantity: 2) check_out(@sub_link, should_verify_address: true) do expect(page).to have_text("Shipping rate US$5", normalize_ws: true) expect(page).to have_text("Total US$37", normalize_ws: true) end expect(page).to have_alert("Your purchase was successful!") purchase = Purchase.last expect(purchase.total_transaction_cents).to eq(37_00) expect(purchase.price_cents).to eq(37_00) expect(purchase.shipping_cents).to eq(5_00) expect(purchase.quantity).to eq(2) 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/shipping/shipping_spec.rb
spec/requests/purchases/product/shipping/shipping_spec.rb
# frozen_string_literal: true describe("Product Page - Shipping Scenarios", type: :system, js: true, shipping: true) do it "shows the shipping in USD in the blurb and not apply taxes on top of it" do @user = create(:user_with_compliance_info) @product = create( :physical_product, user: @user, require_shipping: true, price_cents: 100_00, price_currency_type: "gbp" ) @product.shipping_destinations << ShippingDestination.new(country_code: "US", one_item_rate_cents: 2000, multiple_items_rate_cents: 1000) @product.save! 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" }, should_verify_address: true) do expect(page).to have_text("Subtotal US$153.24", normalize_ws: true) expect(page).to have_text("Sales tax US$10.27", normalize_ws: true) expect(page).to have_text("Shipping rate US$30.65", normalize_ws: true) expect(page).to have_text("Total US$194.16", normalize_ws: true) end expect(Purchase.last.price_cents).to eq(18389) expect(Purchase.last.shipping_cents).to eq(3065) expect(Purchase.last.gumroad_tax_cents).to eq(1027) end it "shows the blurb for a purchase in USD" do @user = create(:user_with_compliance_info) @product = create(:product, user: @user, require_shipping: true, price_cents: 100_00) @product.is_physical = true @product.price_currency_type = "usd" @product.shipping_destinations << ShippingDestination.new(country_code: "US", one_item_rate_cents: 2000, multiple_items_rate_cents: 1000) @product.save! 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" }, should_verify_address: true) do expect(page).to have_text("Subtotal US$100", normalize_ws: true) expect(page).to have_text("Sales tax US$6.70", normalize_ws: true) expect(page).to have_text("Shipping rate US$20", normalize_ws: true) expect(page).to have_text("Total US$126.70", normalize_ws: true) end expect(Purchase.last.price_cents).to eq(12000) expect(Purchase.last.shipping_cents).to eq(2000) expect(Purchase.last.gumroad_tax_cents).to eq(670) end it "pre-selects user's country if not US, and shows appropriate shipping fee" do product = create(:product, require_shipping: true, is_physical: true, price_currency_type: "usd") product.shipping_destinations << build(:shipping_destination, country_code: "US", one_item_rate_cents: 10_00, multiple_items_rate_cents: 10_00) product.shipping_destinations << build(:shipping_destination, country_code: "IT", one_item_rate_cents: 15_00, multiple_items_rate_cents: 15_00) product.save! allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("72.229.28.185") # US visit "/l/#{product.unique_permalink}" add_to_cart(product) expect(page).to have_field("Country", with: "US") expect(page).to have_text("Shipping rate US$10", normalize_ws: true) allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("2.47.255.255") # Italy visit current_path expect(page).to have_field("Country", with: "IT") expect(page).to have_text("Shipping rate US$15", normalize_ws: true) end it "multiple quantities and an offer code" do @product = create(:physical_product, user: create(:user), require_shipping: true, price_cents: 100_00) @product.price_currency_type = "usd" @product.shipping_destinations << ShippingDestination.new(country_code: "US", one_item_rate_cents: 20_00, multiple_items_rate_cents: 15_00) @product.save! @offer_code = create(:offer_code, products: [@product], amount_cents: 50_00, user: @product.user) visit "/l/#{@product.unique_permalink}/#{@offer_code.code}" expect(page).to have_selector("[role='status']", text: "$50 off will be applied at checkout (Code #{@offer_code.code.upcase})") expect(page).to have_selector("[itemprop='price']", text: "$100 $50") add_to_cart(@product, quantity: 2, offer_code: @offer_code) check_out(@product, should_verify_address: true) do expect(page).to have_text("Shipping rate US$35", normalize_ws: true) expect(page).to have_text("Total US$135", normalize_ws: true) end expect(Purchase.last.price_cents).to eq(13500) expect(Purchase.last.shipping_cents).to eq(3500) expect(Purchase.last.quantity).to eq(2) end it "includes the default sku with the purchase" do @product = create(:physical_product, user: create(:user)) visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product, should_verify_address: true) expect(Purchase.last.variant_attributes).to eq(@product.skus.is_default_sku) end it "saves shipping address to purchaser if logged in" do # have to mock EasyPost calls because the timeout throws before EasyPost responds in testing easy_post = EasyPost::Client.new(api_key: GlobalConfig.get("EASYPOST_API_KEY")) address = easy_post.address.create( verify: ["delivery"], street1: "1640 17th St", city: "San Francisco", state: "CA", zip: "94107", country: "US" ) expect_any_instance_of(EasyPost::Services::Address).to receive(:create).at_least(:once).and_return(address) link = create(:product, price_cents: 200, require_shipping: true) user = create(:user, credit_card: create(:credit_card)) login_as(user) visit "#{link.user.subdomain_with_protocol}/l/#{link.unique_permalink}" add_to_cart(link) check_out(link, logged_in_user: user, credit_card: nil, should_verify_address: true) purchaser = Purchase.last.purchaser expect(purchaser.street_address).to eq("1640 17TH ST") expect(purchaser.city).to eq("SAN FRANCISCO") expect(purchaser.state).to eq("CA") expect(purchaser.zip_code).to eq("94107") end context "for a product with a single-unit currency" do it "calculates the correct shipping rate" do product = create(:physical_product, require_shipping: true, is_physical: true, price_currency_type: "jpy", price_cents: 500) product.shipping_destinations << build(:shipping_destination, country_code: "US", one_item_rate_cents: 500, multiple_items_rate_cents: 500) visit product.long_url add_to_cart(product) expect(page).to have_text("Subtotal US$6.38", normalize_ws: true) expect(page).to have_text("Shipping rate US$6.38", normalize_ws: true) expect(page).to have_text("Total US$12.76", normalize_ws: true) check_out(product, should_verify_address: true) expect(Purchase.last.price_cents).to eq(1276) expect(Purchase.last.shipping_cents).to eq(638) end end context "when the buyer's country is not in the seller's shipping destinations" do let(:product) { create(:product, require_shipping: true, is_physical: true, price_cents: 500) } let(:buyer) { create(:buyer_user, country: "Canada") } before do product.shipping_destinations << build(:shipping_destination, country_code: "US", one_item_rate_cents: 500) end it "allows purchase" do login_as buyer visit product.long_url add_to_cart(product) check_out(product, logged_in_user: buyer, should_verify_address: true) purchase = Purchase.last expect(purchase.country).to eq("United States") expect(purchase.price_cents).to eq(1000) expect(purchase.shipping_cents).to eq(500) 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/shipping/shipping_to_virtual_countries_spec.rb
spec/requests/purchases/product/shipping/shipping_to_virtual_countries_spec.rb
# frozen_string_literal: true describe("Product Page - Shipping to Virtual Countries", type: :system, js: true, shipping: true) do it "does not show the blurb if there is shipping, but no tax" do @product = create(:product, user: create(:user), require_shipping: true, price_cents: 100_00) @product.is_physical = true @product.price_currency_type = "usd" destination = ShippingDestination.new(country_code: ShippingDestination::Destinations::NORTH_AMERICA, one_item_rate_cents: 5_00, multiple_items_rate_cents: 1_00, is_virtual_country: true) @product.shipping_destinations << destination @product.save! visit "/l/#{@product.unique_permalink}" add_to_cart(@product) check_out(@product) do expect(page).to have_text("Shipping rate US$5", normalize_ws: true) expect(page).to have_text("Total US$105", normalize_ws: true) end expect(Purchase.last.price_cents).to eq(10500) expect(Purchase.last.shipping_cents).to eq(500) end it "shows correct shipping cost with multiple quantities" do @product = create(:physical_product, user: create(:user), require_shipping: true, price_cents: 100_00) @product.price_currency_type = "usd" destination = ShippingDestination.new(country_code: ShippingDestination::Destinations::NORTH_AMERICA, one_item_rate_cents: 5_00, multiple_items_rate_cents: 1_00, is_virtual_country: true) @product.shipping_destinations << destination @product.save! visit "/l/#{@product.unique_permalink}" add_to_cart(@product, quantity: 2) check_out(@product) do expect(page).to have_text("Shipping rate US$6", normalize_ws: true) expect(page).to have_text("Total US$206", normalize_ws: true) end expect(Purchase.last.price_cents).to eq(20600) expect(Purchase.last.shipping_cents).to eq(600) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/followers/followers_spec.rb
spec/requests/followers/followers_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" require "shared_examples/creator_dashboard_page" describe("Followers", js: true, type: :system) do let(:seller) { create(:named_seller) } before do @page_limit = FollowersController::FOLLOWERS_PER_PAGE @identifiable_follower = create(:follower, user: create(:user), followed_id: seller.id, follower_user_id: create(:user).id, email: "test@example.com", source: Follower::From::PROFILE_PAGE, created_at: Date.today, confirmed_at: Date.today) end include_context "with switching account to user as admin for seller" it_behaves_like "creator dashboard page", "Emails" do let(:path) { followers_path } end describe "no followers scenario" do before do Follower.destroy_all visit followers_path end it "displays no followers message" do expect(page).to have_content("Manage all of your followers in one place.") expect(page).to have_content("Interacting with and serving your audience is an important part of running your business.") expect(page).to have_button("Share subscribe page") end end describe "view followers scenario" do before do @confirmed_followers_count = @page_limit + 3 @unconfirmed_follower = create(:follower, user: create(:user), followed_id: seller.id, follower_user_id: create(:user).id, source: Follower::From::PROFILE_PAGE, created_at: Date.today) create(:follower, user: create(:user), followed_id: seller.id, follower_user_id: create(:user).id, source: Follower::From::PROFILE_PAGE, created_at: Date.today, deleted_at: Date.today) @follower_without_source = create(:follower, user: create(:user), followed_id: seller.id, follower_user_id: create(:user).id, email: "test_nosource@example.com", created_at: Date.today, confirmed_at: Date.yesterday) @follower_without_source2 = create(:follower, user: create(:user), followed_id: seller.id, follower_user_id: create(:user).id, email: "test_nosource2@example.com", created_at: Date.today, confirmed_at: Date.yesterday) @page_limit.times { |x| create(:follower, user: create(:user), followed_id: seller.id, follower_user_id: create(:user).id, source: Follower::From::PROFILE_PAGE, created_at: 1.week.ago, confirmed_at: Date.today) } visit followers_path end it "shows a list of confirmed followers with pagination" do tbody = find(:table, "All subscribers (#{@confirmed_followers_count})").find("tbody") within tbody do expect(page).to have_selector(:table_row, count: @page_limit) end click_on "Load more" within tbody do expect(page).to have_selector(:table_row, count: @confirmed_followers_count) end expect(page).to_not have_button "Load more" end it "supports search functionality" do expect(page).to_not have_selector(:table_row, text: "test@example.com") select_disclosure "Search" do fill_in("Search followers", with: "FALSE_EMAIL@gumroad") end expect(page).to_not have_table("All followers") expect(page).to_not have_button "Load more" expect(page).to have_content("No followers found") fill_in("Search followers", with: "test") expect(page).to have_selector(:table_row, text: "test@example.com", count: 1) expect(page).to have_selector(:table_row, text: "test_nosource@example.com", count: 1) expect(page).to have_selector(:table_row, text: "test_nosource2@example.com", count: 1) expect(page).to_not have_button "Load more" end end describe "follower drawer" do before do visit followers_path end it "shows and hides a drawer with the follower's information" do expect(page).to_not have_modal find(:table_row, text: "test@example.com").click within_modal "Details" do expect(page).to have_content("test@example.com") click_on "Close" end expect(page).to_not have_modal end it "deletes a follower" do find(:table_row, text: "test@example.com").click click_on "Remove follower" wait_for_ajax expect(page).to have_content("Follower removed!") expect(page).to_not have_modal follower = seller.followers.where(email: "test@example.com").first expect(follower.deleted?).to be true end end describe "subscribe page" do it "allows copying the subscribe page URL to the clipboard" do visit followers_path share_button = find_button("Share subscribe page") share_button.hover expect(share_button).to have_tooltip(text: "Copy to Clipboard") share_button.click expect(share_button).to have_tooltip(text: "Copied!") 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/favicon_spec.rb
spec/requests/user/favicon_spec.rb
# frozen_string_literal: true require "spec_helper" describe "User favicons", type: :system, js: true do before do @product = create(:product, name: "product name", user: create(:named_user)) @purchase = create(:purchase, link: @product) @post = create(:installment, seller: @product.user, link: @product, installment_type: "product", published_at: Time.current) @user = @product.user login_as @user upload_profile_photo end describe "user profile photo as a favicon" do it "does display on the profile page" do visit("/#{@user.username}") expect(page).to have_xpath("/html/head/link[@href='#{@user.avatar_url}']", visible: false) end it "does display on a post's page" do visit(view_post_path(username: @user.username, slug: @post.slug, purchase_id: @purchase.external_id)) expect(page).to have_xpath("/html/head/link[@href='#{@user.avatar_url}']", visible: false) end it "does display on a product page" do visit short_link_path(@product) expect(page).to have_xpath("/html/head/link[@href='#{@user.avatar_url}']", visible: false) end end private def upload_profile_photo visit settings_profile_path within_fieldset "Logo" do click_on "Remove" attach_file("Upload", file_fixture("test.png"), visible: false) end within_section("Preview", section_element: :aside) do expect(page).to have_selector("img[alt='Profile Picture'][src*=cdn_url_for_blob]") end click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(@user.reload.avatar_url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{@user.avatar_variant.key}") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/user/posts_spec.rb
spec/requests/user/posts_spec.rb
# frozen_string_literal: true require("spec_helper") require "shared_examples/authorize_called" describe("Posts on seller profile", type: :system, js: true) do include FillInUserProfileHelpers let(:seller) { create(:named_seller, :with_avatar) } let(:buyer) { create(:named_user) } before do section = create(:seller_profile_posts_section, seller:) create(:seller_profile, seller:, json_data: { tabs: [{ name: "", sections: [section.id] }] }) @product = create(:product, name: "a product", user: seller) @visible_product_post = create(:installment, link: @product, published_at: 1.days.ago, shown_on_profile: true) @hidden_product_post = create(:installment, link: @product, published_at: 2.days.ago, shown_on_profile: false) @standard_post = create(:follower_installment, seller:, published_at: 3.days.ago, shown_on_profile: true) @old_product_post = create(:installment, link: @product, published_at: 10.days.ago, shown_on_profile: true) @unpublished_audience_post = create(:audience_installment, seller:, shown_on_profile: true) @installments = build_list(:audience_installment, 17, seller:, shown_on_profile: true) do |installment, i| installment.name = "Audience post #{i + 1}" installment.published_at = i.days.ago installment.save! section.shown_posts << installment.id end section.save! @purchase = create(:purchase, link: @product, seller:, purchaser: buyer, created_at: 6.days.ago) @follower = create(:named_user) create(:follower, user: seller, email: @follower.email, confirmed_at: Time.current) end it "shows only the published audience profile posts" do def assert_posts expect(page).to_not have_link(@visible_product_post.name) expect(page).to_not have_link(@hidden_product_post.name) expect(page).to_not have_link(@standard_post.name) expect(page).to_not have_link(@old_product_post.name) expect(page).to_not have_link(@unpublished_audience_post.name) (0..16).each do |i| expect(page).to have_link(@installments[i].name) end end visit "#{seller.subdomain_with_protocol}" assert_posts login_as(buyer) refresh assert_posts logout login_as(seller) refresh assert_posts end describe "a product post slug page" do before do @new_installments = [] @new_installments << create(:installment, link: @product, published_at: 3.days.ago, shown_on_profile: false) @new_installments << create(:installment, link: @product, published_at: 4.days.ago, shown_on_profile: true) @new_installments << create(:installment, link: @product, published_at: 5.days.ago, shown_on_profile: true) end it "shows the content slug page for a shown_on_profile=false product post if logged in as the purchaser" do login_as(buyer) visit "#{seller.subdomain_with_protocol}/p/#{@hidden_product_post.slug}" expect(page).to have_title "#{@hidden_product_post.name} - #{seller.name}" expect(page).to have_selector("h1", text: @hidden_product_post.name) expect(page).to have_text @hidden_product_post.message end it "shows the content slug page for a shown_on_profile=false product post if logged out with the right purchase_id" do visit "/#{seller.username}/p/#{@hidden_product_post.slug}?purchase_id=#{@purchase.external_id}" expect(page).to have_title "#{@hidden_product_post.name} - #{seller.name}" expect(page).to have_selector("h1", text: @hidden_product_post.name) expect(page).to have_text @hidden_product_post.message end it "shows the content slug page for a shown_on_profile=false product post to the creator without a purchase_id" do login_as seller visit "#{seller.subdomain_with_protocol}/p/#{@hidden_product_post.slug}" expect(page).to have_title "#{@hidden_product_post.name} - #{seller.name}" expect(page).to have_selector("h1", text: @hidden_product_post.name) expect(page).to have_text @hidden_product_post.message end it "shows 'other posts for this product' on a product post page to a customer" do login_as(buyer) visit "#{seller.subdomain_with_protocol}/p/#{@hidden_product_post.slug}" expect(page).to have_link(@visible_product_post.name) (2..4).each do |i| expect(page).to have_link(@new_installments[i - 2].name) expect(page).to have_text(@new_installments[i - 2].published_at.strftime("%B %-d, %Y")) end expect(page).to_not have_link(@hidden_product_post.name) expect(page).to_not have_link(@old_product_post.name) end it "shows the date in the accurate format" do post = create(:installment, link: @product, published_at: Date.parse("Dec 08 2015"), shown_on_profile: true) login_as(buyer) visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" expect(page).to have_selector("time", text: "December 8, 2015") end end describe "a standard post slug page" do it "shows the content slug page for a standard post" do login_as(@follower) visit "#{seller.subdomain_with_protocol}/p/#{@standard_post.slug}" expect(page).to have_selector("h1", text: @standard_post.name) expect(page).to have_text @standard_post.message end it "shows 'recent posts' on a standard post" do login_as(@follower) visit "#{seller.subdomain_with_protocol}/p/#{@standard_post.slug}" expect(page).not_to have_link(@visible_product_post.name) expect(page).not_to have_link(@hidden_product_post.name) (4..6).each do |i| expect(page).to have_link(@installments[i - 4].name) end expect(page).to_not have_link(@standard_post.name) end end describe "an audience post" do describe "following" do before do @follower_email = generate(:email) end it "allows a user to follow the seller when logged in" do login_as(buyer) expect do visit "#{seller.subdomain_with_protocol}/p/#{@installments.first.slug}" submit_follow_form wait_for_ajax Follower.where(email: buyer.email).first.confirm! end.to change { Follower.active.count }.by(1) expect(Follower.last.follower_user_id).to eq buyer.id end it "allows a visitor to follow the seller when logged out" do visit "/#{seller.username}/p/#{@installments.first.slug}" expect do submit_follow_form(with: @follower_email) expect(page).to have_button("Subscribed", disabled: true) Follower.find_by(email: @follower_email).confirm! end.to change { Follower.active.count }.by(1) expect(Follower.last.email).to eq @follower_email end end describe "Comments" do let(:post) { @installments.first } let(:another_post) { @installments.last } let(:commenter) { create(:named_user, :with_avatar) } let!(:comment1) { create(:comment, commentable: post, author: post.seller, created_at: 2.months.ago) } let!(:comment2) { create(:comment) } let!(:comment3) { create(:comment, commentable: another_post, author: commenter) } before do # Set a different user as the seller of 'another_post' another_post.update!(seller: create(:user)) end context "when the 'allow_comments' flag is disabled" do before do post.update!(allow_comments: false) end it "does not show comments on the post" do visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" expect(page).to_not have_text("1 comment") end end it "shows comments on the post" do visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" within_section "1 comment" do expect(page).to have_text(comment1.author.display_name) expect(page).to have_selector("time", text: "2 months ago") expect(page).to have_text(comment1.content) expect(page).to have_text("Creator") end # as a non-signed in user expect(page).to_not have_field("Write a comment") expect(page).to have_text("Log in or Register to join the conversation") # try commenting as a signed in user login_as commenter visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" expect(page).to have_text("1 comment") fill_in("Write a comment", with: "Good article!") click_on("Post") wait_for_ajax expect(page).to have_alert(text: "Successfully posted your comment") within_section "2 comments" do within "article:nth-child(2)" do expect(page).to have_text(commenter.display_name) expect(page).to have_selector("time", text: "less than a minute ago") expect(page).to have_text("Good article!") expect(page).to_not have_text("Creator") end end visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" expect(page).to have_text("2 comments") # check comments on another post visit "#{seller.subdomain_with_protocol}/p/#{another_post.slug}" expect(page).to have_text("1 comment") expect(page).to have_text(comment3.author.display_name) expect(page).to have_text(comment3.content) end context "when signed in as a comment author" do let!(:own_comment) { create(:comment, commentable: post, author: commenter) } before do login_as commenter end it "allows the comment author to delete only their comments" do visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" within_section "2 comments" do expect("article:nth-child(1)").to_not have_disclosure("Open comment action menu") within "article:nth-child(2)" do select_disclosure "Open comment action menu" do click_on("Delete") end end expect(page).to have_text("Are you sure?") expect do click_on("Confirm") wait_for_ajax end.to change { own_comment.reload.alive? }.from(true).to(false) end expect(page).to have_alert(text: "Successfully deleted the comment") visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" expect(page).to have_text("1 comment") expect(page).to_not have_text(own_comment.content) end it "allows the comment author to edit only their comments" do visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" within_section "2 comments" do expect("article:nth-child(1)").to_not have_disclosure("Open comment action menu") within "article:nth-child(2)" do select_disclosure "Open comment action menu" do click_on("Edit") end fill_in("Write a comment", with: "Good article") click_on "Cancel" expect(page).to_not have_field("Write a comment") expect(page).to have_text(own_comment.content) select_disclosure "Open comment action menu" do click_on("Edit") end fill_in("Write a comment", with: "Good article") click_on("Update") wait_for_ajax expect(page).to have_text("Good article") expect(page).to_not have_button("Update") end end expect(page).to have_alert(text: "Successfully updated the comment") visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" within_section "2 comments" do expect(page).to have_selector("article:nth-child(2)", text: "Good article") end end it "updates comment count correctly when deleting a comment with replies" do create(:comment, parent: own_comment, commentable: post, author: commenter) visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" expect(page).to have_text("3 comments") within_section "3 comments" do within all("article")[1] do select_disclosure "Open comment action menu", match: :first do click_on("Delete") end end end expect(page).to have_text("Are you sure?") click_on("Confirm") wait_for_ajax expect(page).to have_alert(text: "Successfully deleted the comment") expect(page).to have_text("1 comment") end end shared_examples_for "delete and update as seller or team member" do it "allows the post author to delete any comment" do visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" select_disclosure "Open comment action menu" do click_on("Delete") end expect(page).to have_text("Are you sure?") expect do click_on("Confirm") wait_for_ajax expect(page).to have_alert(text: "Successfully deleted the comment") end.to change { comment1.reload.alive? }.from(true).to(false) visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" expect(page).to have_text("0 comments") expect(page).to_not have_text(comment1.content) end it "allows the post author to edit only their comments" do create(:comment, commentable: post) visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" within_section "2 comments" do within "article:nth-child(1)" do select_disclosure "Open comment action menu" do click_on("Edit") end fill_in("Write a comment", with: "Good article") click_on("Update") wait_for_ajax expect(page).to have_text("Good article") end end expect(page).to have_alert(text: "Successfully updated the comment") within_section "2 comments" do visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" expect(page).to have_selector("article:nth-child(1)", text: "Good article") within "article:nth-child(2)" do select_disclosure "Open comment action menu" do expect(page).to_not have_button("Edit") end end end end end context "when signed in as a post author" do before do login_as seller end include_examples "delete and update as seller or team member" end context "with switching account to user as admin for seller" do include_context "with switching account to user as admin for seller" let!(:comment1) { create(:comment, commentable: post, author: user_with_role_for_seller, created_at: 2.months.ago) } include_examples "delete and update as seller or team member" end context "when accessing a post using the link received in the purchase receipt" do let(:purchase) { create(:purchase, link: @product, full_name: "John Doe", created_at: 1.second.ago) } let(:product_post) { create(:published_installment, link: @product, shown_on_profile: true) } let(:seller_post) { create(:seller_installment, seller:, published_at: 1.day.ago) } let!(:comment) { create(:comment, commentable: product_post) } it "allows the not signed-in user to add comments and edit/delete own comments" do visit "#{seller.subdomain_with_protocol}/p/#{product_post.slug}?purchase_id=#{purchase.external_id}" within_section "1 comment" do # Does not allow editing or deleting others' comments expect("article:nth-child(1)").to_not have_disclosure("Open comment action menu") end # Allows adding a new comment fill_in("Write a comment", with: "good article") click_on("Post") wait_for_ajax expect(page).to have_alert(text: "Successfully posted your comment") within_section "2 comments" do within "article:nth-child(2)" do expect(page).to have_text("John Doe") expect(page).to have_text("good article") select_disclosure "Open comment action menu" do click_on("Edit") end fill_in("Write a comment", with: "Nice article!") click_on("Update") wait_for_ajax expect(page).to have_text("Nice article!") end end expect(page).to have_alert(text: "Successfully updated the comment") within_section "2 comments" do # Allows deleting own comment within "article:nth-child(2)" do select_disclosure "Open comment action menu" do click_on("Delete") end end expect(page).to have_text("Are you sure?") click_on("Confirm") wait_for_ajax expect(page).to_not have_text("Nice article!") end expect(page).to have_alert(text: "Successfully deleted the comment") expect(page).to have_text("1 comment") end it "allows posting a comment on a seller post" do visit "#{seller.subdomain_with_protocol}/p/#{seller_post.slug}?purchase_id=#{purchase.external_id}" fill_in "Write a comment", with: "Received this in my inbox! Nice article!" click_on "Post" wait_for_ajax expect(page).to have_text("Successfully posted your comment") page.execute_script("window.location.reload()") expect(page).to have_text("1 comment") expect(page).to have_text("Received this in my inbox! Nice article!") end end it "disallows posting or updating a comment with an adult keyword" do login_as commenter # Try posting a comment with an adult keyword visit "#{seller.subdomain_with_protocol}/p/#{another_post.slug}" expect(page).to have_text("1 comment") fill_in("Write a comment", with: "nsfw comment") click_on("Post") wait_for_ajax expect(page).to have_alert(text: "An error occurred while posting your comment - Adult keywords are not allowed") visit "#{seller.subdomain_with_protocol}/p/#{another_post.slug}" expect(page).to_not have_text("nsfw comment") within_section "1 comment" do # Try updating an existing comment with an adult keyword within "article:nth-child(1)" do select_disclosure "Open comment action menu" do click_on("Edit") end fill_in("Write a comment", with: "nsfw comment") click_on("Update") wait_for_ajax end end expect(page).to have_alert(text: "An error occurred while updating the comment - Adult keywords are not allowed") visit "#{seller.subdomain_with_protocol}/p/#{another_post.slug}" expect(page).to_not have_text("nsfw comment") end it "performs miscellaneous validations" do login_as commenter # Prevents posting a comment bigger than the configured character limit visit "#{seller.subdomain_with_protocol}/p/#{another_post.slug}" fill_in("Write a comment", with: "a" * 10_001) click_on("Post") wait_for_ajax expect(page).to have_alert(text: "An error occurred while posting your comment - Content is too long (maximum is 10000 characters)") end it "shows user avatars" do # Verify current user's avatar when signed in as the post author login_as seller visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" within_section "Write a comment", section_element: :section do expect(page).to have_css("img[src='#{seller.avatar_url}']") end # Verify current user's avatar when signed in as the comment author login_as commenter visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" within_section "Write a comment", section_element: :section do expect(page).to have_css("img[src='#{commenter.avatar_url}']") end # Verify avatars of comment authors create(:comment, commentable: post) visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" within_section "2 comments" do within "article:nth-child(1)" do expect(page).to have_css("img[src='#{seller.avatar_url}']") end within "article:nth-child(2)" do expect(page).to have_css("img[src='#{ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png")}']") end end end it "shows HTML-escaped comments with clickable hyperlinks in place of plaintext URLs" do login_as commenter visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" fill_in("Write a comment", with: %( That's a great article!\n\n\n\n\nVisit my website at: https://example.com\n<script type="text/html">console.log("Executing evil script...")</script> )) click_on("Post") wait_for_ajax expect(page).to have_alert(text: "Successfully posted your comment") within_section "2 comments" do within "article:nth-child(2)" do expect(find("p")[:innerHTML]).to eq %(That's a great article!\n\nVisit my website at: <a href="https://example.com" target="_blank" rel="noopener noreferrer nofollow">https://example.com</a>\n&lt;script type="text/html"&gt;console.log("Executing evil script...")&lt;/script&gt;) new_window = window_opened_by { click_link "https://example.com" } within_window new_window do expect(current_url).to eq("https://example.com/") end end end end it "paginates comments with nested replies" do another_comment = create(:comment, commentable: post, created_at: 1.minute.ago) reply1_to_comment1 = create(:comment, parent: comment1, commentable: post) reply1_to_another_comment = create(:comment, parent: another_comment, commentable: post, created_at: 1.minute.ago) reply2_to_another_comment = create(:comment, parent: another_comment, commentable: post) reply_to_another_comment_at_depth_2 = create(:comment, parent: reply1_to_another_comment, commentable: post) reply_to_another_comment_at_depth_3 = create(:comment, parent: reply_to_another_comment_at_depth_2, commentable: post) reply_to_another_comment_at_depth_4 = create(:comment, parent: reply_to_another_comment_at_depth_3, commentable: post) login_as commenter # For the testing purpose, let's have only one comment per page stub_const("PaginatedCommentsPresenter::COMMENTS_PER_PAGE", 1) visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" within_section "8 comments" do expect(page).to have_selector("article", count: 2) within all("article")[0] do expect(page).to have_text(comment1.content) within all("article")[0] do expect(page).to have_text(reply1_to_comment1.content) # Make sure that there are no more replies expect(page).to_not have_selector("article") end end click_on "Load more comments" wait_for_ajax expect(page).to have_selector("article", count: 8) within all("article")[2] do expect(page).to have_text(another_comment.content) within all("article")[0] do expect(page).to have_text(reply1_to_another_comment.content) within all("article")[0] do expect(page).to have_text(reply_to_another_comment_at_depth_2.content) within all("article")[0] do expect(page).to have_text(reply_to_another_comment_at_depth_3.content) within all("article")[0] do expect(page).to have_text(reply_to_another_comment_at_depth_4.content) # Make sure that there are no more replies expect(page).to_not have_selector("article") end end end end within all("article")[4] do expect(page).to have_text(reply2_to_another_comment.content) end end # Ensure that no more comments are remained to load more expect(page).to_not have_text("Load more comments") end end it "allows posting replies" do reply1_to_comment1 = create(:comment, parent: comment1, commentable: post) reply_to_comment1_at_depth_2 = create(:comment, parent: reply1_to_comment1, commentable: post) login_as commenter visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" within_section "3 comments" do within all("article")[0] do expect(page).to have_text(comment1.content) within all("article")[0] do expect(page).to have_text(reply1_to_comment1.content) within all("article")[0] do expect(page).to have_text(reply_to_comment1_at_depth_2.content) click_on "Reply" fill_in("Write a comment", with: "Reply at depth 3") click_on("Post") wait_for_ajax within all("article")[0] do expect(page).to have_text("Reply at depth 3") click_on "Reply" fill_in("Write a comment", with: "Reply at depth 4") click_on("Post") wait_for_ajax within all("article")[0] do expect(page).to have_text("Reply at depth 4") # Verify that there is no way to add a reply at this depth expect(page).to_not have_button "Reply" end end end end # Add another reply to the root comment click_on "Reply", match: :first fill_in("Write a comment", with: "Second reply") click_on("Post") wait_for_ajax within all("article")[4] do expect(page).to have_text("Second reply") end end end expect(page).to have_alert(text: "Successfully posted your comment") within_section "6 comments" do visit "#{seller.subdomain_with_protocol}/p/#{post.slug}" expect(page).to have_text("Reply at depth 3") expect(page).to have_text("Reply at depth 4") expect(page).to have_text("Second reply") # Delete a reply with descendant replies within all("article")[3] do select_disclosure "Open comment action menu", match: :first do click_on("Delete") end end expect(page).to have_text("Are you sure?") click_on("Confirm") wait_for_ajax end expect(page).to have_alert(text: "Successfully deleted the comment") expect(page).to_not have_text("Reply at depth 3") expect(page).to_not have_text("Reply at depth 4") expect(page).to have_text("Second reply") 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/follow_page_spec.rb
spec/requests/user/follow_page_spec.rb
# frozen_string_literal: true require("spec_helper") describe "/follow page", type: :system, js: true do before do @email = generate(:email) @creator = create(:named_user) @user = create(:user) end describe "following" do it "allows user to subscribe when logged in" do login_as(@user) expect do visit "#{@creator.subdomain_with_protocol}/follow" click_on("Subscribe") wait_for_ajax Follower.where(email: @user.email).first.confirm! end.to change { Follower.active.count }.by 1 expect(Follower.last.follower_user_id).to eq @user.id end it "doesn't allow user to subscribe to self when logged in" do login_as(@creator) visit "#{@creator.subdomain_with_protocol}/follow" fill_in("Your email address", with: @creator.email) click_on("Subscribe") expect(page).to have_alert(text: "As the creator of this profile, you can't follow yourself!") end it "allows user to subscribe when logged out" do expect do visit "#{@creator.subdomain_with_protocol}/follow" fill_in("Your email address", with: @email) click_on("Subscribe") wait_for_ajax Follower.find_by(email: @email).confirm! end.to change { Follower.active.count }.by 1 expect(Follower.last.email).to eq @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/user/settings_spec.rb
spec/requests/user/settings_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "User profile settings page", type: :system, js: true do before do @user = create(:named_user, :with_bio) time = Time.current # So that the products get created in a consistent order travel_to time @product1 = create(:product, user: @user, name: "Product 1", price_cents: 2000) travel_to time + 1 @product2 = create(:product, user: @user, name: "Product 2", price_cents: 1000) travel_to time + 2 @product3 = create(:product, user: @user, name: "Product 3", price_cents: 3000) login_as @user create(:seller_profile_products_section, seller: @user, shown_products: [@product1, @product2, @product3].map(&:id)) end describe "profile preview" do it "renders the header" do visit settings_profile_path expect(page).to have_text "Preview" expect(page).to have_link "Preview", href: root_url(host: @user.subdomain) end it "renders the profile" do visit settings_profile_path within_section "Preview", section_element: :aside do expect(page).to have_text @user.name expect(page).to have_text @user.bio end end end describe "saving profile updates" do it "normalizes input and saves the username" do visit settings_profile_path raw_username = "Katsuya 123 !@#" normalized_username = "katsuya123" within_section "Profile", section_element: :section do expect(page).to have_link(@user.subdomain, href: @user.subdomain_with_protocol) fill_in("Username", with: raw_username) new_subdomain = Subdomain.from_username(normalized_username) expect(page).to have_link(new_subdomain, href: "#{PROTOCOL}://#{new_subdomain}") end click_on("Update settings") expect(page).to have_alert(text: "Changes saved!") expect(@user.reload.username).to eq normalized_username end it "saves the name and bio" do visit settings_profile_path fill_in "Name", with: "Creator name" fill_in "Bio", with: "Creator bio" within_section "Preview", section_element: :aside do expect(page).to have_text("Creator name") expect(page).to have_text("Creator bio") end click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(@user.reload.name).to eq "Creator name" expect(@user.bio).to eq "Creator bio" end describe "logo" do def upload_logo(file) within_fieldset "Logo" do click_on "Remove" attach_file("Upload", file_fixture(file), visible: false) end end context "when the logo is valid" do it "saves the logo" do visit settings_profile_path upload_logo("test.png") within_section("Preview", section_element: :aside) do expect(page).to have_selector("img[alt='Profile Picture'][src*=cdn_url_for_blob]") end click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(@user.reload.avatar_url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{@user.avatar_variant.key}") end end it "purges the attached logo when the logo is removed" do # Purging an ActiveStorage::Blob in test environment returns Aws::S3::Errors::AccessDenied allow_any_instance_of(ActiveStorage::Blob).to receive(:purge).and_return(nil) visit settings_profile_path upload_logo("test.png") within_section("Preview", section_element: :aside) do expect(page).to have_selector("img[alt='Profile Picture'][src*=cdn_url_for_blob]") end click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(@user.reload.avatar_url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{@user.avatar_variant.key}") within_fieldset "Logo" do click_on "Remove" expect(page).to have_field("Upload", visible: false) end click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") sleep 0.5 # Since the previous Alerts takes time to disappear, checking avatar_url returns early before the api call is complete expect(@user.reload.avatar_url).to eq(ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png")) refresh expect(page).to have_selector("img[alt='Current logo'][src*='gumroad-default-avatar-5']") within_section("Preview", section_element: :aside) do expect(page).to have_selector("img[alt='Profile Picture'][src*='gumroad-default-avatar-5']") end end context "when the logo is invalid" do it "displays an error if either dimension is less than 200px" do visit settings_profile_path upload_logo("test-small.png") within_section("Preview", section_element: :aside) do expect(page).to have_selector("img[alt='Profile Picture'][src*=cdn_url_for_blob]") end click_on "Update settings" expect(page).to have_alert(text: "Please upload a profile picture that is at least 200x200px") expect(@user.reload.avatar.filename).to_not eq("smaller.png") end it "displays an error if format is unpermitted" do visit settings_profile_path upload_logo("test-svg.svg") expect(page).to have_alert(text: "Invalid file type") end end end it "rejects logo if file type is unsupported" do visit settings_profile_path within_fieldset "Logo" do click_on "Remove" attach_file("Upload", file_fixture("test-small.gif"), visible: false) end expect(page).to have_alert(text: "Invalid file type.") end it "saves the background color, highlight color, and font" do visit settings_profile_path fill_in_color(find_field("Background color"), "#facade") fill_in_color(find_field("Highlight color"), "#decade") choose "Roboto Mono" click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(@user.reload.seller_profile.highlight_color).to eq("#decade") expect(@user.seller_profile.background_color).to eq("#facade") expect(@user.seller_profile.font).to eq("Roboto Mono") end it "saves connected or disconnected Twitter account" do visit settings_profile_path expect(page).to have_button("Connect to X") OmniAuth.config.test_mode = true OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new JSON.parse(File.open("#{Rails.root}/spec/support/fixtures/twitter_omniauth.json").read) OmniAuth.config.before_callback_phase do |env| env["omniauth.params"] = { "state" => "link_twitter_account" } end click_on "Connect to X" expect(@user.reload.twitter_handle).not_to be_nil click_on "Disconnect #{@user.twitter_handle} from X" wait_for_ajax expect(@user.reload.twitter_handle).to be_nil expect(page).to have_button("Connect to X") # Reset the before_callback_phase to avoid making other X tests flaky. OmniAuth.config.before_callback_phase = nil end context "when logged user has role admin" do include_context "with switching account to user as admin for seller" do let(:seller) { @user } end it "does not show social links" do visit settings_profile_path expect(page).not_to have_text("Social links") expect(page).not_to have_link("Connect to X", href: user_twitter_omniauth_authorize_path(state: "link_twitter_account", x_auth_access_type: "read")) 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/profile_spec.rb
spec/requests/user/profile_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "User profile page", type: :system, js: true do include FillInUserProfileHelpers describe "viewing profile", :sidekiq_inline, :elasticsearch_wait_for_refresh do let(:creator) { create(:named_user) } it "formats links in the creator bio" do creator.update!(bio: "Hello!\n\nI'm Mr. Personman! I like https://www.gumroad.com/link, and my email is mister@personman.fr!") visit creator.subdomain_with_protocol within "main > header" do expect(page).to have_text "Hello!\n\nI'm Mr. Personman! I like gumroad.com/link, and my email is mister@personman.fr!" expect(page).to have_link "gumroad.com/link", href: "https://www.gumroad.com/link" expect(page).to have_link "mister@personman.fr", href: "mailto:mister@personman.fr" end end it "allows impersonating from the profile page when logged in as Gumroad admin" do admin = create(:user, is_team_member: true) sign_in admin visit "/#{creator.username}" click_on "Impersonate" expect(page).to have_current_path("/products") select_disclosure "#{creator.display_name}" do expect(page).to have_menuitem("Unbecome") click_on "Profile" end logout sleep 1 # Since logout doesn't seem to immediately invalidate the session visit "/#{creator.username}" expect(page).to_not have_text("Impersonate") expect(page).to_not have_text("Unbecome") login_as(creator) refresh expect(page).to_not have_text("Impersonate") expect(page).to_not have_text("Unbecome") end describe "viewing products" do it "displays the lowest cost variant's price for a product with variants" do recreate_model_indices(Link) section = create(:seller_profile_products_section, seller: creator) create(:seller_profile, seller: creator, json_data: { tabs: [{ name: "", sections: [section.id] }] }) product = create(:product, user: creator, price_cents: 300) category = create(:variant_category, link: product) create(:variant, variant_category: category, price_difference_cents: 300) create(:variant, variant_category: category, price_difference_cents: 150) create(:variant, variant_category: category, price_difference_cents: 200) create(:variant, variant_category: category, price_difference_cents: 50, deleted_at: 1.hour.ago) visit "/#{creator.username}" wait_for_ajax within find_product_card(product) do expect(page).to have_selector("[itemprop='price']", text: "$4.50") end end end end describe "Profile edit buttons" do let(:seller) { create(:named_user) } context "with switching account to user as admin for seller" do include_context "with switching account to user as admin for seller" it "doesn't show the profile edit buttons on logged-in user's profile" do create(:seller_profile_products_section, seller:) visit user_with_role_for_seller.subdomain_with_protocol expect(page).not_to have_link("Edit profile") expect(page).not_to have_disclosure("Edit section") expect(page).not_to have_button("Page settings") end end context "without user logged in" do it "doesn't show the profile edit button" do create(:seller_profile_products_section, seller:) visit seller.subdomain_with_protocol expect(page).not_to have_link("Edit profile") expect(page).not_to have_disclosure("Edit section") expect(page).not_to have_button("Page settings") end end end describe "Tabs and Profile sections" do let(:seller) { create(:named_user, :eligible_for_service_products) } before do time = Time.current # So that the products get created in a consistent order @product1 = create(:product, user: seller, name: "Product 1", price_cents: 2000, created_at: time) @product2 = create(:product, user: seller, name: "Product 2", price_cents: 1000, created_at: time + 1) @product3 = create(:product, user: seller, name: "Product 3", price_cents: 3000, created_at: time + 2) @product4 = create(:product, user: seller, name: "Product 4", price_cents: 3000, created_at: time + 3) end context "without user logged in" do it "displays sections correctly", :elasticsearch_wait_for_refresh do create(:seller_profile_products_section, seller:, header: "Section 1", product: @product1) create(:seller_profile_products_section, seller:, header: "Section 1", shown_products: [@product1.id, @product2.id, @product3.id, @product4.id]) create(:seller_profile_products_section, seller:, header: "Section 2", shown_products: [@product1.id, @product4.id], default_product_sort: ProductSortKey::PRICE_DESCENDING) create(:published_installment, seller:, shown_on_profile: true) posts = create_list(:audience_installment, 2, published_at: Date.yesterday, seller:, shown_on_profile: true) create(:seller_profile_posts_section, seller:, header: "Section 3", shown_posts: posts.pluck(:id)) create(:seller_profile_rich_text_section, seller:, header: "Section 4", text: { type: "doc", content: [{ type: "heading", attrs: { level: 2 }, content: [{ type: "text", text: "Heading" }] }, { type: "paragraph", content: [{ type: "text", text: "Some more text" }] }] }) create(:seller_profile_subscribe_section, seller:, header: "Section 5") create(:seller_profile_featured_product_section, seller:, header: "Section 6", featured_product_id: @product1.id) section = create(:seller_profile_featured_product_section, seller:, header: "Section 7", featured_product_id: create(:membership_product_with_preset_tiered_pricing, user: seller).id) create(:seller_profile, seller:, json_data: { tabs: [{ name: "Tab", sections: ([section] + seller.seller_profile_sections.to_a[...-1]).pluck(:id) }] }) visit seller.subdomain_with_protocol within_section "Section 1", section_element: :section do expect_product_cards_in_order([@product1, @product2, @product3, @product4]) end within_section "Section 2", section_element: :section do expect_product_cards_in_order([@product4, @product1]) end within_section "Section 3", section_element: :section do expect(page).to have_link(count: 2) posts.each { expect(page).to have_link(_1.name, href: "/p/#{_1.slug}") } end within_section "Section 4", section_element: :section do expect(page).to have_selector("h2", text: "Heading") expect(page).to have_text("Some more text") end within_section "Section 5", section_element: :section do fill_in "Your email address", with: "subscriber@gumroad.com" click_on "Subscribe" end expect(page).to have_alert(text: "Check your inbox to confirm your follow request.") expect(page).to_not have_text "Subscribe to receive email updates from #{seller.name}" within_section "Section 6", section_element: :section do expect(page).to have_section("Product 1", section_element: :article) end within find("main > section:first-of-type", text: "Section 7") do expect(page).to have_text "$3 a month" expect(page).to have_text "$5 a month" end end it "shows the subscribe block when there are no sections" do visit seller.subdomain_with_protocol expect(page).to_not have_selector "main > header" expect(page).to have_text "Subscribe to receive email updates from #{seller.name}" submit_follow_form(with: "hello@example.com") wait_for_ajax expect(Follower.last.email).to eq "hello@example.com" seller.update!(bio: "Hello!") visit seller.subdomain_with_protocol expect(page).to have_selector "main > header" end end context "with seller logged in" do before do login_as seller end def add_section(type) all(:disclosure, "Add section").last.select_disclosure do click_on type end sleep 1 all(:disclosure, "Edit section").last.select_disclosure do click_on "Name" fill_in "Name", with: "New section" end end def save_changes toggle_disclosure "Edit section" sleep 1 wait_for_ajax end it "shows the subscribe block when there are no sections" do visit seller.subdomain_with_protocol expect(page).to have_link("Edit profile") expect(page).to have_text "Subscribe to receive email updates from #{seller.name}" submit_follow_form(with: "hello@example.com") expect(page).to have_alert(text: "As the creator of this profile, you can't follow yourself!") add_section "Products" expect(page).to_not have_text "Subscribe to receive email updates from #{seller.name}" wait_for_ajax expect(seller.seller_profile_sections.count).to eq 1 seller.update!(bio: "Hello!") visit seller.subdomain_with_protocol end it "allows adding and deleting sections" do section = create(:seller_profile_products_section, seller:, header: "Section 1", shown_products: [@product1.id, @product2.id, @product3.id, @product4.id]) create(:seller_profile, seller:, json_data: { tabs: [{ name: "", sections: [section.id] }] }) visit seller.subdomain_with_protocol expect(page).to have_link("Edit profile") select_disclosure "Edit section" do click_on "Name" fill_in "Name", with: "New name" uncheck "Display above section" end save_changes expect(page).to_not have_section "Section 1" expect(page).to_not have_section "New name" expect(section.reload.header).to eq "New name" expect(section.hide_header?).to eq true select_disclosure "Edit section" do click_on "Name" check "Display above section" end expect(page).to have_section "New name" save_changes expect(section.reload.hide_header?).to eq false add_section "Products" expect(page).to have_disclosure("Edit section", count: 2) within_section "New name", section_element: :section do select_disclosure "Edit section" do click_on "Remove" end end sleep 1 wait_for_ajax expect(page).to have_disclosure("Edit section", count: 1) expect(page).to_not have_section "New name" expect(seller.seller_profile_sections.reload.sole).to_not eq section end it "allows copying the link to a section" do section = create(:seller_profile_products_section, seller:) section2 = create(:seller_profile_posts_section, seller:) create(:seller_profile, seller:, json_data: { tabs: [{ name: "Tab 1", sections: [section.id] }, { name: "Tab 2", sections: [section2.id] }] }) visit "#{seller.subdomain_with_protocol}/?section=#{section2.external_id}" expect(page).to have_tab_button "Tab 2", open: true select_disclosure "Edit section" do # This currently cannot be tested properly as `navigator.clipboard` is `undefined` in Selenium. # Attempting to use `Browser.grantPermissions` like in Flexile throws an error saying "Permissions can't be granted in current context." expect(page).to have_button "Copy link" end end it "saves tab settings" do published_audience_installment = create(:audience_installment, seller:, shown_on_profile: true, published_at: 1.day.ago, name: "Published audience post") unpublished_audience_installment = create(:audience_installment, seller:, shown_on_profile: true) published_follower_installment = create(:follower_installment, seller:, shown_on_profile: true, published_at: 1.day.ago) visit seller.subdomain_with_protocol expect(page).to_not have_tab_button select_disclosure "Page settings" do click_on "Pages" click_on "New page" set_rich_text_editor_input(find("[aria-label='Page name']"), to_text: "Hi! I'm page!") click_on "New page" click_on "New page" items = all("[role=list][aria-label=Pages] [role=listitem]") expect(items.count).to eq 3 items[0].find("[aria-grabbed]").drag_to items[2], delay: 0.1 within items[1] do click_on "Remove page" click_on "No, cancel" click_on "Remove page" click_on "Yes, delete" end expect(page).to have_selector("[role=list][aria-label=Pages] [role=listitem]", count: 2) end toggle_disclosure "Page settings" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(page).to have_tab_button(count: 2) expect(page).to have_tab_button "Hi! I'm page!", open: true expect(page).to have_tab_button "New page" expect(seller.reload.seller_profile.json_data["tabs"]).to eq([{ name: "New page", sections: [] }, { name: "Hi! I'm page!", sections: [] }].as_json) add_section "Products" add_section "Products" select_disclosure "Add section", match: :first do click_on "Posts" end expect(page).to have_disclosure("Edit section", count: 3) all(:disclosure_button, "Edit section")[1].click click_on "Remove" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") select_tab "New page" add_section "Posts" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(page).to have_link(published_audience_installment.name) expect(page).to_not have_link(unpublished_audience_installment.name) expect(page).to_not have_link(published_follower_installment.name) expect(seller.seller_profile_sections.count).to eq 3 expect(seller.seller_profile.reload.json_data["tabs"]).to eq([ { name: "New page", sections: [seller.seller_profile_posts_sections.last.id] }, { name: "Hi! I'm page!", sections: [seller.seller_profile_posts_sections.first.id, seller.seller_profile_products_sections.sole.id] }, ].as_json) expect(seller.seller_profile_posts_sections[0].shown_posts).to eq [published_audience_installment.id] end it "allows reordering sections" do def expect_sections_in_order(*names) names.each_with_index { |name, index| expect(page).to have_selector("section:nth-of-type(#{index + 1}) h2", text: name) } end section1 = create(:seller_profile_products_section, seller:, header: "Section 1") section2 = create(:seller_profile_products_section, seller:, header: "Section 2") section3 = create(:seller_profile_products_section, seller:, header: "Section 3") create(:seller_profile, seller:, json_data: { tabs: [{ name: "", sections: [section1, section2, section3].pluck(:id) }] }) visit seller.subdomain_with_protocol expect_sections_in_order("Section 1", "Section 2", "Section 3") within_section "Section 1", section_element: :section do expect(page).to have_button "Move section up", disabled: true click_on "Move section down" end expect_sections_in_order("Section 2", "Section 1", "Section 3") add_section "Posts" expect_sections_in_order("Section 2", "Section 1", "Section 3", "New section") within_section "New section", section_element: :section do toggle_disclosure "Edit section" expect(page).to have_button "Move section down", disabled: true click_on "Move section up" end expect_sections_in_order("Section 2", "Section 1", "New section", "Section 3") wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(seller.seller_profile_sections.count).to eq 4 expect(seller.seller_profile.reload.json_data["tabs"]).to eq([ { name: "", sections: [section2, section1, seller.seller_profile_posts_sections.sole, section3].pluck(:id) }, ].as_json) end it "allows creating products sections" do visit seller.subdomain_with_protocol add_section "Products" click_on "Go back" click_on "Products" expect(page).to have_checked_field "Add new products by default" expect(page).to have_unchecked_field "Show product filters" expect(page).not_to have_selector("[aria-label='Filters']") [@product1, @product2, @product3, @product4].each { check _1.name } expect_product_cards_in_order([@product1, @product2, @product3, @product4]) drag_product_row(@product1, to: @product2) expect_product_cards_in_order([@product2, @product1, @product3, @product4]) drag_product_row(@product3, to: @product2) uncheck @product2.name expect_product_cards_in_order([@product3, @product1, @product4]) expect(page).to have_select("Default sort order", options: ["Custom", "Newest", "Highest rated", "Most reviewed", "Price (Low to High)", "Price (High to Low)"], selected: "Custom") select "Price (Low to High)", from: "Default sort order" expect_product_cards_in_order([@product1, @product4, @product3]) save_changes section = seller.seller_profile_products_sections.reload.sole expect(section).to have_attributes(show_filters: false, add_new_products: true, default_product_sort: "price_asc", shown_products: [@product3.id, @product1.id, @product4.id]) select_disclosure "Edit section" do click_on "Products" check "Show product filters" uncheck "Add new products by default" end save_changes expect(page).to have_selector("[aria-label='Filters']") expect(section.reload).to have_attributes(show_filters: true, add_new_products: false) refresh expect_product_cards_in_order([@product1, @product4, @product3]) end it "allows creating posts sections" do create(:published_installment, seller:) posts = create_list(:audience_installment, 2, published_at: Date.yesterday, seller:, shown_on_profile: true) visit seller.subdomain_with_protocol add_section "Posts" save_changes within_section "New section" do expect(page).to have_link(count: 2) posts.each { expect(page).to have_link(_1.name, href: "/p/#{_1.slug}") } end expect(seller.seller_profile_posts_sections.reload.sole).to have_attributes(header: "New section", shown_posts: posts.pluck(:id)) refresh within_section "New section" do expect(page).to have_link(count: 2) posts.each { expect(page).to have_link(_1.name, href: "/p/#{_1.slug}") } end end it "allows creating rich text sections" do visit seller.subdomain_with_protocol add_section "Rich text" save_changes within_section "New section" do editor = find("[contenteditable=true]") editor.click select_disclosure "Text formats" do choose "Title" end editor.send_keys "Heading\nSome more text" attach_file(file_fixture("test.jpg")) do click_on "Insert image" end end wait_for_ajax toggle_disclosure "Edit section" # unfocus editor wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(page).to_not have_alert section = seller.seller_profile_rich_text_sections.sole Selenium::WebDriver::Wait.new(timeout: 10).until { section.reload.text["content"].map { _1["type"] }.include?("image") } image_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{ActiveStorage::Blob.last.key}" expected_rich_text = { type: "doc", content: [ { type: "heading", attrs: { level: 2 }, content: [{ type: "text", text: "Heading" }] }, { type: "paragraph", content: [{ type: "text", text: "Some more text" }] }, { type: "image", attrs: { src: image_url, link: nil } } ] }.as_json expect(section).to have_attributes(header: "New section", text: expected_rich_text) refresh within_section "New section" do expect(page).to have_selector("h2", text: "Heading") expect(page).to have_text("Some more text") expect(page).to have_image(src: image_url) end end it "allows creating subscribe sections" do visit seller.subdomain_with_protocol all(:disclosure, "Add section").last.select_disclosure do click_on "Subscribe" end within_section "Subscribe to receive email updates from Gumbot." do expect(page).to have_field("Your email address") expect(page).to have_button("Subscribe") end wait_for_ajax new_section = seller.seller_profile_sections.sole expect(new_section).to have_attributes(header: "Subscribe to receive email updates from Gumbot.", button_label: "Subscribe") select_disclosure "Edit section" do click_on "Name" fill_in "Name", with: "Subscribe now or else" click_on "Go back" click_on "Button Label" fill_in "Button Label", with: "Follow" end save_changes within_section "Subscribe now or else" do expect(page).to have_field("Your email address") expect(page).to have_button("Follow") end expect(new_section.reload).to have_attributes(header: "Subscribe now or else", button_label: "Follow") end it "allows creating featured product sections" do visit seller.subdomain_with_protocol add_section "Featured Product" expect(page).to have_alert(text: "Changes saved!") section = seller.seller_profile_sections.sole expect(section).to be_a SellerProfileFeaturedProductSection expect(section.featured_product_id).to be_nil within_disclosure "Edit section" do fill_in "Name", with: "My featured product" end save_changes expect(section.reload).to have_attributes(header: "My featured product", featured_product_id: nil) select_disclosure "Edit section" do click_on "Featured Product" select_combo_box_option search: "Product 2", from: "Featured Product" end within_section "My featured product" do expect(page).to have_section "Product 2", section_element: :article end save_changes expect(section.reload).to have_attributes(header: "My featured product", featured_product_id: @product2.id) select_disclosure "Edit section" do click_on "Featured Product" select_combo_box_option search: "Product 3", from: "Featured Product" end within_section "My featured product" do expect(page).to have_section "Product 3", section_element: :article end save_changes expect(section.reload).to have_attributes(header: "My featured product", featured_product_id: @product3.id) end it "allows creating coffee featured product sections" do coffee_product = create(:coffee_product, user: seller, name: "Buy me a coffee", description: "I need caffeine!") visit seller.subdomain_with_protocol add_section "Featured Product" expect(page).to have_alert(text: "Changes saved!") section = seller.seller_profile_sections.sole expect(section).to be_a SellerProfileFeaturedProductSection expect(section.featured_product_id).to be_nil within_disclosure "Edit section" do fill_in "Name", with: "My featured product" end save_changes expect(section.reload).to have_attributes(header: "My featured product", featured_product_id: nil) select_disclosure "Edit section" do click_on "Featured Product" select_combo_box_option search: "Buy me a coffee", from: "Featured Product" end within_section "My featured product" do expect(page).to_not have_section "Buy me a coffee", section_element: :article expect(page).to have_section "Buy me a coffee", section_element: :section expect(page).to have_selector("h1", text: "Buy me a coffee") expect(page).to have_selector("h3", text: "I need caffeine!") end save_changes expect(section.reload).to have_attributes(header: "My featured product", featured_product_id: coffee_product.id) end it "allows creating wishlists sections" do wishlists = [ create(:wishlist, name: "First Wishlist", user: seller), create(:wishlist, name: "Second Wishlist", user: seller), ] visit seller.subdomain_with_protocol add_section "Wishlists" save_changes expect(page).to have_text("No wishlists selected") section = seller.seller_profile_sections.sole expect(section).to be_a SellerProfileWishlistsSection expect(section.shown_wishlists).to eq([]) select_disclosure "Edit section" do click_on "Wishlists" end wishlists.each { check _1.name } expect_product_cards_in_order(wishlists) drag_product_row(wishlists.first, to: wishlists.second) expect_product_cards_in_order(wishlists.reverse) save_changes expect(section.reload.shown_wishlists).to eq(wishlists.reverse.map(&:id)) refresh expect_product_cards_in_order(wishlists.reverse) click_link "First Wishlist" expect(page).to have_button("Copy link") expect(page).to have_text("First Wishlist") expect(page).to have_text(seller.name) expect(page).to have_button("Subscribe") 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/follow_spec.rb
spec/requests/user/follow_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "User Follow Page Scenario", type: :system, js: true do include FillInUserProfileHelpers let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:other_user) { create(:user) } let(:follower_email) { generate(:email) } it "allows user to follow when logged in" do login_as(other_user) expect do visit seller.subdomain_with_protocol submit_follow_form wait_for_ajax Follower.where(email: other_user.email).first.confirm! expect(page).to have_button("Subscribed", disabled: true) end.to change { seller.followers.active.count }.by(1) expect(Follower.last.follower_user_id).to eq other_user.id end context "with seller as logged_in_user" do before do login_as(seller) end it "doesn't prefill the email" do visit seller.subdomain_with_protocol expect(find("input[type='email']").value).to be_empty end context "with switching account to user as admin for seller" do include_context "with switching account to user as admin for seller" it "doesn't allow to follow logged-in user's profile" do visit user_with_role_for_seller.subdomain_with_protocol expect(find("input[type='email']").value).to be_empty submit_follow_form(with: user_with_role_for_seller.email) expect(page).to have_alert(text: "As the creator of this profile, you can't follow yourself!") end end end context "without user logged in" do it "allows user to follow" do visit seller.subdomain_with_protocol expect do submit_follow_form(with: follower_email) wait_for_ajax Follower.find_by(email: follower_email).confirm! end.to change { seller.followers.active.count }.by(1) expect(Follower.last.email).to eq follower_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/user/disable_affiliate_requests_setting_spec.rb
spec/requests/user/disable_affiliate_requests_setting_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Disable affiliate requests setting", type: :system, js: true do let(:user) { create(:named_user) } before do login_as(user) end it "allows user to toggle the prevent being added as affiliate setting" do visit settings_main_path within_section "Affiliates", section_element: :section do expect(page).to have_text("Prevent others from adding me as an affiliate") expect(page).to have_text("When enabled, other users cannot add you as an affiliate or request to become your affiliate.") expect(page).to have_field("Prevent others from adding me as an affiliate", checked: false) check "Prevent others from adding me as an affiliate" end click_on "Update settings" wait_for_ajax expect(page).to have_alert(text: "Your account has been updated!") expect(user.reload.disable_affiliate_requests?).to eq(true) refresh within_section "Affiliates", section_element: :section do expect(page).to have_field("Prevent others from adding me as an affiliate", checked: true) end within_section "Affiliates", section_element: :section do uncheck "Prevent others from adding me as an affiliate" end click_on "Update settings" wait_for_ajax expect(page).to have_alert(text: "Your account has been updated!") expect(user.reload.disable_affiliate_requests?).to eq(false) end it "shows the affiliates section in the settings page" do visit settings_main_path expect(page).to have_section("Affiliates") within_section "Affiliates", section_element: :section do expect(page).to have_text("Prevent others from adding me as an affiliate") expect(page).to have_text("When enabled, other users cannot add you as an affiliate or request to become your affiliate.") 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/gallery_spec.rb
spec/requests/user/gallery_spec.rb
# frozen_string_literal: true require("spec_helper") describe "User Gallery Page Scenario", :elasticsearch_wait_for_refresh, type: :system, js: true do describe "Product thumbnails", :sidekiq_inline do before do @creator = create(:user, username: "creatorgal") section = create(:seller_profile_products_section, seller: @creator) create(:seller_profile, seller: @creator, json_data: { tabs: [{ name: "", sections: [section.id] }] }) create(:product, user: @creator) @product_with_previews = create(:product, user: @creator, name: "Product with previews") create(:asset_preview, link: @product_with_previews, url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ") create(:asset_preview, link: @product_with_previews) create(:product_review, purchase: create(:purchase, link: @product_with_previews), rating: 3) create(:product_review, purchase: create(:purchase, link: @product_with_previews), rating: 4) create(:thumbnail, product: @product_with_previews) @product_with_previews.reload Link.import(refresh: true, force: true) end it "displays product thumbnail instead of previews" do visit("/creatorgal") within find_product_card(@product_with_previews) do expect(find("figure")).to have_image(src: @product_with_previews.thumbnail.url) end end end describe "Product previews", :sidekiq_inline do before do @creator = create(:user, username: "creatorgal") section = create(:seller_profile_products_section, seller: @creator) create(:seller_profile, seller: @creator, json_data: { tabs: [{ name: "", sections: [section.id] }] }) create(:product, user: @creator) @product_with_previews = create(:product, user: @creator, name: "Product with previews") create(:asset_preview, link: @product_with_previews, url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ", attach: false) create(:asset_preview, link: @product_with_previews) create(:product_review, purchase: create(:purchase, link: @product_with_previews), rating: 3) create(:product_review, purchase: create(:purchase, link: @product_with_previews), rating: 4) Link.import(refresh: true, force: true) end it "uses the first image cover as the preview" do visit("/creatorgal") within find_product_card(@product_with_previews) do expect(find("figure")).to have_image(src: @product_with_previews.asset_previews.last.url) end end it "displays average rating with reviews count if product reviews are enabled" do visit("/creatorgal") within find_product_card(@product_with_previews) do within("[aria-label=Rating]") do expect(page).to have_content("3.5 (2)", normalize_ws: true) end end @product_with_previews.display_product_reviews = false @product_with_previews.save! visit "/creatorgal" within find_product_card(@product_with_previews) do expect(page).not_to have_selector("[aria-label=Rating]") end end end describe "product share_url" do before do @user = create(:named_user) section = create(:seller_profile_products_section, seller: @user) create(:seller_profile, seller: @user, json_data: { tabs: [{ name: "", sections: [section.id] }] }) @product = create(:product, user: @user) end it "contains link to individual product page with long_url" do stub_const("DOMAIN", "127.0.0.1") stub_const("SHORT_DOMAIN", "test.gum.co") visit "/#{@user.username}" # Custom domain pages will have share URLs with the custom domain. Since subdomain profile page works # the same way as custom domain, it will have share URL with subdomain of the creator. share_url = "#{@user.subdomain_with_protocol}/l/#{@product.unique_permalink}?layout=profile" expect(page).to have_link(@product.name, href: share_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/user/affiliate_request_form_spec.rb
spec/requests/user/affiliate_request_form_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Public affiliate request onboarding form", type: :system, js: true do let(:creator) { create(:named_user) } let!(:product) { create(:product, user: creator) } let!(:enabled_self_service_affiliate_product) { create(:self_service_affiliate_product, enabled: true, seller: creator, product:) } context "when the requester is not signed in" do it "allows requester to submit a request to become an affiliate of the creator" do visit new_affiliate_request_path(username: creator.username) expect(page).to have_text("Become an affiliate for #{creator.display_name}") expect(page).to have_text("Applying to be an affiliate is easy. Fill out the form below and let #{creator.display_name} know how you'll be promoting their products.") expect(page).to have_text("To help speed up your approval, include things like social urls, audience size, audience engagement, etc...") # Ensure form validations work click_on("Submit affiliate request") expect(page).to have_alert(text: "Name can't be blank") # Request submission status message when the requester already has an account create(:user, email: "jane@example.com") fill_in("Name", with: "Jane Doe") fill_in("Email", with: "jane@example.com") fill_in("How do you intend to promote their products? How big is your audience?", with: "Hello!") click_on("Submit affiliate request") expect(page).to have_text("Your request has been submitted! We will send you an email notification when you are approved.") expect(page).to_not have_text("In the meantime, create your Gumroad account using email jane@example.com and confirm it. You'll receive your affiliate links once your Gumroad account is active.") expect(AffiliateRequest.last.attributes.with_indifferent_access).to include(name: "Jane Doe", email: "jane@example.com", promotion_text: "Hello!", seller_id: creator.id) # Request submission status message when the requester does not have an account visit new_affiliate_request_path(username: creator.username) fill_in("Name", with: "John Doe") fill_in("Email", with: "john@example.com") fill_in("How do you intend to promote their products? How big is your audience?", with: "Hello!") click_on("Submit affiliate request") expect(page).to have_text("Your request has been submitted! We will send you an email notification when you are approved.") expect(page).to have_text("In the meantime, create your Gumroad account using email john@example.com and confirm it. You'll receive your affiliate links once your Gumroad account is active.") expect(AffiliateRequest.last.attributes.with_indifferent_access).to include(name: "John Doe", email: "john@example.com", promotion_text: "Hello!", seller_id: creator.id) # Try submitting yet another request to the same creator using same email address visit new_affiliate_request_path(username: creator.username) fill_in("Name", with: "JD") fill_in("Email", with: "john@example.com") fill_in("How do you intend to promote their products? How big is your audience?", with: "Howdy!") click_on("Submit affiliate request") expect(page).to have_alert(text: "You have already requested to become an affiliate of this creator.") expect(page).to_not have_text("Your request has been submitted!") end end context "when the requester is signed in" do let(:seller) { create(:named_user) } let(:requester) { create(:named_user) } context "when requester has not completed onboarding" do before do requester.update!(name: nil, username: nil) end context "with other seller as current_seller" do include_context "with switching account to user as admin for seller" let(:requester) { user_with_role_for_seller } it "it submits form and saves name to requester's profile" do visit custom_domain_new_affiliate_request_url(host: creator.subdomain_with_protocol) fill_in("Name", with: "Jane Doe") fill_in("How do you intend to promote their products? How big is your audience?", with: "Hello!") click_on("Submit affiliate request") expect(page).to have_text("Your request has been submitted! We will send you an email notification when you are approved.") expect(AffiliateRequest.last.attributes.with_indifferent_access).to include(name: "Jane Doe", email: requester.email, promotion_text: "Hello!", seller_id: creator.id) expect(user_with_role_for_seller.reload.name).to eq("Jane Doe") end end end it "allows requester to submit a request to become an affiliate of the creator without needing to enter identification details" do login_as(requester) visit custom_domain_new_affiliate_request_url(host: creator.subdomain_with_protocol) # Ensure form validations work click_on("Submit affiliate request") expect(page).to have_alert(text: "Promotion text can't be blank") # Request submission status message fill_in("How do you intend to promote their products? How big is your audience?", with: "Hello!") click_on("Submit affiliate request") expect(page).to have_text("Your request has been submitted! We will send you an email notification when you are approved.") expect(AffiliateRequest.last.attributes.with_indifferent_access).to include(name: requester.name, email: requester.email, promotion_text: "Hello!", seller_id: creator.id) 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/product_panel/scroll_pagination_spec.rb
spec/requests/user/product_panel/scroll_pagination_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Product panel on creator profile - infinite scroll pagination", type: :system, js: true) do before do @creator = create(:named_user) purchaser_email = "one@gr.test" @preview_image_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/kFDzu.png" @a = create(:product_with_files, user: @creator, name: "Digital Product A", created_at: 20.minutes.ago, preview_url: @preview_image_url) @a.tag!("Audio") create(:price, link: @a, price_cents: 300) @b = create(:product, user: @creator, name: "Physical Product B", created_at: 19.minutes.ago) @b.tag!("Video") @b.tag!("Book") create(:price, link: @b, price_cents: 200) purchase_b1 = create(:purchase, link: @b, email: purchaser_email) create(:product_review, purchase: purchase_b1, rating: 4) purchase_b2 = create(:purchase, link: @b, email: purchaser_email) create(:product_review, purchase: purchase_b2, rating: 1) @c = create(:product, user: @creator, name: "Digital Subscription C", created_at: 18.minutes.ago) @c.tag!("Book") create(:price, link: @c, price_cents: 400) purchase_c1 = create(:purchase, link: @c, email: purchaser_email) create(:product_review, purchase: purchase_c1, rating: 3) purchase_c2 = create(:purchase, link: @c, email: purchaser_email) create(:product_review, purchase: purchase_c2, rating: 3) @d = create(:product, user: @creator, name: "Physical Subscription D", created_at: 17.minutes.ago) @d.tag!("Audio") create(:price, link: @d, price_cents: 100) @e = create(:product, user: @creator, name: "Digital Preorder E", created_at: 16.minutes.ago) @e.tag!("Audio") create(:price, link: @e, price_cents: 500) @hideme = create(:product_with_files, user: @creator, name: "Hidden") @f = create(:product, user: @creator, name: "Digital Product F", price_cents: 110, created_at: 15.minutes.ago) purchase_f = create(:purchase, link: @f, email: purchaser_email) create(:product_review, purchase: purchase_f, rating: 2) @g = create(:product, user: @creator, name: "Digital Product G", price_cents: 120, created_at: 14.minutes.ago, display_product_reviews: false) purchase_g = create(:purchase, link: @g, email: purchaser_email) create(:product_review, purchase: purchase_g, rating: 2) @h = create(:product, user: @creator, name: "Digital Product H", price_cents: 130, created_at: 13.minutes.ago) purchase_h = create(:purchase, link: @h, email: purchaser_email) create(:product_review, purchase: purchase_h, rating: 1) @i = create(:product, user: @creator, name: "Digital Product I", price_cents: 140, created_at: 12.minutes.ago) @j = create(:product, user: @creator, name: "Digital Product J", price_cents: 150, created_at: 11.minutes.ago) @creator.save! Link.import(refresh: true, force: true) end describe "infinite scroll pagination" do before do 28.times do |count| create(:product, user: @creator, name: "product #{count + 1}", price_cents: (100 + count) * 100) end section = create(:seller_profile_products_section, seller: @creator, shown_products: (@creator.products - [@hideme]).pluck(:id), show_filters: true) create(:seller_profile, seller: @creator, json_data: { tabs: [{ name: "Products", sections: [section.id] }] }) Link.import(refresh: true, force: true) end it "allows other users to be able to load results" do visit "/#{@creator.username}?sort=price_asc" wait_for_ajax expect(page).to have_product_card(count: 9) expect(page).to have_product_card(@a) expect(page).to have_product_card(@c) expect(page).to_not have_product_card(text: "product 7") first("main").scroll_to :bottom wait_for_ajax expect(page).to have_product_card(count: 18) expect(page).to have_text("1-18 of 38") expect(page).to have_product_card(text: "product 7") expect(page).to have_product_card(text: "product 8") expect(page).to_not have_product_card(text: "product 13") first("main").scroll_to :bottom wait_for_ajax expect(page).to have_product_card(count: 27) expect(page).to have_text("1-27 of 38") expect(page).to have_product_card(text: "product 13") expect(page).to have_product_card(text: "product 14") expect(page).to_not have_product_card(text: "product 20") first("main").scroll_to :bottom wait_for_ajax expect(page).to have_product_card(count: 36) expect(page).to have_text("1-36 of 38") expect(page).to have_product_card(text: "product 20") expect(page).to have_product_card(text: "product 21") expect(page).to_not have_product_card(text: "product 27") expect(page).to have_product_card(count: 36) first("main").scroll_to :bottom wait_for_ajax expect(page).to have_product_card(count: 38) expect(page).to have_text("1-38 of 38") expect(page).to have_product_card(text: "product 27") expect(page).to have_product_card(text: "product 28") expect(page).to have_product_card(count: 38) first("main").scroll_to :bottom wait_for_ajax expect(page).to have_product_card(count: 38) expect(page).to have_text("1-38 of 38") 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/product_panel/product_panel_spec.rb
spec/requests/user/product_panel/product_panel_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Product panel on creator profile", type: :system, js: true) do before do @creator = create(:named_user) purchaser_email = "one@gr.test" @preview_image_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/kFDzu.png" @a = create(:product_with_files, user: @creator, name: "Digital Product A", created_at: 20.minutes.ago, preview_url: @preview_image_url) @a.tag!("Audio") create(:price, link: @a, price_cents: 300) @b = create(:product, user: @creator, name: "Physical Product B", created_at: 19.minutes.ago) @b.tag!("Video") @b.tag!("Book") create(:price, link: @b, price_cents: 200) purchase_b1 = create(:purchase, link: @b, email: purchaser_email) create(:product_review, purchase: purchase_b1, rating: 4) purchase_b2 = create(:purchase, link: @b, email: purchaser_email) create(:product_review, purchase: purchase_b2, rating: 1) @c = create(:product, user: @creator, name: "Digital Subscription C", created_at: 18.minutes.ago) @c.tag!("Book") create(:price, link: @c, price_cents: 400) purchase_c1 = create(:purchase, link: @c, email: purchaser_email) create(:product_review, purchase: purchase_c1, rating: 3) purchase_c2 = create(:purchase, link: @c, email: purchaser_email) create(:product_review, purchase: purchase_c2, rating: 3) @d = create(:product, user: @creator, name: "Physical Subscription D", created_at: 17.minutes.ago) @d.tag!("Audio") create(:price, link: @d, price_cents: 100) @e = create(:product, user: @creator, name: "Digital Preorder E", created_at: 16.minutes.ago) @e.tag!("Audio") create(:price, link: @e, price_cents: 500) @hideme = create(:product_with_files, user: @creator, name: "Hidden") @f = create(:product, user: @creator, name: "Digital Product F", price_cents: 110, created_at: 15.minutes.ago) purchase_f = create(:purchase, link: @f, email: purchaser_email) create(:product_review, purchase: purchase_f, rating: 2) @g = create(:product, user: @creator, name: "Digital Product G", price_cents: 120, created_at: 14.minutes.ago, display_product_reviews: false) purchase_g = create(:purchase, link: @g, email: purchaser_email) create(:product_review, purchase: purchase_g, rating: 2) @h = create(:product, user: @creator, name: "Digital Product H", price_cents: 130, created_at: 13.minutes.ago) purchase_h = create(:purchase, link: @h, email: purchaser_email) create(:product_review, purchase: purchase_h, rating: 1) @i = create(:product, user: @creator, name: "Digital Product I", price_cents: 140, created_at: 12.minutes.ago) @j = create(:product, user: @creator, name: "Digital Product J", price_cents: 150, created_at: 11.minutes.ago) section = create(:seller_profile_products_section, seller: @creator, shown_products: [@a, @b, @c, @d, @e, @f, @g, @h, @i, @j].map { _1.id }, show_filters: true) create(:seller_profile, seller: @creator, json_data: { tabs: [{ name: "Products", sections: [section.id] }] }) Link.import(refresh: true, force: true) end it "shows a product's asset preview if set" do login_as(@creator) visit("/#{@creator.username}") expect(page.first("article figure img")[:src]).to match(PUBLIC_STORAGE_S3_BUCKET) login_as(create(:user)) visit("/#{@creator.username}") expect(page.first("article figure img")[:src]).to match(PUBLIC_STORAGE_S3_BUCKET) end it "only shows products that have been selected to be shown" do login_as(create(:user)) visit("/#{@creator.username}") expect_product_cards_in_order([@a, @b, @c, @d, @e, @f, @g, @h, @i]) expect(page).to_not have_product_card(@hideme) end it "shows sold out banner on product card when max_purchase_count has been reached" do @a.max_purchase_count = 3 @a.save! 3.times { create(:purchase, link: @a) } login_as(create(:user)) visit("/#{@creator.username}") expect(find_product_card(@a)).to have_text("0 left") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/user/product_panel/product_panel_sort_filter_spec.rb
spec/requests/user/product_panel/product_panel_sort_filter_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Product panel on creator profile - Sort/Filter", type: :system, js: true) do before do @creator = create(:named_user) purchaser_email = "one@gr.test" @preview_image_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/kFDzu.png" @a = create(:product_with_files, user: @creator, name: "Digital Product A", price_cents: 300, created_at: 20.minutes.ago, preview_url: @preview_image_url) @a.tag!("Audio") @b = create(:product, user: @creator, name: "Physical Product B", price_cents: 200, created_at: 19.minutes.ago) @b.tag!("Video") @b.tag!("Book") purchase_b1 = create(:purchase, link: @b, email: purchaser_email) create(:product_review, purchase: purchase_b1, rating: 4) purchase_b2 = create(:purchase, link: @b, email: purchaser_email) create(:product_review, purchase: purchase_b2, rating: 1) @c = create(:product, user: @creator, name: "Digital Subscription C", price_cents: 400, created_at: 18.minutes.ago) @c.tag!("Book") purchase_c1 = create(:purchase, link: @c, email: purchaser_email) create(:product_review, purchase: purchase_c1, rating: 3) purchase_c2 = create(:purchase, link: @c, email: purchaser_email) create(:product_review, purchase: purchase_c2, rating: 3) recurrence_price_values_d = [ { BasePrice::Recurrence::MONTHLY => { enabled: true, price: 1 } }, { BasePrice::Recurrence::MONTHLY => { enabled: true, price: 1.5 } } ] @d = create(:membership_product_with_preset_tiered_pricing, recurrence_price_values: recurrence_price_values_d, name: "Physical Subscription D", user: @creator, created_at: 17.minutes.ago) @d.tag!("Audio") @e = create(:product, price_cents: 400, name: "Digital Preorder E", user: @creator, created_at: 16.minutes.ago) create(:variant, variant_category: create(:variant_category, link: @e), price_difference_cents: 100) @e.tag!("Audio") @hideme = create(:product_with_files, user: @creator, name: "Hidden") @f = create(:product, user: @creator, name: "Digital Product F", price_cents: 110, created_at: 15.minutes.ago) purchase_f = create(:purchase, link: @f, email: purchaser_email) create(:product_review, purchase: purchase_f, rating: 2) @g = create(:product, user: @creator, name: "Digital Product G", price_cents: 120, created_at: 14.minutes.ago, display_product_reviews: false) purchase_g = create(:purchase, link: @g, email: purchaser_email) create(:product_review, purchase: purchase_g, rating: 2) @h = create(:product, user: @creator, name: "Digital Product H", price_cents: 130, created_at: 13.minutes.ago) purchase_h = create(:purchase, link: @h, email: purchaser_email) create(:product_review, purchase: purchase_h, rating: 1) @i = create(:product, user: @creator, name: "Digital Product I", price_cents: 140, created_at: 12.minutes.ago) @j = create(:product, user: @creator, name: "Digital Product J", price_cents: 150, created_at: 11.minutes.ago) @section = create(:seller_profile_products_section, seller: @creator, shown_products: [@a, @b, @c, @d, @e, @f, @g, @h, @i, @j].map { _1.id }, show_filters: true) create(:seller_profile, seller: @creator, json_data: { tabs: [{ name: "Products", sections: [@section.id] }] }) Link.import(refresh: true, force: true) end it("allows other users to sort the products") do login_as(create(:user)) visit("/#{@creator.username}") expect_product_cards_in_order([@a, @b, @c, @d, @e, @f, @g, @h, @i]) toggle_disclosure "Sort by" choose "Price (Low to High)" wait_for_ajax expect_product_cards_in_order([@d, @f, @g, @h, @i, @j, @b, @a, @c]) choose "Highest rated" wait_for_ajax expect_product_cards_in_order([@c, @b, @g, @f, @h, @j, @i, @e, @d]) choose "Most reviewed" wait_for_ajax expect_product_cards_in_order([@c, @b, @h, @g, @f, @j, @i, @e, @d]) end it("allows other users to search for products") do login_as(create(:user)) visit("/#{@creator.username}") expect_product_cards_in_order([@a, @b, @c, @d, @e, @f, @g, @h, @i]) fill_in "Search products", with: "Physical\n" sleep 2 # because there's an explicit delay in the javascript handler wait_for_ajax expect_product_cards_in_order([@b, @d]) end describe "Filetype filter" do before do # seed PDF create(:product_file, link: @a) # seed ZIP create(:product_file, link: @b, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/preorder.zip") @c.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/preorder.zip") # seed MP3 @c.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/magic.mp3") @c.save! Link.import(refresh: true, force: true) end it "handles filetype filters properly" do visit("/#{@creator.username}") toggle_disclosure "Contains" check "pdf (1)" wait_for_ajax expect(page).to have_product_card(count: 1) expect(page).to have_product_card(text: "Digital Product A") check "zip (2)" wait_for_ajax # filetype filters are additive, e.g. if both PDF + ZIP are selected we should be # seeing A (PDF) and B, C (ZIP) expect_product_cards_in_order([@a, @b, @c]) uncheck "zip (2)" wait_for_ajax uncheck "pdf (1)" wait_for_ajax check "mp3 (1)" wait_for_ajax expect(page).to have_product_card(count: 1) expect(page).to have_product_card(text: "Digital Subscription C") uncheck "mp3 (1)" wait_for_ajax expect_product_cards_in_order([@a, @b, @c, @d, @e, @f, @g, @h, @i]) end end it "allows other users to filter by price" do login_as(create(:user)) visit("/#{@creator.username}") toggle_disclosure "Price" fill_in "Minimum price", with: "2" wait_for_ajax expect_product_cards_in_order([@a, @b, @c, @e]) fill_in "Maximum price", with: "4" wait_for_ajax expect_product_cards_in_order([@a, @b, @c]) fill_in "Minimum price", with: "" fill_in "Maximum price", with: "" wait_for_ajax expect_product_cards_in_order([@a, @b, @c, @d, @e, @f, @g, @h, @i]) end it("displays products sorted by default_product_sort") do @section.update!(default_product_sort: ProductSortKey::PRICE_ASCENDING) visit("/#{@creator.username}") toggle_disclosure "Sort by" expect(page).to have_checked_field("Price (Low to High)") expect_product_cards_in_order([@d, @f, @g, @h, @i, @j, @b, @a, @c]) end it("allows users to search for products with selected tags and sort them") do login_as(create(:user)) visit("/#{@creator.username}") expect_product_cards_in_order([@a, @b, @c, @d, @e, @f, @g, @h, @i]) toggle_disclosure "Tags" check "audio (3)" wait_for_ajax expect_product_cards_in_order([@a, @d, @e]) fill_in "Search products", with: "digital\n" sleep 2 # because there's an explicit delay in the javascript handler wait_for_ajax expect_product_cards_in_order([@a, @e]) toggle_disclosure "Sort by" choose "Price (High to Low)" wait_for_ajax expect_product_cards_in_order([@e, @a]) uncheck "audio (2)" expect_product_cards_in_order([@e, @c, @a, @j, @i, @h, @g, @f]) fill_in("Search products", with: "") find_field("Search products").native.send_keys(:return) sleep 2 # because there's an explicit delay in the javascript handler wait_for_ajax expect_product_cards_in_order([@e, @c, @a, @b, @j, @i, @h, @g, @f]) end it "allows to reset active filters" do @section.update!(default_product_sort: ProductSortKey::HIGHEST_RATED) login_as(create(:user)) visit("/#{@creator.username}") expect(page).to have_text("1-9 of 10 products") expect(page).to_not have_button("Clear") toggle_disclosure "Sort by" expect(page).to have_checked_field("Highest rated") # Apply some filters choose "Most reviewed" wait_for_ajax toggle_disclosure "Price" fill_in "Maximum price", with: "2" wait_for_ajax expect(page).to have_text("1-7 of 7 products") expect(page).to have_button("Clear") expect(page).to have_checked_field("Most reviewed") # Reset the applied filters click_on("Clear") wait_for_ajax expect(page).to have_text("1-9 of 10 products") expect(page).to_not have_button("Clear") expect(page).to have_checked_field("Highest rated") end it "hides 'Show NSFW' toggle and always displays NSFW products" do @a.update!(is_adult: true) Link.import(refresh: true, force: true) visit("/#{@creator.username}") expect(page).to_not have_text("Show NSFW") expect(page).to have_product_card(text: "Digital Product A") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/bundles/show_spec.rb
spec/requests/bundles/show_spec.rb
# frozen_string_literal: true require "spec_helper" describe("Bundle page", type: :system, js: true) do let(:seller) { create(:named_seller) } let(:bundle) { create(:product, user: seller, is_bundle: true, price_cents: 1000) } let(:product) { create(:product, user: seller, name: "Product", price_cents: 500) } let!(:bundle_product) { create(:bundle_product, bundle:, product:) } let(:versioned_product) { create(:product_with_digital_versions, user: seller, name: "Versioned product") } let!(:versioned_bundle_product) { create(:bundle_product, bundle:, product: versioned_product, variant: versioned_product.alive_variants.first, quantity: 3) } before do versioned_bundle_product.variant.update!(price_difference_cents: 400) end describe "price" do it "displays the standalone price and the bundle price" do visit bundle.long_url within first("[itemprop='price']") do expect(page).to have_selector("s", text: "$20") expect(page).to have_text("$10") end end context "when the bundle has a discount" do let(:offer_code) { create(:percentage_offer_code, user: seller, products: [bundle], amount_percentage: 50) } it "displays the standalone price and the discounted bundle price" do visit "#{bundle.long_url}/#{offer_code.code}" within first("[itemprop='price']") do expect(page).to have_selector("s", text: "$20") expect(page).to have_text("$5") end end end end it "displays the bundle products" do visit bundle.long_url within_section "This bundle contains..." do within_cart_item "Product" do expect(page).to have_link("Product", href: product.long_url) expect(page).to have_selector("[aria-label='Rating']", text: "0.0 (0)") expect(page).to have_selector("[aria-label='Price'] s", text: "$5") expect(page).to have_text("Qty: 1") end within_cart_item "Versioned product" do expect(page).to have_link("Versioned product", href: versioned_product.long_url) expect(page).to have_selector("[aria-label='Rating']", text: "0.0 (0)") expect(page).to have_selector("[aria-label='Price'] s", text: "$15") expect(page).to have_text("Qty: 3") expect(page).to have_text("Version: Untitled 1") end end end context "when the bundle has already been purchased" do let(:user) { create(:user) } let!(:url_redirect) { create(:url_redirect, purchase: create(:purchase, link: bundle, purchaser: user)) } it "displays the existing purchase stack" do login_as user visit bundle.long_url within_section "You've purchased this bundle" do expect(page).to have_link("View content", href: url_redirect.download_page_url) expect(page).to_not have_text("Liked it? Give it a rating") 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/bundles/edit_spec.rb
spec/requests/bundles/edit_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" require "shared_examples/creator_dashboard_page" describe("Bundle edit page", type: :system, js: true) do let(:seller) { create(:named_seller) } let(:bundle) { create(:product, :bundle, user: seller, price_cents: 200) } let!(:asset_preview1) { create(:asset_preview, link: bundle) } let!(:asset_preview2) { create(:asset_preview_gif, link: bundle) } include_context "with switching account to user as admin for seller" it_behaves_like "creator dashboard page", "Products" do let(:path) { bundle_path(bundle.external_id) } end it "updates the bundle" do Feature.activate_user(:audio_previews, seller) visit bundle_path(bundle.external_id) in_preview { expect(page).to have_section("Bundle") } find_field("Name", with: "Bundle").fill_in with: "New bundle" in_preview { expect(page).to have_section("New bundle") } rich_text_editor_input = find("[aria-label='Description']") expect(rich_text_editor_input).to have_text("This is a bundle of products") in_preview { expect(page).to have_text("This is a bundle of products") } set_rich_text_editor_input rich_text_editor_input, to_text: "This is a new bundle of products" in_preview { expect(page).to have_text("This is a new bundle of products") } page.attach_file(file_fixture("test.jpg")) do click_on "Insert image" end attach_file file_fixture("test.mp3") do click_on "Insert audio" end expect(page).to have_button("Save changes", disabled: true) expect(page).to have_button("Unpublish", disabled: true) wait_for_file_embed_to_finish_uploading(name: "test") wait_for_ajax in_preview { expect(page).to have_selector("img[src*='#{AWS_S3_ENDPOINT}/#{S3_BUCKET}']") } in_preview { expect(page).to have_embed(name: "test") } find_field("URL", with: "").fill_in with: "bundle" in_preview { expect(page).to have_selector("[itemprop='price']", text: "$2") } find_field("Amount", with: "2").fill_in with: "1" in_preview { expect(page).to have_selector("[itemprop='price']", text: "$2 $1") } in_preview { expect(page).to_not have_field("Name a fair price:") } expect(page).to have_unchecked_field("Allow customers to pay what they want") check "Allow customers to pay what they want" in_preview { expect(page).to have_field("Name a fair price:", placeholder: "1+") } in_preview { expect(page).to have_selector("[itemprop='price']", text: "$2 $1+") } expect(page).to have_field("Minimum amount", with: "1", disabled: true) find_field("Suggested amount", with: "").fill_in with: "5" in_preview { expect(page).to have_field("Name a fair price:", placeholder: "5+") } in_preview { expect(page).to have_selector("img[src*='#{asset_preview1.url}']") } within_section "Cover", section_element: :section do first("[role='tab'][aria-selected='true']").drag_to first("[role='tab'][aria-selected='false']") end in_preview { expect(page).to have_selector("img[src*='#{asset_preview2.url}']") } in_preview { expect(page).to have_link("I want this!") } find_field("Call to action", with: "i_want_this_prompt").find(:option, "Buy this").select_option in_preview { expect(page).to have_link("Buy this") } find_field("Summary", with: "").fill_in with: "To summarize, I am a bundle." in_preview { expect(page).to have_text("To summarize, I am a bundle.") } click_on "Add detail" within_fieldset "Additional details" do inputs = all("input[type='text']") inputs[0].fill_in with: "Attribute" inputs[1].fill_in with: "Value" end in_preview { expect(page).to have_text("Attribute Value", normalize_ws: true) } in_preview { expect(page).to_not have_text("20 left") } check("Limit product sales", unchecked: true) fill_in "Maximum number of purchases", with: "20" in_preview { expect(page).to have_text("20 left") } in_preview { expect(page).to_not have_field("Quantity") } check("Allow customers to choose a quantity", unchecked: true) in_preview { expect(page).to have_field("Quantity", with: "1") } in_preview { expect(page).to_not have_selector("[role='status']") } check("Publicly show the number of sales on your product page", unchecked: true) in_preview { expect(page).to have_selector("[role='status']", text: "0 sales") } check("Mark product as e-publication for VAT purposes", unchecked: true) click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") product_page = window_opened_by { click_on "Preview" } bundle.reload within_window(product_page) { expect(page.current_url).to eq(bundle.long_url) } expect(bundle.name).to eq("New bundle") public_file = bundle.alive_public_files.sole expect(bundle.description).to include("<p>This is a new bundle of products</p>") expect(bundle.description).to include(%{<figure><img src="#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{ActiveStorage::Blob.find_by(filename: "test.jpg").key}"><p class="figcaption"></p></figure>}) expect(bundle.description).to include(%{<public-file-embed id="#{public_file.public_id}"></public-file-embed>}) expect(bundle.custom_permalink).to eq("bundle") expect(bundle.price_cents).to eq(100) expect(bundle.customizable_price).to eq(true) expect(bundle.suggested_price_cents).to eq(500) expect(bundle.display_asset_previews).to eq([asset_preview2, asset_preview1]) expect(bundle.custom_button_text_option).to eq("buy_this_prompt") expect(bundle.custom_summary).to eq("To summarize, I am a bundle.") expect(bundle.custom_attributes).to eq([{ "name" => "Attribute", "value" => "Value" }]) expect(bundle.max_purchase_count).to eq(20) expect(bundle.quantity_enabled).to eq(true) expect(bundle.should_show_sales_count).to eq(true) expect(bundle.is_epublication?).to eq(true) end context "when seller refund is set to false" do before do seller.update!(refund_policy_enabled: false) create(:product_refund_policy, seller:, product: create(:product, user: seller, name: "Other product")) end it "allows updating the bundle refund policy" do visit bundle_path(bundle.external_id) find_field("Specify a refund policy for this product", unchecked: true).check select_disclosure "Copy from other products" do select_combo_box_option "Other product" click_on "Copy" end select "7-day money back guarantee", from: "Refund period" find_field("Fine print (optional)", with: "This is a product-level refund policy").fill_in with: "I hate being small" in_preview do within "[role=dialog]" do expect(page).to have_selector("h2", text: "7-day money back guarantee") expect(page).to have_text("I hate being small") end end product_page = window_opened_by { click_on "Preview" } expect(page).to have_alert(text: "Changes saved!") bundle.reload within_window(product_page) { expect(page.current_url).to eq(bundle.long_url) } expect(bundle.product_refund_policy_enabled?).to eq(true) expect(bundle.product_refund_policy.max_refund_period_in_days).to eq(7) expect(bundle.product_refund_policy.title).to eq("7-day money back guarantee") expect(bundle.product_refund_policy.fine_print).to eq("I hate being small") end end it "updates the covers" do visit bundle_path(bundle.external_id) within_section "Cover", section_element: :section do first("[role='tab']").hover find("[aria-label='Remove cover']").click wait_for_ajax first("[role='tab']").hover find("[aria-label='Remove cover']").click wait_for_ajax expect(bundle.reload.display_asset_previews).to be_empty vcr_turned_on do VCR.use_cassette("Update bundle covers") do click_on "Upload images or videos" attach_file file_fixture("test.png") do select_tab "Computer files" end wait_for_ajax expect(page).to have_selector("img[src*='#{AWS_S3_ENDPOINT}/#{S3_BUCKET}']") expect(bundle.reload.display_asset_previews.alive.first.url).to match("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}") select_disclosure "Add cover" do click_on "Upload images or videos" select_tab "External link" fill_in "https://", with: "https://www.youtube.com/watch?v=dQw4w9WgXcQ" click_on "Upload" end wait_for_ajax all("img[src*='#{AWS_S3_ENDPOINT}/#{S3_BUCKET}']").last.hover click_on "Show next cover" expect(page).to have_selector("iframe[src*='youtube.com']") expect(bundle.reload.display_asset_previews.alive.second.url).to match("youtube.com") end end end end describe "content tab" do let!(:versioned_product) { create(:product_with_digital_versions, name: "Versioned product", user: seller, created_at: 1.month.ago) } let!(:products) do create_list(:product, 10, user: seller, quantity_enabled: true) do |product, i| product.update(name: "Product #{i}", created_at: i.days.ago) end end before do index_model_records(Link) end it "updates the bundle products" do visit "#{bundle_path(bundle.external_id)}/content" within "[aria-label='Product selector']" do check("Product 1", unchecked: true) end expect(page).to_not have_field("Versioned product") fill_in "Search products", with: "Versioned product" within "[aria-label='Product selector']" do check("Versioned product", unchecked: true) end within "[aria-label='Bundle products']" do within_cart_item "Bundle Product 1" do click_on "Remove" end within_cart_item "Versioned product" do expect(page).to have_text("Qty: 1") expect(page).to have_text("Version: Untitled 1") select_disclosure "Configure" do choose "Untitled 2" click_on "Apply" end expect(page).to have_text("Version: Untitled 2") end within_cart_item "Product 1" do expect(page).to have_text("Qty: 1") select_disclosure "Configure" do fill_in "Quantity", with: 2 click_on "Apply" end expect(page).to have_text("Qty: 2") end end select_tab "Product" in_preview { expect(page).to have_selector("[itemprop='price']", text: "$4 $2") } click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") bundle.reload expect(bundle.bundle_products.first.deleted_at).to_not be_nil expect(bundle.bundle_products.second.deleted_at).to be_nil expect(bundle.bundle_products.second.position).to eq(0) expect(bundle.bundle_products.third.product).to eq(products[1]) expect(bundle.bundle_products.third.variant).to be_nil expect(bundle.bundle_products.third.quantity).to eq(2) expect(bundle.bundle_products.third.position).to eq(1) expect(bundle.bundle_products.fourth.product).to eq(versioned_product) expect(bundle.bundle_products.fourth.variant).to eq(versioned_product.alive_variants.second) expect(bundle.bundle_products.fourth.quantity).to eq(1) expect(bundle.bundle_products.fourth.position).to eq(2) end it "loads more products when scrolled to the bottom" do visit "#{bundle_path(bundle.external_id)}/content" wait_for_ajax expect(page).to_not have_selector("[role='progressbar']") expect(page).to_not have_field("Product 8") scroll_to find_field("Product 7") expect(page).to have_field("Product 8") end it "allows selecting and unselecting all products" do visit "#{bundle_path(bundle.external_id)}/content" check "All products", unchecked: true expect(page).to have_field("All products", disabled: true) wait_for_ajax within "[aria-label='Bundle products']" do (0..9).each do |i| expect(page).to have_section("Product #{i}") end expect(page).to have_section("Versioned product") expect(page).to have_section("Bundle Product 1") expect(page).to have_section("Bundle Product 2") end within "[aria-label='Product selector']" do (0..9).each do |i| expect(page).to have_section("Product #{i}") end expect(page).to have_section("Versioned product") expect(page).to have_section("Bundle Product 1") expect(page).to have_section("Bundle Product 2") end uncheck "All products", checked: true expect(page).to_not have_selector("[aria-label='Bundle products']") click_on "Save changes" expect(page).to have_alert(text: "Bundles must have at least one product.") end context "when the bundle has no products" do let(:empty_bundle) { create(:product, :unpublished, user: seller, is_bundle: true) } it "displays a placeholder" do visit "#{bundle_path(empty_bundle.external_id)}/content" expect(page).to_not have_selector("[aria-label='Product selector']") within_section "Select products", section_element: :section, match: :first do expect(page).to have_text("Choose the products you want to include in your bundle") click_on "Add products" end expect(page).to_not have_section("Select products") expect(page).to have_selector("[aria-label='Product selector']") click_on "Publish and continue" expect(page).to have_alert(text: "Bundles must have at least one product.") end end end describe "share tab" do it "updates the bundle share settings" do visit "#{bundle_path(bundle.external_id)}/share" encoded_url = CGI.escape(bundle.long_url) expect(page).to have_link("Share on X", href: "https://twitter.com/intent/tweet?url=#{encoded_url}&text=Buy%20Bundle%20on%20%40Gumroad") expect(page).to have_link("Share on Facebook", href: "https://www.facebook.com/sharer/sharer.php?u=#{encoded_url}&quote=Bundle") expect(page).to have_button("Copy URL") within_fieldset "Category" do select_combo_box_option search: "3D > 3D Modeling", from: "Category" end within_fieldset "Tags" do 5.times do |index| select_combo_box_option search: "Test#{index}", from: "Tags" expect(page).to have_button("test#{index}") end fill_in "Tags", with: "Test6" expect(page).to_not have_combo_box "Tags", expanded: true click_on "test2" click_on "test3" click_on "test4" end uncheck("Display your product's 1-5 star rating to prospective customers", checked: true) check("This product contains content meant only for adults, including the preview", checked: false) expect(page).to have_text "You currently have no sections in your profile to display this" expect(page).to have_link "create one here", href: root_url(host: seller.subdomain) click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") bundle.reload expect(bundle.taxonomy.slug).to eq("3d-modeling") expect(bundle.tags.size).to eq(2) expect(bundle.tags.first.name).to eq("test0") expect(bundle.tags.second.name).to eq("test1") expect(bundle.display_product_reviews?).to eq(false) expect(bundle.is_adult?).to eq(true) expect(bundle.discover_fee_per_thousand).to eq(100) section = create(:seller_profile_products_section, seller:) visit "#{bundle_path(bundle.external_id)}/share" within_fieldset "Category" do click_on "Clear value" end # Unfocus input find("h2", text: "Gumroad Discover").click within_fieldset "Tags" do click_on "test0" end check("Display your product's 1-5 star rating to prospective customers", checked: false) uncheck("This product contains content meant only for adults, including the preview", checked: true) check("Unnamed section", checked: false) click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") bundle.reload expect(bundle.taxonomy).to be_nil expect(bundle.tags.size).to eq(1) expect(bundle.tags.first.name).to eq("test1") expect(bundle.display_product_reviews?).to eq(true) expect(bundle.is_adult?).to eq(false) expect(bundle.discover_fee_per_thousand).to eq(100) expect(section.reload.shown_products).to include bundle.id visit "#{bundle_path(bundle.external_id)}/share" uncheck("Unnamed section", checked: true) click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(section.reload.shown_products).to_not include bundle.id end end it "allows unpublishing and publishing the bundle" do bundle.publish! visit "#{bundle_path(bundle.external_id)}" click_on "Unpublish" expect(page).to have_alert(text: "Unpublished!") expect(bundle.reload.purchase_disabled_at).to_not be_nil click_on "Save and continue" wait_for_ajax expect(page.current_path).to eq("#{bundle_path(bundle.external_id)}/content") select_tab "Share" expect(page).to have_alert(text: "Not yet! You've got to publish your awesome product before you can share it with your audience and the world.") select_tab "Product" fill_in "Name", with: "New bundle" select_tab "Content" click_on "Publish and continue" expect(page).to have_alert(text: "Published!") bundle.reload expect(bundle.purchase_disabled_at).to be_nil expect(bundle.name).to eq("New bundle") expect(page.current_path).to eq("#{bundle_path(bundle.external_id)}/share") click_on "Unpublish" expect(page).to have_alert(text: "Unpublished!") expect(bundle.reload.purchase_disabled_at).to_not be_nil expect(page.current_path).to eq("#{bundle_path(bundle.external_id)}/content") end context "product is not a bundle" do let(:product) { create(:product, user: seller) } it "converts the product to a bundle on save" do visit bundle_path(product.external_id) expect(page).to have_alert(text: "Select products and save your changes to finish converting this product to a bundle.") select_tab "Content" click_on "Add products" check "Bundle Product 1" click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") product.reload expect(product.is_bundle).to eq(true) expect(product.native_type).to eq(Link::NATIVE_TYPE_BUNDLE) expect(product.bundle_products.map(&:product)).to eq([bundle.bundle_products.first.product]) end end context "bundle has purchases with outdated content" do before { bundle.update!(has_outdated_purchases: true) } it "shows a notice from which the seller can update the purchases" do visit "#{bundle_path(bundle.external_id)}/content" expect(page).to have_text("Some of your customers don't have access to the latest content in your bundle.") expect(page).to have_text("Would you like to give them access and send them an email notification?") click_on "Yes, update" expect(page).to have_alert(text: "Queued an update to the content of all outdated purchases.") expect(page).to_not have_text("Some of your customers don't have access to the latest content in your bundle.") expect(UpdateBundlePurchasesContentJob).to have_enqueued_sidekiq_job(bundle.id) end end it "shows marketing status" do bundle.update!(price_cents: 100) create(:audience_member, seller:, purchases: [{}]) visit "#{bundle_path(bundle.external_id)}/share" original_window = page.current_window expect(page).to have_text("Your product bundle is ready. Would you like to send an email about this offer to existing customers?") expect(page).to have_radio_button("Customers who have purchased at least one product in the bundle", checked: true) expect(page).to have_radio_button("All customers", unchecked: true) within_window(window_opened_by { click_on "Draft and send" }) do expect(page).to have_field("Title", with: "Introducing Bundle") within "[aria-label='Email message']" do expect(page).to have_text("Hey there,") expect(page).to have_text("I've put together a bundle of my products that I think you'll love.") expect(page).to have_text("Bundle") expect(page).to have_text("$2 $1") expect(page).to have_text("Included in this bundle") within "ul" do expect(page).to have_link("Bundle Product 1", href: short_link_url(bundle.bundle_products.first.product.unique_permalink, host: DOMAIN)) expect(page).to have_link("Bundle Product 2", href: short_link_url(bundle.bundle_products.second.product.unique_permalink, host: DOMAIN)) end expect(page).to have_link("Get your bundle", href: short_link_url(bundle.unique_permalink, host: DOMAIN)) expect(page).to have_text("Thanks for your support!") end expect(page).to have_radio_button("Everyone", unchecked: true) expect(page).to have_radio_button("Customers only", checked: true) find(:combo_box, "Bought").click within(:fieldset, "Bought") do expect(page).to have_button("Bundle Product 1") expect(page).to have_button("Bundle Product 2") expect(page).to have_combo_box "Bought", options: ["Bundle"] end find(:combo_box, "Has not yet bought").click within(:fieldset, "Has not yet bought") do expect(page).to_not have_button("Bundle Product 1") expect(page).to_not have_button("Bundle Product 2") expect(page).to have_combo_box "Has not yet bought", options: ["Bundle Product 1", "Bundle Product 2", "Bundle"] end end page.switch_to_window(original_window) choose "All customers" within_window(window_opened_by { click_on "Draft and send" }) do expect(page).to have_radio_button("Everyone", unchecked: true) expect(page).to have_radio_button("Customers only", checked: true) find(:combo_box, "Bought").click within(:fieldset, "Bought") do expect(page).to_not have_button("Bundle Product 1") expect(page).to_not have_button("Bundle Product 2") expect(page).to have_combo_box "Bought", options: ["Bundle Product 1", "Bundle Product 2", "Bundle"] end send_keys :escape find(:combo_box, "Has not yet bought").click find(:combo_box, "Has not yet bought").click within(:fieldset, "Has not yet bought") do expect(page).to_not have_button("Bundle Product 1") expect(page).to_not have_button("Bundle Product 2") expect(page).to have_combo_box "Has not yet bought", options: ["Bundle Product 1", "Bundle Product 2", "Bundle"] 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/settings/team_spec.rb
spec/requests/settings/team_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Settings > Team Scenario", type: :system, js: true) do let(:seller) { create(:named_seller) } shared_examples_for "leaves the team" do it "deletes membership and switches account" do visit settings_team_path within_section("Team members", section_element: :section) do within find(:table_row, { "Member" => user_with_role_for_seller.display_name }) do click_on("Leave team") end end within_modal "Leave team?" do expect(page).to have_text("Are you sure you want to leave Seller team? Once you leave the team you will no longer have access.") click_on "Yes, leave team" end wait_for_ajax expect(seller.seller_memberships.find_by(user: user_with_role_for_seller).deleted?).to eq(true) within 'nav[aria-label="Main"]' do expect(page).to have_text(user_with_role_for_seller.display_name) end expect(page).to have_text("Welcome") end end context "with switching account to user as admin for seller" do include_context "with switching account to user as admin for seller" describe "Add team members section" do it "displays only allowed roles" do visit settings_team_path within_section("Add team members", section_element: :section) do find("label", text: "Role").click expect(page).to have_combo_box( "Role", options: TeamInvitation::ROLES.map { |role| role.humanize } ) end end it "submits the form and refreshes the table" do visit settings_team_path within_section("Add team members", section_element: :section) do fill_in("Email", with: "new@example.com") select_combo_box_option("Admin", from: "Role") click_on("Send invitation") end wait_for_ajax within_section("Team members", section_element: :section) do expect(page).to have_content "new@example.com" end end end describe "Team members section" do let(:user) { create(:user, name: "Joe") } let!(:team_membership) { create(:team_membership, seller:, user:, role: TeamMembership::ROLE_MARKETING) } let!(:team_invitation) { create(:team_invitation, seller:, email: "member@example.com") } it "renders the table" do visit settings_team_path within_section("Team members", section_element: :section) do expect(page).to have_content seller.display_name expect find(:table_row, { "Member" => "Seller", "Role" => "Owner" }) expect(find(:table_row, { "Member" => user_with_role_for_seller.display_name, "Role" => "Admin" })).to have_button("Leave team") end end it "removes and restores team membership" do visit settings_team_path within_section("Team members", section_element: :section) do within find(:table_row, { "Member" => "Joe" }) do select_combo_box_option("Remove from team") end wait_for_ajax expect(page).to have_alert(text: "Joe was removed from team members") within find(:table) do expect(page).not_to have_content "Joe" end click_on "Undo" end wait_for_ajax expect(page).to have_alert(text: "Joe was added back to the team") within_section("Team members", section_element: :section) do expect(page).not_to have_button("Undo") expect(find(:table_row, { "Member" => "Joe", "Role" => "Marketing" })) end end it "removes and restores team invitation" do visit settings_team_path within_section("Team members", section_element: :section) do within find(:table_row, { "Member" => team_invitation.email }) do select_combo_box_option("Remove from team") end wait_for_ajax expect(page).to have_alert(text: "#{team_invitation.email} was removed from team members") within find(:table) do expect(page).not_to have_content team_invitation.email end click_on "Undo" end wait_for_ajax expect(page).to have_alert(text: "#{team_invitation.email} was added back to the team") within_section("Team members", section_element: :section) do expect(page).not_to have_button("Undo") expect(find(:table_row, { "Member" => "member@example.com", "Role" => "Admin" })) end end it "updates role" do visit settings_team_path within_section("Team members", section_element: :section) do within find(:table_row, { "Member" => "Joe", "Role" => "Marketing" }) do select_combo_box_option("Admin") end end wait_for_ajax expect(page).to have_alert(text: "Role for Joe has changed to Admin") within_section("Team members", section_element: :section) do expect find(:table_row, { "Member" => "Joe", "Role" => "Admin" }) end end it_behaves_like "leaves the team" context "with expired invitation" do before do team_invitation.update!(expires_at: 1.minute.ago) end it "resends invitation" do visit settings_team_path within_section("Team members", section_element: :section) do within find(:table_row, { "Member" => team_invitation.email }) do select_combo_box_option("Resend invitation") end end wait_for_ajax expect(page).to have_alert(text: "Invitation sent!") end end 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_behaves_like "leaves the team" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/settings/password_spec.rb
spec/requests/settings/password_spec.rb
# frozen_string_literal: true require "spec_helper" describe("Password Settings Scenario", type: :system, js: true) do let(:compromised_password) { "password" } let(:not_compromised_password) { SecureRandom.hex(24) } before do login_as user end context "when logged in using social login provider" do let(:user) { create(:user, provider: :facebook) } before(:each) do login_as user end it "doesn't allow setting a new password with a value that was found in the password breaches" do visit settings_password_path expect(page).to_not have_field("Old password") within("form") do fill_in("Add password", with: compromised_password) end vcr_turned_on do VCR.use_cassette("Add Password-with a compromised password") do with_real_pwned_password_check do click_on("Change password") expect(page).to have_alert(text: "New 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 "allows setting a new password with a value that was not found in the password breaches" do visit settings_password_path expect(page).to_not have_field("Old password") within("form") do fill_in("Add password", with: not_compromised_password) end vcr_turned_on do VCR.use_cassette("Add Password-with a not compromised password") do with_real_pwned_password_check do click_on("Change password") expect(page).to have_alert(text: "You have successfully changed your password.") end end end end end context "when not logged in using social provider" do let(:user) { create(:user) } before(:each) do login_as user end it "validates the new password length" do visit settings_password_path expect do fill_in("Old password", with: user.password) fill_in("New password", with: "123") click_on("Change password") expect(page).to have_alert(text: "Your new password is too short.") end.to_not change { user.reload.encrypted_password } expect do fill_in("New password", with: "1234") click_on("Change password") expect(page).to have_alert(text: "You have successfully changed your password.") end.to change { user.reload.encrypted_password } expect do fill_in("Old password", with: "1234") fill_in("New password", with: "*" * 128) click_on("Change password") expect(page).to have_alert(text: "Your new password is too long.") end.to_not change { user.reload.encrypted_password } expect do fill_in("Old password", with: "1234") fill_in("New password", with: "*" * 127) click_on("Change password") expect(page).to have_alert(text: "You have successfully changed your password.") end.to change { user.reload.encrypted_password } end it "doesn't allow changing the password with a value that was found in the password breaches" do visit settings_password_path within("form") do fill_in("Old password", with: user.password) fill_in("New password", with: compromised_password) end vcr_turned_on do VCR.use_cassette("Add Password-with a compromised password") do with_real_pwned_password_check do click_on("Change password") expect(page).to have_alert( text: "New 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 "allows changing the password with a value that was not found in the password breaches" do visit settings_password_path within("form") do fill_in("Old password", with: user.password) fill_in("New password", with: not_compromised_password) end vcr_turned_on do VCR.use_cassette("Add Password-with a not compromised password") do with_real_pwned_password_check do click_on("Change password") expect(page).to have_alert(text: "You have successfully changed your password.") 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/settings/main_spec.rb
spec/requests/settings/main_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Main Settings Scenario", type: :system, js: true) do let(:user) { create(:user, name: "Gum") } before do login_as user end describe "sub navigation" do it "displays main, profile, payments, password, and advanced sections" do visit settings_main_path expect(page).to have_tab_button "Settings" expect(page).to have_tab_button "Profile" expect(page).to have_tab_button "Payments" expect(page).to have_tab_button "Password" expect(page).to have_tab_button "Advanced" end end context "when email is present" do it "allows user to update settings" do visit settings_main_path new_email = "k@gumroad.com" within_section "User details", section_element: :section do fill_in("Email", with: new_email) end click_on("Update settings") expect(page).to have_alert(text: "Your account has been updated!") expect(user.reload.unconfirmed_email).to eq new_email end end context "when email is empty" do it "shows a validation error on save" do visit settings_main_path within_section "User details", section_element: :section do fill_in("Email", with: "") end click_on("Update settings") within_section "User details", section_element: :section do validation_message = find_field("Email").native.attribute("validationMessage") expect(validation_message).to eq "Please fill out this field." end end end describe "Unconfirmed email" do context "when email is verified" do it "doesn't show resend link" do visit settings_main_path within_section "User details", section_element: :section do expect(find_field("Email").value).to eq user.email end expect(page).to_not have_link("Resend confirmation?") end end context "when email is not verified" do before do user.update!(email: "n00b@gumroad.com") end it "allows resending email confirmation" do visit settings_main_path within_section "User details", section_element: :section do expect(find_field("Email").value).to eq "n00b@gumroad.com" end expect(page).to have_text("This email address has not been confirmed yet. Resend confirmation?") click_on "Resend confirmation?" expect(page).to have_alert(text: "Confirmation email resent!") expect(page).to_not have_link("Resend confirmation?") end end end context "when logged user has role admin" do let(:seller) { create(:named_seller) } include_context "with switching account to user as admin for seller" it "disables the form" do visit settings_main_path expect(page).not_to have_link("Password") expect(page).not_to have_button("Update settings") expect(page).not_to have_selector(".js-invalidate-active-sessions-trigger", text: "Sign out from all active sessions") end end describe "purchasing power parity" do it "allows the user to update the settings" do visit settings_main_path expect(page).to have_unchecked_field("Enable purchasing power parity") check "Enable purchasing power parity" fill_in "Maximum PPP discount", with: "50" check "Apply only if the customer is currently located in the country of their payment method" click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") user.reload expect(user.purchasing_power_parity_enabled).to eq(true) expect(user.purchasing_power_parity_limit).to eq(50) expect(user.purchasing_power_parity_payment_verification_disabled).to eq(false) visit settings_main_path expect(page).to have_checked_field("Enable purchasing power parity") fill_in "Maximum PPP discount", with: "" uncheck "Apply only if the customer is currently located in the country of their payment method" uncheck "Enable purchasing power parity" expect(page).to_not have_field("Maximum PPP discount") expect(page).to_not have_field("Apply only if the customer is currently located in the country of their payment method") click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") user.reload expect(user.purchasing_power_parity_enabled).to eq(false) expect(user.purchasing_power_parity_limit).to eq(nil) expect(user.purchasing_power_parity_payment_verification_disabled).to eq(true) visit settings_main_path expect(page).to have_unchecked_field("Enable purchasing power parity") end describe "excluding products" do before do @product_1 = create(:product, user:, name: "Product 1") @product_2 = create(:product, user:, name: "Product 2") user.update(purchasing_power_parity_enabled: true) end it "allows the user to exclude certain products" do visit settings_main_path select_combo_box_option "Product 2", from: "Products to exclude" within_fieldset "Products to exclude" do expect(page).to have_button("Product 2") end click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") user.reload expect(user.purchasing_power_parity_excluded_product_external_ids).to eq([@product_2.external_id]) expect(@product_1.reload.purchasing_power_parity_enabled?).to eq(true) expect(@product_2.reload.purchasing_power_parity_enabled?).to eq(false) end it "allows the user to exclude all products" do visit settings_main_path check "All products", unchecked: true within_fieldset "Products to exclude" do expect(page).to have_button("Product 1") expect(page).to have_button("Product 2") end click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") user.reload expect(user.purchasing_power_parity_excluded_product_external_ids).to eq([@product_1.external_id, @product_2.external_id]) expect(@product_1.reload.purchasing_power_parity_enabled?).to eq(false) expect(@product_2.reload.purchasing_power_parity_enabled?).to eq(false) end it "allows the user to remove all excluded products" do @product_1.update(purchasing_power_parity_disabled: true) @product_2.update(purchasing_power_parity_disabled: true) visit settings_main_path uncheck "All products", checked: true within_fieldset "Products to exclude" do expect(page).to_not have_button("Product 1") expect(page).to_not have_button("Product 2") end click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") user.reload expect(user.purchasing_power_parity_excluded_product_external_ids).to eq([]) expect(@product_1.reload.purchasing_power_parity_enabled?).to eq(true) expect(@product_2.reload.purchasing_power_parity_enabled?).to eq(true) end end end it "allows the user to disable review notifications" do visit settings_main_path uncheck "Reviews", checked: true click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") expect(user.reload.disable_reviews_email).to eq(true) visit settings_main_path check "Reviews", unchecked: true click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") expect(user.reload.disable_reviews_email).to eq(false) end it "allows the user to toggle showing NSFW products" do visit settings_main_path expect(user.show_nsfw_products).to eq(false) expect(page).to have_unchecked_field("Show adult content in recommendations and search results") check "Show adult content in recommendations and search results" click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") expect(user.reload.show_nsfw_products).to eq(true) visit settings_main_path expect(page).to have_checked_field("Show adult content in recommendations and search results") uncheck "Show adult content in recommendations and search results" click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") expect(user.reload.show_nsfw_products).to eq(false) end describe "Refund policy" do context "when the refund policy is enabled" do before do user.update!(refund_policy_enabled: true) user.refund_policy.update!(max_refund_period_in_days: 0) end it "allows the user to update the refund policy" do visit settings_main_path expect(page).to have_field("Add a fine print to your refund policy", disabled: true) select "30-day money back guarantee", from: "Refund period" check "Add a fine print to your refund policy" fill_in "Fine print", with: "This is a sample fine print" click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") refund_policy = user.refund_policy.reload expect(refund_policy.max_refund_period_in_days).to eq(30) expect(refund_policy.fine_print).to eq("This is a sample fine print") end end context "when the refund policy is disabled" do it "does not allow the user to update the refund policy" do visit settings_main_path expect(page).to_not have_field("Refund policy") end end end context "Product level support email" do let!(:product_1) { create(:product, user:, name: "Product 1", support_email: email_1) } let!(:product_2) { create(:product, user:, name: "Product 2", support_email: nil) } let(:email_1) { "support1@example.com" } let(:email_2) { "support2@example.com" } let(:email_3) { "support3@example.com" } before { Feature.activate(:product_level_support_emails) } it "allows adding new support emails" do visit settings_main_path click_on "Add a product specific email" within find_product_level_support_email_row(name: "No email set") do fill_in "Email", with: email_2 select_combo_box_option "Product 2", from: "Products" end click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") expect(product_1.reload.support_email).to eq email_1 expect(product_2.reload.support_email).to eq email_2 end it "allows deleting support email" do visit settings_main_path within find_product_level_support_email_row(name: email_1) do click_on "Delete email" end click_on "Update settings" expect(page).to have_alert(text: "Your account has been updated!") expect(product_1.reload.support_email).to be_nil expect(product_2.reload.support_email).to be_nil end it "does not allow same product to be selected for multiple emails" do visit settings_main_path click_on "Add a product specific email" within find_product_level_support_email_row(name: "No email set") do find(:label, text: "Products").click # Product 1 is not available because it already has an email. expect(page).to have_combo_box "Products", options: ["Product 2"] end end context "when product_level_support_emails feature is disabled" do before { Feature.deactivate(:product_level_support_emails) } it "does not show product level support email form" do visit settings_main_path expect(page).not_to have_button("Add a product specific email") end end end def find_product_level_support_email_row(name:) find("[role=listitem] h4", text: name).ancestor("[role=listitem]") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/settings/advanced_spec.rb
spec/requests/settings/advanced_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Advanced Settings Scenario", type: :system, js: true) do let(:seller) { create(:user, name: "Gum") } describe "deleting the gumroad account" do context "when logged user has role admin" do include_context "with switching account to user as admin for seller" it "does not show Danger Zone" do visit settings_advanced_path expect(page).not_to have_text("Danger Zone") expect(page).not_to have_link("Delete your Gumroad account") end end context "when logged user is owner" do before do login_as seller stub_const("GUMROAD_ADMIN_ID", create(:admin_user).id) # For negative credits end it "allows deletion" do visit(settings_advanced_path) click_on "Delete your Gumroad account" click_on "Yes, delete my account" expect_alert_message("Your account has been successfully deleted.") expect(page).to have_current_path(login_path, ignore_query: true) expect(seller.reload.deleted?).to eq(true) end it "does not allow deletion if there is an unpaid balance pending" do create(:balance, user: seller, amount_cents: 10) visit(settings_advanced_path) click_on "Delete your Gumroad account" click_on "Yes, delete my account" expect_alert_message("Cannot delete due to an unpaid balance of $0.10.") expect(seller.reload.deleted?).to eq(false) end describe "when the feature delete_account_forfeit_balance is active" do before do Feature.activate_user :delete_account_forfeit_balance, seller end it "allows deletion if there is a positive unpaid balance pending" do balance = create(:balance, user: seller, amount_cents: 10) visit(settings_advanced_path) click_on "Delete your Gumroad account" expect(page).to have_text "You have a balance of $0.10. To delete your account, you will need to forfeit your balance." click_on "Yes, forfeit balance and delete" expect_alert_message("Your account has been successfully deleted.") expect(page).to have_current_path(login_path, ignore_query: true) expect(seller.reload.deleted?).to eq(true) expect(balance.reload.state).to eq("forfeited") end it "does not allow deletion if there is a negative unpaid balance pending" do create(:balance, user: seller, amount_cents: -10) visit(settings_advanced_path) click_on "Delete your Gumroad account" click_on "Yes, delete my account" expect_alert_message("Cannot delete due to an unpaid balance of $-0.10.") expect(seller.reload.deleted?).to eq(false) end end end it "logs out of all the existing sessions" do Capybara.using_session(:session_1) do login_as seller visit settings_main_path end Capybara.using_session(:session_2) do login_as seller visit settings_main_path end login_as seller visit settings_advanced_path click_on "Delete your Gumroad account" click_on "Yes, delete my account" expect_alert_message("Your account has been successfully deleted.") expect(page).to have_current_path(login_path, ignore_query: true) Capybara.using_session(:session_1) do refresh expect_alert_message("We're sorry; you have been logged out. Please login again.") expect(page).to have_current_path(login_path, ignore_query: true) end Capybara.using_session(:session_2) do refresh expect_alert_message("We're sorry; you have been logged out. Please login again.") expect(page).to have_current_path(login_path, ignore_query: true) end end end describe "Custom domain" do let(:user) { create(:user) } let(:valid_domain) { "valid-domain.com" } let(:invalid_domain) { "invalid-domain.com" } before do expect(CustomDomainVerificationService) .to receive(:new) .twice .with(domain: valid_domain) .and_return(double(process: true)) expect(CustomDomainVerificationService) .to receive(:new) .thrice .with(domain: invalid_domain) .and_return(double(process: false)) login_as user end it "allows validating the custom domain configuration and also mark it as verified/unverified accordingly on saving the specified domain" do visit settings_advanced_path # Specify invalid domain fill_in "Domain", with: invalid_domain # Save it expect do click_on "Update settings", match: :first expect(page).to have_alert(text: "Your account has been updated!") end.to change { user.reload.custom_domain&.domain }.from(nil).to(invalid_domain) expect(user.reload.custom_domain.failed_verification_attempts_count).to eq(0) expect(user.custom_domain.verified?).to eq(false) visit settings_advanced_path within_section("Custom domain", section_element: :section) do expect(page).to have_text("Domain verification failed. Please make sure you have correctly configured the DNS" \ " record for invalid-domain.com.") end # Specify blank domain fill_in "Domain", with: " " expect(page).not_to have_button("Verify") # Specify valid domain fill_in "Domain", with: valid_domain # Test the domain configuration click_on "Verify" within_section("Custom domain", section_element: :section) do expect(page).to have_text("valid-domain.com domain is correctly configured!") end # Save it expect do click_on "Update settings", match: :first expect(page).to have_alert(text: "Your account has been updated!") expect(page).to have_button("Update settings") end.to change { user.reload.custom_domain.domain }.from(invalid_domain).to(valid_domain) .and change { user.custom_domain.verified? }.from(false).to(true) end end describe "Mass-block emails" do before do ["customer1@example.com", "customer2@example.com"].each do |email| BlockedCustomerObject.block_email!(email:, seller_id: seller.id) end login_as seller visit settings_advanced_path end it "allows mass blocking customer emails by automatically sanitizing and normalizing them" do # Shows the existing blocked emails on initial page load expect(page).to have_field("Block emails from purchasing", with: "customer1@example.com\ncustomer2@example.com") # Unblocks the missing email and blocks all provided emails fill_in "Block emails from purchasing", with: "customer.2@example.com,,JOhN +1 @exAMPLE.com\n\n\ncustomer 2@ EXAMPLE.com,\nbob@ example.com" click_on "Update settings", match: :first expect(page).to have_alert(text: "Your account has been updated!") expect(page).to have_field("Block emails from purchasing", with: "customer2@example.com\njohn@example.com\nbob@example.com") expect(seller.blocked_customer_objects.active.email.pluck(:object_value)).to match_array(["customer2@example.com", "john@example.com", "bob@example.com"]) # Does not allow saving invalid emails fill_in "Block emails from purchasing", with: "JOHN @example.com\ninvalid-email@example,john+test1@EXAMPLE.com\njane.doe@example.com\nbob..rocks@example.com\nfoo+thespammer@example.com" click_on "Update settings", match: :first expect(page).to have_alert(text: "The email invalid-email@example cannot be blocked as it is invalid.") expect(page).to have_field("Block emails from purchasing", with: "john@example.com\ninvalid-email@example\njanedoe@example.com\nbob..rocks@example.com\nfoo@example.com") expect(seller.blocked_customer_objects.active.email.pluck(:object_value)).to match_array(["customer2@example.com", "john@example.com", "bob@example.com"]) # Unblocks all the previously blocked emails if saved with a blank value fill_in "Block emails from purchasing", with: "", fill_options: { clear: :backspace } click_on "Update settings", match: :first expect(page).to have_alert(text: "Your account has been updated!") expect(page).to have_field("Block emails from purchasing", with: "") expect(seller.blocked_customer_objects.active.email.count).to eq(0) refresh expect(page).to have_field("Block emails from purchasing", with: "") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/settings/third_party_analytics_spec.rb
spec/requests/settings/third_party_analytics_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Third-party Analytics Settings Scenario", type: :system, js: true) do let(:seller) { create(:named_seller) } let!(:snippet) { create(:third_party_analytic, user: seller, name: "Snippet 1") } include_context "with switching account to user as admin for seller" describe "third-party analytics updates" do it "saves the global third-party analytics toggle" do visit settings_third_party_analytics_path uncheck "Enable third-party analytics services" click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.disable_third_party_analytics).to eq(true) visit settings_third_party_analytics_path check "Enable third-party analytics services" click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.disable_third_party_analytics).to eq(false) end it "saves the Google Analytics property ID" do google_analytics_id = "G-1234567-12" visit settings_third_party_analytics_path fill_in "Google Analytics Property ID", with: google_analytics_id click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.google_analytics_id).to eq(google_analytics_id) end it "saves the Facebook pixel" do facebook_pixel_id = "123456789" visit settings_third_party_analytics_path fill_in "Facebook Pixel", with: facebook_pixel_id click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.facebook_pixel_id).to eq(facebook_pixel_id) end it "saves the $0 purchase setting" do visit settings_third_party_analytics_path uncheck "Send 'Purchase' events for free ($0) sales" click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.skip_free_sale_analytics).to eq(true) visit settings_third_party_analytics_path check "Send 'Purchase' events for free ($0) sales" click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.skip_free_sale_analytics).to eq(false) end it "saves the domain verification setting and Facebook meta tag" do facebook_meta_tag = '<meta name="facebook-domain-verification" content="dkd8382hfdjs" />' visit settings_third_party_analytics_path check "Verify domain in third-party services" fill_in "Facebook Business", with: facebook_meta_tag click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") seller.reload expect(seller.enable_verify_domain_third_party_services).to eq(true) expect(seller.facebook_meta_tag).to eq(facebook_meta_tag) visit settings_third_party_analytics_path uncheck "Verify domain in third-party services" expect(seller.reload.facebook_meta_tag).to eq(facebook_meta_tag) end it "deletes snippets" do visit settings_third_party_analytics_path within find_snippet_row(name: snippet.name) do click_on "Delete snippet" end click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") expect(snippet.reload.deleted_at).to_not be_nil end it "updates existing snippets" do visit settings_third_party_analytics_path within find_snippet_row(name: snippet.name) do click_on "Edit snippet" fill_in "Name", with: "New name" select "All products", from: "Product" select "All pages", from: "Location" fill_in "Code", with: "New code" end click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") snippet.reload expect(snippet.name).to eq("New name") expect(snippet.location).to eq("all") expect(snippet.link_id).to be_nil expect(snippet.analytics_code).to eq("New code") end it "adds new snippets" do visit settings_third_party_analytics_path click_on "Add snippet" within find_snippet_row(name: "Untitled") do fill_in "Name", with: "New name" select "All products", from: "Product" select "All pages", from: "Location" fill_in "Code", with: "New code" end click_on "Update settings" expect(page).to have_alert(text: "Changes saved!") snippet = ThirdPartyAnalytic.last expect(snippet.name).to eq("New name") expect(snippet.location).to eq("all") expect(snippet.link_id).to be_nil expect(snippet.analytics_code).to eq("New code") end end def find_snippet_row(name:) find("[role=listitem] h4", text: name).ancestor("[role=listitem]") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/settings/payments_spec.rb
spec/requests/settings/payments_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Payments Settings Scenario", type: :system, js: true) do describe "PayPal section" do let(:user) { create(:user, name: "Gum") } before do allow_any_instance_of(User).to receive(:paypal_connect_allowed?).and_return(true) login_as user end it "render Payments tab navigation" do visit settings_payments_path expect(page).to have_tab_button("Payments", open: true) end it "shows the PayPal Connect section if country is supported" do create(:user_compliance_info, user:) visit settings_payments_path expect(page).to have_link("Connect with Paypal") end it "does not show the Paypal Connect section if country is not supported" do creator = create(:user) create(:user_compliance_info, user: creator, country: "India") login_as creator visit settings_payments_path expect(page).not_to have_link("Connect with Paypal") end it "keeps the PayPal Connect button enabled and does not show the notification when user has payment_address set up" do create(:user_compliance_info, user:) visit settings_payments_path expect(page).not_to have_alert(text: "You must set up credit card purchases above before enabling customers to pay with PayPal.") expect(page).not_to have_link(text: "Connect with Paypal", inert: true) end it "keeps the PayPal Connect button enabled even when user does not have either bank account or payment address set up" do creator = create(:user, payment_address: nil) create(:user_compliance_info, user: creator) login_as creator visit settings_payments_path expect(page).to have_link(text: "Connect with Paypal", inert: false) end it "keeps the PayPal Connect button enabled when user has stripe account connected" do creator = create(:user, payment_address: nil) create(:user_compliance_info, user: creator) create(:merchant_account_stripe_connect, user: creator) creator.check_merchant_account_is_linked = true creator.save! expect(creator.has_stripe_account_connected?).to be true login_as creator visit settings_payments_path expect(page).to have_link(text: "Connect with Paypal", inert: false) end it "keeps the PayPal Connect button enabled when user has bank account connected" do creator = create(:user, payment_address: nil) create(:user_compliance_info, user: creator) create(:ach_account, user: creator) login_as creator visit settings_payments_path expect(page).to have_link(text: "Connect with Paypal", inert: false) end it "keeps the PayPal Connect button enabled when user has debit card connected" do creator = create(:user, payment_address: nil) create(:user_compliance_info, user: creator) create(:card_bank_account, user: creator) login_as creator visit settings_payments_path expect(page).to have_link(text: "Connect with Paypal", inert: false) end it "keeps the PayPal Connect button disabled and shows the eligibility requirements when the user is not eligible" do create(:user_compliance_info, user:) allow_any_instance_of(User).to receive(:paypal_connect_allowed?).and_return(false) visit settings_payments_path expect(page).to have_link(text: "Connect with Paypal", inert: true) expect(page).to have_text("You must meet the following requirements in order to connect a PayPal account:") expect(page).to have_text("Your account must be marked as compliant") expect(page).to have_text("You must have earned at least $100") expect(page).to have_text("You must have received at least one successful payout") end context "when logged user has role admin" do let(:seller) { create(:named_seller) } include_context "with switching account to user as admin for seller" it "does not Connect with Paypal button link" do visit settings_payments_path expect(page).not_to have_link("Connect with Paypal") end end end describe "VAT section" do let(:user) { create(:user, name: "Gum") } before do login_as user end context "when user cannot disable vat" do before do allow_any_instance_of(User).to receive(:can_disable_vat?).and_return(false) end it "doesn't render section" do visit settings_payments_path expect(page).not_to have_text("VAT") end end end describe("Payout Information Collection", type: :system, js: true) do before do @user = create(:named_user, payment_address: nil) user_compliance_info = @user.fetch_or_build_user_compliance_info user_compliance_info.country = "United States" user_compliance_info.save! login_as @user end it "allows the (US based) creator to enter their kyc and ach information and it'll save it properly" do visit settings_payments_path fill_in("First name", with: "barnabas") fill_in("Last name", with: "barnabastein") fill_in("Address", with: "address_full_match") fill_in("City", with: "barnabasville") select("California", from: "State") fill_in("ZIP code", with: "12345") fill_in("Phone number", with: "(502) 254-1982") fill_in("Pay to the order of", with: "barnabas ngagy") fill_in("Routing number", with: "110000000") fill_in("Account number", with: "123456781") fill_in("Confirm account number", with: "123456781") expect(page).to have_content("Must exactly match the name on your bank account") expect(page).to have_content("Payouts will be made in USD.") select("1", from: "Day") select("January", from: "Month") select("1980", from: "Year") fill_in("Last 4 digits of SSN", with: "1235") click_on("Update settings") expect(page).to have_alert("You must use a test bank account number. Try 000123456789 or see more options at https://stripe.com/docs/connect/testing#account-numbers.") fill_in("Account number", with: "000123456789") fill_in("Confirm account number", with: "000123456789") click_on("Update settings") expect(page).to have_alert(text: "Thanks! You're all set.") expect(page).to have_content("Routing number") compliance_info = @user.alive_user_compliance_info expect(compliance_info.first_name).to eq("barnabas") expect(compliance_info.last_name).to eq("barnabastein") expect(compliance_info.street_address).to eq("address_full_match") expect(compliance_info.city).to eq("barnabasville") expect(compliance_info.state).to eq("CA") expect(compliance_info.zip_code).to eq("12345") expect(compliance_info.phone).to eq("+15022541982") expect(compliance_info.birthday).to eq(Date.new(1980, 1, 1)) expect(compliance_info.individual_tax_id.decrypt("1234")).to eq("1235") expect(@user.active_ach_account.routing_number).to eq("110000000") expect(@user.active_ach_account.account_number_visual).to eq("******6789") expect(@user.stripe_account).to be_present end it "allows the creator to switch to debit card as payout method" do visit settings_payments_path choose "Debit Card" fill_in("First name", with: "barnabas") fill_in("Last name", with: "barnabastein") fill_in("Address", with: "123 barnabas st") fill_in("City", with: "barnabasville") select "California", from: "State" fill_in("ZIP code", with: "10110") select("1", from: "Day") select("January", from: "Month") select("1901", from: "Year") fill_in("Last 4 digits of SSN", with: "0000") fill_in("Phone number", with: "5022-541-982") within_fieldset "Card information" do within_frame do fill_in "Card number", with: "5200828282828210" fill_in "MM / YY", with: StripePaymentMethodHelper::EXPIRY_MMYY fill_in "CVC", with: "123" end end click_on "Update settings" expect(page).to have_alert(text: "Thanks! You're all set.") compliance_info = @user.reload.alive_user_compliance_info expect(compliance_info.first_name).to eq("barnabas") expect(compliance_info.last_name).to eq("barnabastein") expect(compliance_info.street_address).to eq("123 barnabas st") expect(compliance_info.city).to eq("barnabasville") expect(compliance_info.state).to eq("CA") expect(compliance_info.zip_code).to eq("10110") expect(compliance_info.birthday).to eq(Date.new(1901, 1, 1)) expect(compliance_info.individual_tax_id.decrypt("1234")).to eq("0000") bank_account = @user.bank_accounts.alive.last expect(bank_account.type).to eq("CardBankAccount") expect(bank_account.account_number_last_four).to eq("8210") end it "allows the creator to update other info when they have a debit card connected" do creator = create(:user, payment_address: nil) create(:user_compliance_info, user: creator, phone: "+15022541982") create(:card_bank_account, user: creator) expect(creator.payout_frequency).to eq(User::PayoutSchedule::WEEKLY) login_as creator visit settings_payments_path expect(page).to have_select("Schedule", selected: "Weekly") select "Monthly", from: "Schedule" click_on "Update settings" expect(page).to have_alert(text: "Thanks! You're all set.") expect(creator.reload.payout_frequency).to eq(User::PayoutSchedule::MONTHLY) refresh expect(page).to have_select("Schedule", selected: "Monthly") end it "allows the creator to connect their Stripe account if they are from Brazil" do visit settings_payments_path expect(page).not_to have_field("Stripe") create(:user_compliance_info, user: @user, country: "Brazil") Feature.activate_user(:merchant_migration, @user) refresh choose "Stripe" expect(page).to have_content("This feature is available in all countries where Stripe operates, except India, Indonesia, Malaysia, Mexico, Philippines, and Thailand.") expect(page).to have_link("all countries where Stripe operates", href: "https://stripe.com/en-in/global") OmniAuth.config.test_mode = true OmniAuth.config.mock_auth[:stripe_connect] = OmniAuth::AuthHash.new JSON.parse(File.open("#{Rails.root}/spec/support/fixtures/stripe_connect_omniauth.json").read) click_on "Connect with Stripe" expect(page).to have_alert(text: "You have successfully connected your Stripe account!") expect(page).to have_button("Disconnect") end it "allows the creator to connect their Stripe account if they have can_connect_stripe flag enabled" do visit settings_payments_path expect(page).not_to have_field("Stripe") @user.update!(can_connect_stripe: true) refresh choose "Stripe" expect(page).to have_content("This feature is available in all countries where Stripe operates, except India, Indonesia, Malaysia, Mexico, Philippines, and Thailand.") expect(page).to have_link("all countries where Stripe operates", href: "https://stripe.com/en-in/global") OmniAuth.config.test_mode = true OmniAuth.config.mock_auth[:stripe_connect] = OmniAuth::AuthHash.new JSON.parse(File.open("#{Rails.root}/spec/support/fixtures/stripe_connect_omniauth.json").read) click_on "Connect with Stripe" expect(page).to have_alert(text: "You have successfully connected your Stripe account!") expect(page).to have_button("Disconnect") end it "allows the creator to disconnect their Stripe account" do create(:merchant_account_stripe_connect, user: @user) @user.check_merchant_account_is_linked = true @user.save! expect(@user.has_stripe_account_connected?).to be true visit settings_payments_path click_on "Disconnect Stripe account" expect(page).to have_content("Pay to the order of") expect(@user.reload.has_stripe_account_connected?).to be false expect(@user.stripe_connect_account).to be nil end it "does not allow the creator to disconnect their Stripe account if it is in use" do create(:merchant_account_stripe_connect, user: @user) @user.check_merchant_account_is_linked = true @user.save! expect(@user.has_stripe_account_connected?).to be true allow_any_instance_of(User).to receive(:stripe_disconnect_allowed?).and_return false visit settings_payments_path expect(page).to have_content("You cannot disconnect your Stripe account because it is being used for active subscription or preorder payments.") expect(find_button("Disconnect Stripe account", disabled: true)[:disabled]).to eq "true" end it "does not allow saving placeholder state values" do visit settings_payments_path fill_in("First name", with: "barnabas") fill_in("Last name", with: "barnabastein") fill_in("Address", with: "address_full_match") fill_in("City", with: "barnabasville") select("State", from: "State") fill_in("ZIP code", with: "12345") fill_in("Phone number", with: "(502) 254-1982") fill_in("Pay to the order of", with: "barnabas ngagy") fill_in("Routing number", with: "110000000") fill_in("Account number", with: "000123456789") fill_in("Confirm account number", with: "000123456789") select("1", from: "Day") select("January", from: "Month") select("1980", from: "Year") fill_in("Last 4 digits of SSN", with: "1235") expect do click_on("Update settings") expect(page).to have_status(text: "Please select a valid state or province.") end.to_not change { @user.alive_user_compliance_info.reload.state } select("California", from: "State") expect do click_on("Update settings") wait_for_ajax expect(page).to have_alert(text: "Thanks! You're all set.") end.to change { @user.alive_user_compliance_info.reload.state }.to("CA") end it "does not allow saving placeholder state values for business" do visit settings_payments_path choose("Business") fill_in("Legal business name", with: "Acme") select("LLC", from: "Type") find_field("Address", match: :first).set("123 North street") find_field("City", match: :first).set("Barnesville") find_field("State", match: :first).select("State") find_field("ZIP code", match: :first).set("12345") fill_in("Business phone number", with: "15052229876") fill_in("Business Tax ID (EIN, or SSN for sole proprietors)", with: "123456789") fill_in("First name", with: "barnabas") fill_in("Last name", with: "barnabastein") all('input[id$="creator-street-address"]').last.set("address_full_match") all('input[id$="creator-city"]').last.set("barnabasville") all('select[id$="creator-state"]').last.select("California") all('input[id$="creator-zip-code"]').last.set("12345") fill_in("Phone number", with: "(502) 254-1982") fill_in("Pay to the order of", with: "barnabas ngagy") fill_in("Routing number", with: "110000000") fill_in("Account number", with: "000123456789") fill_in("Confirm account number", with: "000123456789") select("1", from: "Day") select("January", from: "Month") select("1980", from: "Year") fill_in("Last 4 digits of SSN", with: "1235") expect do click_on("Update settings") expect(page).to have_status(text: "Please select a valid state or province.") end.to_not change { @user.alive_user_compliance_info.reload.business_state } find_field("State", match: :first).select("California") expect do click_on("Update settings") wait_for_ajax expect(page).to have_alert(text: "Thanks! You're all set.") end.to change { @user.alive_user_compliance_info.reload.business_state }.to("CA") end describe "US-based creator with information set" do before do create(:ach_account_stripe_succeed, user: @user) old_user_compliance_info = @user.alive_user_compliance_info new_user_compliance_info = old_user_compliance_info.dup new_user_compliance_info.first_name = "barnabas" new_user_compliance_info.last_name = "barnabastein" new_user_compliance_info.street_address = "address_full_match" new_user_compliance_info.city = "barnabasville" new_user_compliance_info.state = "CA" new_user_compliance_info.zip_code = "12345" new_user_compliance_info.phone = "+15022541982" new_user_compliance_info.birthday = Date.new(1980, 1, 1) new_user_compliance_info.individual_tax_id = "1234" ActiveRecord::Base.transaction do old_user_compliance_info.mark_deleted! new_user_compliance_info.save! end end it "allows the creator to edit their personal info without changing their ach account" do visit settings_payments_path old_ach_account = @user.active_ach_account fill_in("Address", with: "address_full_match") click_on("Update settings") expect(page).to have_alert(text: "Thanks! You're all set.") compliance_info = @user.alive_user_compliance_info expect(compliance_info.first_name).to eq("barnabas") expect(compliance_info.last_name).to eq("barnabastein") expect(compliance_info.street_address).to eq("address_full_match") expect(compliance_info.city).to eq("barnabasville") expect(compliance_info.state).to eq("CA") expect(compliance_info.zip_code).to eq("12345") expect(compliance_info.birthday).to eq(Date.new(1980, 1, 1)) expect(compliance_info.individual_tax_id.decrypt("1234")).to eq("1234") expect(@user.active_ach_account).to eq(old_ach_account) end it "allows the creator to edit their personal info that is locked at Stripe after account verification, and displays an error" do error_message = "You cannot change legal_entity[first_name] via API if an account is verified. Please contact us via https://support.stripe.com/contact if you need to change the information associated with this account." param = "legal_entity[first_name]" allow(StripeMerchantAccountManager).to receive(:handle_new_user_compliance_info).and_raise(Stripe::InvalidRequestError.new(error_message, param)) old_ach_account = @user.active_ach_account @user.merchant_accounts << create(:merchant_account, charge_processor_verified_at: Time.current) visit settings_payments_path expect(page).to have_alert(visible: false) fill_in("First name", with: "barny") click_on("Update settings") within(:alert, text: "Your account could not be updated.") compliance_info = @user.alive_user_compliance_info expect(compliance_info.first_name).to eq("barnabas") expect(compliance_info.last_name).to eq("barnabastein") expect(compliance_info.street_address).to eq("address_full_match") expect(compliance_info.city).to eq("barnabasville") expect(compliance_info.state).to eq("CA") expect(compliance_info.zip_code).to eq("12345") expect(compliance_info.birthday).to eq(Date.new(1980, 1, 1)) expect(compliance_info.individual_tax_id.decrypt("1234")).to eq("1234") expect(@user.active_ach_account).to eq(old_ach_account) end it "allows the creator to see and edit their ach account" do @user.mark_compliant!(author_id: @user.id) visit settings_payments_path expect(page).to have_field("Routing number", with: "110000000", disabled: true) expect(page).to have_field("Account number", with: "******6789", disabled: true) click_on("Change account") fill_in("Pay to the order of", with: "barnabas ngagy") fill_in("Routing number", with: "110000000") fill_in("Account number", with: "000111111116") fill_in("Confirm account number", with: "000111111116") click_on("Update settings") expect(page).to have_alert(text: "Thanks! You're all set.") compliance_info = @user.alive_user_compliance_info expect(compliance_info.first_name).to eq("barnabas") expect(compliance_info.last_name).to eq("barnabastein") expect(compliance_info.street_address).to eq("address_full_match") expect(compliance_info.city).to eq("barnabasville") expect(compliance_info.state).to eq("CA") expect(compliance_info.zip_code).to eq("12345") expect(compliance_info.birthday).to eq(Date.new(1980, 1, 1)) expect(compliance_info.individual_tax_id.decrypt("1234")).to eq("1234") expect(@user.active_ach_account.routing_number).to eq("110000000") expect(@user.active_ach_account.account_number_visual).to eq("******1116") end it "does not show PayPal as a payout method as bank payouts are supported" do stub_const("GUMROAD_ADMIN_ID", create(:admin_user).id) visit settings_payments_path expect(page).not_to have_field("PayPal") end it "allows the creator to update the name on their account" do @user.mark_compliant!(author_id: @user.id) visit settings_payments_path fill_in "Pay to the order of", with: "Gumhead Moneybags" click_on("Update settings") expect(page).to have_alert(text: "Thanks! You're all set.") expect(@user.active_bank_account.account_holder_full_name).to eq("Gumhead Moneybags") end it "displays the Stripe Connect embedded verification banner" do user = create(:user, username: nil, payment_address: nil) create(:user_compliance_info, user:, birthday: Date.new(1901, 1, 2)) create(:ach_account_stripe_succeed, user:) create(:tos_agreement, user:) StripeMerchantAccountManager.create_account(user, passphrase: "1234") create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Individual::STRIPE_IDENTITY_DOCUMENT_ID) expect(user.user_compliance_info_requests.requested. where(field_needed: UserComplianceInfoFields::Individual::STRIPE_IDENTITY_DOCUMENT_ID).count).to eq(1) login_as user visit settings_payments_path expect(page).to have_selector("iframe[src*='connect-js.stripe.com']") end it "always shows the verification section with success message when verification is not needed" do user = create(:user, username: nil, payment_address: nil) create(:user_compliance_info, user:, birthday: Date.new(1901, 1, 2)) create(:ach_account_stripe_succeed, user:) create(:tos_agreement, user:) StripeMerchantAccountManager.create_account(user, passphrase: "1234") expect(user.user_compliance_info_requests.requested.count).to eq(0) login_as user visit settings_payments_path expect(page).to have_section("Verification") expect(page).to have_status(text: "Your account details have been verified!") end it "does not show the verification section if Stripe account is not active" do user = create(:user, username: nil, payment_address: nil) create(:user_compliance_info, user:, birthday: Date.new(1901, 1, 2)) create(:ach_account_stripe_succeed, user:) create(:tos_agreement, user:) merchant_account = StripeMerchantAccountManager.create_account(user, passphrase: "1234") create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Individual::TAX_ID) expect(user.user_compliance_info_requests.requested. where(field_needed: UserComplianceInfoFields::Individual::TAX_ID).count).to eq(1) login_as user visit settings_payments_path expect(page).to have_selector("iframe[src*='connect-js.stripe.com']") merchant_account.mark_deleted! visit settings_payments_path expect(page).to have_status(text: "Your account details have been verified!") end context "when the creator has a business account" do let(:user) { create(:user, username: nil, payment_address: nil) } before do create(:user_compliance_info_business, user:, birthday: Date.new(1901, 1, 2)) create(:ach_account_stripe_succeed, user:) create(:tos_agreement, user:) end let!(:merchant_account) { StripeMerchantAccountManager.create_account(user, passphrase: "1234") } before do expect(user.merchant_accounts.alive.count).to eq(1) create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Business::STRIPE_COMPANY_DOCUMENT_ID) expect(user.user_compliance_info_requests.requested. where(field_needed: UserComplianceInfoFields::Business::STRIPE_COMPANY_DOCUMENT_ID).count).to eq(1) login_as user end it "renders the account selector" do visit settings_payments_path within_section("Payout method", section_element: :section) do expect(page).to have_text("Account type") expect(page).to have_radio_button("Business", checked: true) end end it "allows the creator to switch to individual account" do expect(user.alive_user_compliance_info.is_business).to be(true) visit settings_payments_path within_section("Payout method", section_element: :section) do expect(page).to have_text("Account type") expect(page).to have_radio_button("Business", checked: true) choose "Individual" fill_in("Phone number", with: "(502) 254-1982") end expect do expect do click_on "Update settings" wait_for_ajax expect(page).to have_alert(text: "Thanks! You're all set.") end.to change { user.reload.user_compliance_infos.count }.by(1) end.to change { user.alive_user_compliance_info.is_business }.to be(false) end end it "does not allow saving a P.O. Box address" do visit settings_payments_path choose "Individual" fill_in "Street address", with: "P.O. Box 123, Smith street" expect do click_on "Update settings" expect(page).to have_status(text: "We require a valid physical US address. We cannot accept a P.O. Box as a valid address.") end.to_not change { @user.alive_user_compliance_info.reload.street_address } fill_in "Street address", with: "123, Smith street" expect do click_on "Update settings" wait_for_ajax expect(page).to have_alert(text: "Thanks! You're all set.") end.to change { @user.alive_user_compliance_info.reload.street_address }.to("123, Smith street") choose "Business" fill_in "Legal business name", with: "Acme" select "LLC", from: "Type" find_field("Address", match: :first).set("PO Box 123 North street") find_field("City", match: :first).set("Barnesville") find_field("State", match: :first).select("California") find_field("ZIP code", match: :first).set("12345") fill_in "Business phone number", with: "15052229876" fill_in "Business Tax ID (EIN, or SSN for sole proprietors)", with: "123456789" expect do click_on "Update settings" expect(page).to have_status(text: "We require a valid physical US address. We cannot accept a P.O. Box as a valid address.") end.to_not change { @user.alive_user_compliance_info.reload.business_street_address } find_field("Address", match: :first).set("123 North street") expect do click_on "Update settings" wait_for_ajax expect(page).to have_alert(text: "Thanks! You're all set.") sleep 0.5 # Since the previous Alerts takes time to disappear, checking alert returns early before the api call is complete end.to change { @user.alive_user_compliance_info.reload.business_street_address }.to("123 North street") fill_in "Street address", with: "po box 123 smith street" expect do click_on "Update settings" expect(page).to have_status(text: "We require a valid physical US address. We cannot accept a P.O. Box as a valid address.") end.to_not change { @user.alive_user_compliance_info.reload.street_address } end end describe "US business with non-US representative" do before do old_user_compliance_info = @user.alive_user_compliance_info new_user_compliance_info = old_user_compliance_info.dup new_user_compliance_info.country = "United States" ActiveRecord::Base.transaction do old_user_compliance_info.mark_deleted! new_user_compliance_info.save! end expect(@user.active_bank_account).to be nil expect(@user.stripe_account).to be nil end it "allows to enter bank account details" do visit settings_payments_path choose "Business" fill_in("Legal business name", with: "US LLC with Brazilian rep") select("LLC", from: "Type") find_field("Address", match: :first).set("address_full_match") find_field("City", match: :first).set("NY") find_field("State", match: :first).select("New York") find_field("ZIP code", match: :first).set("10110") fill_in("Business phone number", with: "5052426789") fill_in("Business Tax ID (EIN, or SSN for sole proprietors)", with: "000000000") fill_in("First name", with: "Brazilian") fill_in("Last name", with: "Creator") all('select[id$="creator-country"]').last.select("Brazil") all('input[id$="creator-street-address"]').last.set("address_full_match") all('input[id$="creator-city"]').last.set("RDJ") all('select[id$="creator-state"]').last.select("Rio de Janeiro") find_field("Postal code").set("1001001") fill_in("Phone number", with: "987654321") fill_in("Cadastro de Pessoas Físicas (CPF)", with: "000.000.000-00") select("1", from: "Day") select("January", from: "Month") select("1980", from: "Year") fill_in("Pay to the order of", with: "US LLC Brazilian Rep") fill_in("Routing number", with: "110000000") fill_in("Account number", with: "000123456789") fill_in("Confirm account number", with: "000123456789") expect(page).to have_content("Must exactly match the name on your bank account") expect(page).to have_content("Payouts will be made in USD.") click_on("Update settings") expect(page).to have_alert(text: "Thanks! You're all set.") expect(page).to have_content("Routing number") compliance_info = @user.alive_user_compliance_info expect(compliance_info.is_business).to be true expect(compliance_info.business_name).to eq("US LLC with Brazilian rep") expect(compliance_info.business_street_address).to eq("address_full_match") expect(compliance_info.business_city).to eq("NY") expect(compliance_info.business_state).to eq("NY") expect(compliance_info.business_country).to eq("United States") expect(compliance_info.business_zip_code).to eq("10110") expect(compliance_info.business_phone).to eq("+15052426789") expect(compliance_info.business_type).to eq("llc") expect(compliance_info.business_tax_id.decrypt("1234")).to eq("000000000") expect(compliance_info.first_name).to eq("Brazilian") expect(compliance_info.last_name).to eq("Creator") expect(compliance_info.street_address).to eq("address_full_match") expect(compliance_info.city).to eq("RDJ") expect(compliance_info.state).to eq("RJ") expect(compliance_info.country).to eq("Brazil") expect(compliance_info.zip_code).to eq("1001001") expect(compliance_info.phone).to eq("+55987654321") expect(compliance_info.birthday).to eq(Date.new(1980, 1, 1)) expect(@user.reload.active_bank_account.routing_number).to eq("110000000") expect(@user.active_bank_account.send(:account_number_decrypted)).to eq("000123456789") expect(@user.stripe_account.charge_processor_merchant_id).to be_present end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/emails/create_spec.rb
spec/requests/emails/create_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Email Creation Flow", :js, type: :system) do include EmailHelpers let(:seller) { create(:named_seller) } before do allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE) create(:merchant_account_stripe_connect, user: seller) create(:payment_completed, user: seller) end include_context "with switching account to user as admin for seller" it "creates a product-type email with images and attachments" do product = create(:product, name: "Sample product", user: seller) another_product = create(:product, name: "Another product", user: seller) create(:purchase, link: product) create(:purchase, link: product, email: "john@example.com") create(:purchase, link: another_product, email: "john@example.com") create(:active_follower, user: product.user) visit emails_path wait_for_ajax click_on "New email", match: :first wait_for_ajax expect(page).to have_content("New email") # Ensure that the "Everyone" audience type is selected by default expect(page).to have_radio_button "Everyone", checked: true expect(page).to have_text("Audience 3 / 3", normalize_ws: true) # It updates the audience count when the audience type is changed choose "Customers only" wait_for_ajax expect(page).to have_text("Audience 2 / 3", normalize_ws: true) # It shows the correct options for bought/not bought filters and updates the audience count when those are changed find(:combo_box, "Bought").click expect(page).to have_combo_box("Bought", expanded: true, with_options: ["Sample product", "Another product"]) select_combo_box_option "Sample product", from: "Bought" wait_for_ajax expect(page).to have_text("Audience 2 / 3", normalize_ws: true) select_combo_box_option "Another product", from: "Has not yet bought" wait_for_ajax expect(page).to have_text("Audience 1 / 3", normalize_ws: true) fill_in "Paid more than", with: "1" fill_in "Paid less than", with: "10" fill_in "After", with: "01-07-2024" fill_in "Before", with: "05-07-2024" within :fieldset, "After" do expect(page).to have_text("00:00 #{Time.now.in_time_zone(seller.timezone).strftime("%Z")}") end within :fieldset, "Before" do expect(page).to have_text("11:59 #{Time.now.in_time_zone(seller.timezone).strftime("%Z")}") end select "Canada", from: "From" wait_for_ajax expect(page).to have_text("Audience 0 / 3", normalize_ws: true) expect(page).to have_checked_field("Allow comments") uncheck "Allow comments" fill_in "Title", with: "Hello" set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Hello, world!") select_disclosure "Insert" do click_on "Button" end within_modal do fill_in "Enter text", with: "Click me" fill_in "Enter URL", with: "https://example.com/button" click_on "Add button" end # Allows embedding images in the email body attach_file(file_fixture("test.jpg")) do click_on "Insert image" end wait_for_ajax # Allows attaching files to the email upload_attachment("thing.mov") upload_attachment("test.mp4") within find_attachment("test") do click_on "Edit" attach_file("Add subtitles", Rails.root.join("spec/support/fixtures/sample.srt"), visible: false) end # Allows disabling file downloads when the attachments contain streamable files expect(page).to have_unchecked_field("Disable file downloads (stream only)") check "Disable file downloads (stream only)" expect(page).to have_button("Save", disabled: false) click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Email created!") installment = Installment.last expect(installment.name).to eq("Hello") expect(installment.message).to include("<p>Hello, world!</p>") expect(installment.message).to have_link("Click me", href: "https://example.com/button") image_cdn_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{ActiveStorage::Blob.last.key}" expect(installment.message).to include(%Q(<img src="#{image_cdn_url}")) expect(installment.product_type?).to be(true) expect(installment.link).to eq(product) expect(installment.base_variant).to be_nil expect(installment.seller).to eq(seller) expect(installment.published?).to be(false) expect(installment.ready_to_publish?).to be(false) expect(installment.bought_products).to eq([product.unique_permalink]) expect(installment.bought_variants).to be_nil expect(installment.not_bought_products).to eq([another_product.unique_permalink]) expect(installment.not_bought_variants).to be_nil expect(installment.affiliate_products).to be_nil expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) expect(installment.paid_more_than_cents).to eq(100) expect(installment.paid_less_than_cents).to eq(1000) expect(installment.created_after).to be_present expect(installment.created_before).to be_present expect(installment.bought_from).to eq("Canada") expect(installment.allow_comments?).to be(false) expect(installment.product_files.alive.map(&:s3_filename)).to eq(["thing.mov", "test.mp4"]) subtitle = installment.product_files.alive.last.subtitle_files.alive.sole expect(subtitle.url).to include("sample.srt") expect(subtitle.language).to include("English") expect(installment.stream_only?).to be(true) # It redirects to the edit page on creating the email and shows the correct data expect(page).to have_current_path("#{emails_path}/#{installment.external_id}/edit") expect(page).to have_text("Edit email") expect(page).to have_radio_button "Customers only", checked: true within :fieldset, "Bought" do expect(page).to have_button("Sample product") end expect(page).to have_unchecked_field("Allow comments") expect(page).to have_field("Title", with: "Hello") within("[aria-label='Email message']") do expect(page).to have_text("Hello, world!") expect(page).to have_link("Click me", href: "https://example.com/button") expect(page).to have_selector("img[src*='#{image_cdn_url}']") end expect(page).to have_attachment(name: "thing") within find_attachment("test") do click_on "Edit" expect(page).to have_attachment(name: "sample") end expect(page).to have_checked_field("Disable file downloads (stream only)") # On cancel, it redirects back to the drafts tab since the email is a draft click_on "Cancel" expect(page).to have_current_path("#{emails_path}/drafts") # Ensures that the just-created email is shown in the "Drafts" tab expect(page).to have_table_row({ "Subject" => "Hello", "Sent to" => "Customers of Sample product", "Audience" => "0" }) find(:table_row, { "Subject" => "Hello" }).click click_on "Edit" expect(page).to have_attachment(name: "thing") expect(page).to have_checked_field("Disable file downloads (stream only)") end it "creates a variant-type email" do product = create(:product, name: "Sample product", user: seller) variant_category = create(:variant_category, link: product) variant1 = create(:variant, name: "V1", variant_category:) create(:variant, name: "V2", variant_category:) create(:purchase, seller:, link: product, country: "Italy", variant_attributes: [variant1]) visit emails_path click_on "New email", match: :first choose "Customers only" find(:combo_box, "Bought").click # Ensure that the variant options are shown in bought/not-bought filters expect(page).to have_combo_box("Bought", expanded: true, with_options: ["Sample product", "Sample product - V1", "Sample product - V2"]) # Select a variant option select_combo_box_option "Sample product - V1", from: "Bought" expect(page).to have_text("Audience 1 / 1", normalize_ws: true) fill_in "Title", with: "Hello" set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Hello, world!") sleep 0.5 # wait for the message editor to update click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Email created!") installment = Installment.last expect(installment.name).to eq("Hello") expect(installment.message).to include("<p>Hello, world!</p>") expect(installment.variant_type?).to be(true) expect(installment.link).to eq(product) expect(installment.base_variant).to eq(variant1) expect(installment.seller).to eq(seller) expect(installment.published?).to be(false) expect(installment.ready_to_publish?).to be(false) expect(installment.bought_products).to be_nil expect(installment.bought_variants).to eq([variant1.external_id]) expect(installment.not_bought_products).to be_nil expect(installment.not_bought_variants).to be_nil expect(installment.affiliate_products).to be_nil expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) expect(installment.paid_more_than_cents).to be_nil expect(installment.paid_less_than_cents).to be_nil expect(installment.created_after).to be_nil expect(installment.created_before).to be_nil expect(installment.bought_from).to be_nil expect(installment.allow_comments?).to be(true) expect(installment.product_files).to be_empty expect(page).to have_current_path("#{emails_path}/#{installment.external_id}/edit") click_on "Cancel" expect(page).to have_current_path("#{emails_path}/drafts") expect(page).to have_table_row({ "Subject" => "Hello", "Sent to" => "Customers of Sample product - V1", "Audience" => "1" }) end it "creates a audience-type email" do product = create(:product, name: "Sample product", user: seller) create(:product, user: product.user, name: "Another product") create(:purchase, link: product) create_list(:active_follower, 2, user: product.user) visit emails_path click_on "New email", match: :first expect(page).to have_radio_button("Everyone", checked: true) expect(page).to have_text("Audience 3 / 3", normalize_ws: true) expect(page).to have_checked_field("Send email") expect(page).to have_checked_field("Post to profile") # Audience type does not show the "Bought", "Paid more/less than" and "From" filters expect(page).to_not have_combo_box("Bought") expect(page).to have_combo_box("Has not yet bought") expect(page).to_not have_combo_box(fieldset: "Affiliated 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("After", with: "") expect(page).to have_input_labelled("Before", with: "") expect(page).to_not have_select("From") fill_in "Title", with: "Hello" set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Hello, world!") sleep 0.5 # wait for the message editor to update click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Email created!") installment = Installment.last expect(installment.name).to eq("Hello") expect(installment.message).to include("<p>Hello, world!</p>") expect(installment.audience_type?).to be(true) expect(installment.link).to be_nil expect(installment.seller).to eq(seller) expect(installment.published?).to be(false) expect(installment.ready_to_publish?).to be(false) expect(installment.bought_products).to be_nil expect(installment.bought_variants).to be_nil expect(installment.not_bought_products).to be_nil expect(installment.not_bought_variants).to be_nil expect(installment.affiliate_products).to be_nil expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) expect(installment.paid_more_than_cents).to be_nil expect(installment.paid_less_than_cents).to be_nil expect(installment.created_after).to be_nil expect(installment.created_before).to be_nil expect(installment.bought_from).to be_nil expect(installment.allow_comments?).to be(true) expect(installment.product_files).to be_empty expect(page).to have_current_path("#{emails_path}/#{installment.external_id}/edit") click_on "Cancel" expect(page).to have_current_path("#{emails_path}/drafts") expect(page).to have_table_row({ "Subject" => "Hello", "Sent to" => "Your customers and followers", "Audience" => "3" }) end it "creates a follower-type email" do product = create(:product, name: "Sample product", user: seller) create(:product, user: product.user, name: "Another product") create(:purchase, link: product) create_list(:active_follower, 2, user: product.user) visit emails_path click_on "New email", match: :first choose "Followers only" expect(page).to have_text("Audience 2 / 3", normalize_ws: true) expect(page).to_not have_field("Paid more than") expect(page).to_not have_field("Paid less than") fill_in "Title", with: "Hello" set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Hello, world!") sleep 0.5 # wait for the message editor to update click_on "Save" expect(page).to have_alert(text: "Email created!") installment = Installment.last expect(installment.name).to eq("Hello") expect(installment.message).to include("<p>Hello, world!</p>") expect(installment.follower_type?).to be(true) expect(page).to have_current_path("#{emails_path}/#{installment.external_id}/edit") click_on "Cancel" expect(page).to have_current_path("#{emails_path}/drafts") expect(page).to have_table_row({ "Subject" => "Hello", "Sent to" => "Your followers", "Audience" => "2" }) end it "creates an affiliate-type email" do product = create(:product, name: "Sample product", user: seller) another_product = create(:product, name: "Another product", user: seller) create_list(:purchase, 2, link: product) affiliate = create(:direct_affiliate, seller: product.user) affiliate.products << product visit emails_path click_on "New email", match: :first # Ensure that the audience count is correct when the "Affiliates only" audience type is selcted choose "Affiliates only" expect(page).to have_text("Audience 1 / 3", normalize_ws: true) find(:combo_box, fieldset: "Affiliated products").click expect(page).to have_combo_box(fieldset: "Affiliated products", expanded: true, with_options: ["Sample product", "Another product"]) within(:fieldset, "Affiliated products") do expect(page).to_not have_button("Sample product") expect(page).to_not have_button("Another product") end # Ensure that the "All products" checkbox under the "Affiliated products" filter section works correctly expect(page).to have_unchecked_field("All products") check "All products" within(:fieldset, "Affiliated products") do expect(page).to have_button("Sample product") expect(page).to have_button("Another product") end wait_for_ajax # Unselecting a selected option from "Affiliated products" automatically unchecks "All products" within(:fieldset, "Affiliated products") do click_on "Sample product" expect(page).to_not have_button("Sample product") expect(page).to have_button("Another product") end expect(page).to have_unchecked_field("All products") # Ensure that the updated audience count is correct wait_for_ajax expect(page).to have_text("Audience 0 / 3", normalize_ws: true) check "All products" wait_for_ajax expect(page).to have_text("Audience 1 / 3", normalize_ws: true) # Check presence of other filters and make some changes expect(page).to_not have_combo_box("Bought") expect(page).to_not have_combo_box("Has not yet bought") expect(page).to_not have_field("Paid more than", with: "") expect(page).to_not have_field("Paid less than", with: "") expect(page).to have_field("After") expect(page).to have_field("Before") expect(page).to_not have_select("From") fill_in "Title", with: "Hello" set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Hello, world!") sleep 0.5 # wait for the message editor to update click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Email created!") installment = Installment.last expect(installment.name).to eq("Hello") expect(installment.message).to include("<p>Hello, world!</p>") expect(installment.affiliate_type?).to be(true) expect(installment.link).to be_nil expect(installment.seller).to eq(seller) expect(installment.published?).to be(false) expect(installment.ready_to_publish?).to be(false) expect(installment.bought_products).to be_nil expect(installment.bought_variants).to be_nil expect(installment.not_bought_products).to be_nil expect(installment.not_bought_variants).to be_nil expect(installment.affiliate_products).to match_array([product.unique_permalink, another_product.unique_permalink]) expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) expect(installment.paid_more_than_cents).to be_nil expect(installment.paid_less_than_cents).to be_nil expect(installment.created_after).to be_nil expect(installment.created_before).to be_nil expect(installment.bought_from).to be_nil expect(installment.allow_comments?).to be(true) expect(installment.product_files).to be_empty expect(page).to have_current_path("#{emails_path}/#{installment.external_id}/edit") click_on "Cancel" expect(page).to have_current_path("#{emails_path}/drafts") expect(page).to have_table_row({ "Subject" => "Hello", "Sent to" => "Your affiliates", "Audience" => "1" }) end it "does not show archived products" do product = create(:product, name: "Sample product", user: seller) archived_product = create(:product, name: "Archived product", user: seller, archived: true) create(:purchase, link: archived_product) create(:purchase, link: product) create(:audience_member, seller:, affiliates: [{}]) visit emails_path click_on "New email", match: :first choose "Customers only" find(:combo_box, "Bought").click expect(page).to have_combo_box("Bought", expanded: true, with_options: ["Sample product"]) find(:combo_box, "Has not yet bought").click expect(page).to have_combo_box("Has not yet bought", expanded: true, with_options: ["Sample product"]) choose "Affiliates only" find(:combo_box, fieldset: "Affiliated products").click expect(page).to have_combo_box(fieldset: "Affiliated products", expanded: true, with_options: ["Sample product"]) end it "does not upload unsupported file as a subtitle" do visit "#{emails_path}/new" fill_in "Title", with: "Hello" set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Hello, world!") upload_attachment("test.mp4") within find_attachment("test") do click_on "Edit" attach_file("Add subtitles", Rails.root.join("spec/support/fixtures/sample.gif"), visible: false) end expect(page).to have_alert(text: "Invalid file type.") within find_attachment("test") do expect(page).to_not have_attachment(name: "sample") end click_on "Save" expect(page).to have_alert(text: "Email created!") installment = Installment.last expect(installment.product_files.alive.map(&:s3_filename)).to eq(["test.mp4"]) expect(installment.product_files.alive.sole.subtitle_files).to be_empty expect(page).to have_current_path("#{emails_path}/#{installment.external_id}/edit") within find_attachment("test") do expect(page).to_not have_attachment(name: "sample") end end it "auto populates the new email form when URL contains 'product' query parameter" do product = create(:product, user: seller, name: "Sample product") create(:purchase, link: product) visit "#{emails_path}/new?product=#{product.unique_permalink}" wait_for_ajax expect(page).to have_radio_button("Customers only", checked: true) find(:combo_box, "Bought").click within(:fieldset, "Bought") do expect(page).to have_button(product.name) end expect(page).to have_field("Title", with: "Sample product - updated!") within find("[aria-label='Email message']") do expect(page).to have_text("I have recently updated some files associated with Sample product. They're yours for free.") end sleep 0.5 # wait for the message editor to update click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Email created!") installment = Installment.last expect(page).to have_current_path("#{emails_path}/#{installment.external_id}/edit") expect(installment.name).to eq("Sample product - updated!") expect(installment.message).to eq("<p>I have recently updated some files associated with Sample product. They're yours for free.</p>") expect(installment.link).to eq(product) expect(installment.seller).to eq(seller) expect(installment.product_type?).to be(true) expect(installment.bought_products).to eq([product.unique_permalink]) end it "auto populates the new email form when URL contains bundle product related query parameter" do product = create(:product, :bundle, user: seller) create(:purchase, link: product) visit edit_link_path(product.unique_permalink) # Create a draft email from the "Share" tab of a bundle product select_tab "Share" expect(page).to have_checked_field("Customers who have purchased at least one product in the bundle") new_window = window_opened_by { click_on "Draft and send" } within_window new_window do expect(page).to have_text("New email") expect(page).to have_radio_button("Customers only", checked: true) expect(page).to have_checked_field("Send email") expect(page).to have_unchecked_field("Post to profile") find(:combo_box, "Bought").click within(:fieldset, "Bought") do expect(page).to have_button("Bundle Product 1") expect(page).to have_button("Bundle Product 2") end expect(page).to have_field("Title", with: "Introducing Bundle") within find("[aria-label='Email message']") do expect(page).to have_text("Hey there,") expect(page).to have_text("I've put together a bundle of my products that I think you'll love.") expect(page).to have_text("Bundle") expect(page).to have_text("$2 $1", normalize_ws: true) expect(page).to have_text("Included in this bundle") expect(page).to have_link("Bundle Product 1", href: short_link_url(product.bundle_products.first.product, host: DOMAIN)) expect(page).to have_link("Bundle Product 2", href: short_link_url(product.bundle_products.last.product, host: DOMAIN)) expect(page).to have_link("Get your bundle", href: short_link_url(product, host: DOMAIN)) expect(page).to have_text("Thanks for your support!") end sleep 0.5 # wait for the message editor to update click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Email created!") installment = Installment.last expect(installment.name).to eq("Introducing Bundle") message = Capybara.string(installment.message) expect(message).to have_css("p", text: "Hey there,") expect(message).to have_css("p", text: "I've put together a bundle of my products that I think you'll love.") expect(message).to have_css("hr", count: 2) expect(message).to have_css("p strong", text: "Bundle") expect(message).to have_css("p s", text: "$2") expect(message).to have_text("$1") expect(message).to have_text("Included in this bundle") expect(message).to have_css("ul li", count: 2) expect(message).to have_link("Bundle Product 1", href: short_link_url(product.bundle_products.first.product, host: DOMAIN)) expect(message).to have_link("Bundle Product 2", href: short_link_url(product.bundle_products.last.product, host: DOMAIN)) expect(message).to have_css("a.tiptap__button.button.primary", text: "Get your bundle") expect(message).to have_link("Get your bundle", href: short_link_url(product, host: DOMAIN)) expect(message).to have_css("p", text: "Thanks for your support!") expect(installment.link).to be_nil expect(installment.seller).to eq(seller) expect(installment.seller_type?).to be(true) expect(installment.bought_products).to eq(product.bundle_products.flat_map(&:product).map(&:unique_permalink)) expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(false) end new_window.close end it "creates and schedules an email" do product = create(:product, name: "Sample product", user: seller) create(:purchase, link: product) visit emails_path click_on "New email", match: :first expect(page).to have_checked_field("Post to profile") expect(page).to have_checked_field("Send email") fill_in "Title", with: "Hello" set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Hello, world!") sleep 0.5 # wait for the message editor to update # Does not create an email if the schedule date is invalid while scheduling it select_disclosure "Publish" do expect(page).to have_button("Publish now") fill_in "Schedule date", with: "01/01/2021\t04:00PM" click_on "Schedule" end wait_for_ajax expect(page).to have_alert("Please select a date and time in the future.") expect(page).to have_current_path("#{emails_path}/new") expect(Installment.count).to eq(0) # Creates and schedules an email if the schedule date is valid select_disclosure "Publish" do expect(page).to have_button("Publish now") fill_in "Schedule date", with: "01/01/#{Date.today.year.next}\t04:00PM" click_on "Schedule" end wait_for_ajax expect(page).to have_alert("Email successfully scheduled!") expect(page).to have_current_path("#{emails_path}/scheduled") expect(page).to have_table_row({ "Subject" => "Hello" }) expect(Installment.count).to eq(1) installment = Installment.last expect(installment.name).to eq("Hello") expect(installment.message).to eq("<p>Hello, world!</p>") expect(installment.reload.ready_to_publish?).to be(true) expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) expect(installment.published?).to be(false) expect(installment.installment_rule.to_be_published_at).to be_present end it "creates and publishes an email" do product = create(:product, name: "Sample product", user: seller) create(:purchase, link: product) visit emails_path click_on "New email", match: :first expect(page).to have_checked_field("Post to profile") expect(page).to have_checked_field("Send email") expect(page).to_not have_field("Publish date") fill_in "Title", with: "Hello" # Does not create an email if a required field is empty select_disclosure "Publish" do click_on "Publish now" end expect(page).to have_alert(text: "Please include a message as part of the update.") expect(Installment.count).to eq(0) # Creates and publishes an email if all required fields are present and valid set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Hello, world!") sleep 1 # wait for the message editor to update select_disclosure "Publish" do click_on "Publish now" end expect(page).to have_alert(text: "Email successfully sent!") expect(Installment.count).to eq(1) installment = Installment.last expect(installment.name).to eq("Hello") expect(installment.message).to eq("<p>Hello, world!</p>") expect(installment.published?).to be(true) expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) expect(installment.has_been_blasted?).to be(true) expect(installment.ready_to_publish?).to be(false) expect(installment.installment_rule).to be_nil expect(SendPostBlastEmailsJob).to have_enqueued_sidekiq_job(PostEmailBlast.sole.id) # Check that the email is shown under the "Published" tab expect(page).to have_current_path("#{emails_path}/published") expect(page).to have_table_row({ "Subject" => "Hello" }) # Check that the "Send email" is disabled and the publish date is displayed find(:table_row, { "Subject" => "Hello" }).click click_on "Edit" expect(page).to have_checked_field("Send email", disabled: true) expect(page).to have_field("Publish date", with: installment.published_at.to_date.to_s) end it "returns an error while publishing an email if the seller is not eligible to send emails" do allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE - 1) product = create(:product, name: "Sample product", user: seller) create(:purchase, link: product) visit emails_path click_on "New email", match: :first fill_in "Title", with: "Hello" set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Hello, world!") select_disclosure "Publish" do click_on "Publish now" end wait_for_ajax expect(page).to have_alert(text: "You are not eligible to publish or schedule emails. Please ensure you have made at least $100 in sales and received a payout.") expect(Installment.count).to eq(0) end context "when both 'Send email' and 'Post to profile' channels are selected" do it "creates and previews the email" do product = create(:product, name: "Sample product", user: seller) create(:purchase, link: product) allow_any_instance_of(Installment).to receive(:send_preview_email).with(user_with_role_for_seller) visit emails_path click_on "New email", match: :first expect(page).to have_checked_field("Post to profile") expect(page).to have_checked_field("Send email") fill_in "Title", with: "Hello" set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Hello, world!") sleep 0.5 # wait for the message editor to update # Sends the preview email select_disclosure "Preview" do expect(page).to have_button("Preview Post") click_on "Preview Email" end wait_for_ajax expect(page).to have_alert(text: "A preview has been sent to your email.") installment = Installment.last expect(installment.name).to eq("Hello") expect(installment.message).to eq("<p>Hello, world!</p>") expect(installment.published?).to be(false) expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) expect(installment.has_been_blasted?).to be(false) expect(page).to have_current_path("#{emails_path}/#{installment.external_id}/edit") click_on "Cancel" click_on "New email", match: :first # Creates and opens the post in a new window fill_in "Title", with: "My post" set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Hello, world!") sleep 0.5 # wait for the message editor to update new_window = window_opened_by do select_disclosure "Preview" do expect(page).to have_button("Preview Email") click_on "Preview Post" end wait_for_ajax expect(page).to have_alert(text: "Preview link opened.") end within_window new_window do wait_for_ajax expect(page).to have_text("My post") expect(page).to have_text("Hello, world!") end new_window.close installment = Installment.last expect(installment.name).to eq("My post") expect(installment.message).to eq("<p>Hello, world!</p>") expect(installment.published?).to be(false) expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) expect(installment.has_been_blasted?).to be(false) expect(page).to have_current_path("#{emails_path}/#{installment.external_id}/edit") end end context "when either 'Send email' or 'Post to profile' channel is selected" do it "creates and previews the email" do
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/emails/list_spec.rb
spec/requests/emails/list_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Email List", :js, :sidekiq_inline, :elasticsearch_wait_for_refresh, type: :system) do before do allow_any_instance_of(Iffy::Post::IngestService).to receive(:perform).and_return(true) end describe "emails" do let(:seller) { create(:named_seller, timezone: "UTC") } let(:buyer) { create(:user) } let(:product) { create(:product, user: seller, name: "Product name") } let!(:purchase) { create(:purchase, link: product, purchaser: buyer) } let!(:installment1) { create(:installment, link: product, name: "Email 1 (sent)", message: "test", published_at: 2.days.ago) } let!(:installment2) { create(:installment, link: product, name: "Email 2 (draft)", message: "test", created_at: 1.hour.ago) } let!(:installment3) { create(:installment, link: product, name: "Email 3 (sent)", message: "test", shown_on_profile: true, published_at: 3.days.ago) } let!(:installment4) { create(:installment, link: product, name: "Email 4 (draft)", message: "test", created_at: 5.hour.ago, updated_at: 5.hour.ago) } let!(:installment5) { create(:scheduled_installment, link: product, name: "Email 5 (scheduled)", message: "test", created_at: 5.hour.ago) } let!(:installment6) { create(:scheduled_installment, link: product, name: "Email 6 (scheduled)", message: "test", created_at: 1.hour.ago) } include_context "with switching account to user as admin for seller" before do recreate_model_indices(Purchase) end describe "published emails" do it "shows published emails" do expect_any_instance_of(Installment).to receive(:send_preview_email).with(user_with_role_for_seller) CreatorEmailOpenEvent.create!(installment_id: installment1.id) url1 = "example.com" url2 = "example.com/this-is-a-very-very-long-url-12345-the-quick-brown-fox-jumps-over-the-lazy-dog" CreatorEmailClickSummary.create!(installment_id: installment1.id, total_unique_clicks: 123, urls: { url1 => 100, url2 => 23 }) installment1.increment_total_delivered visit "#{emails_path}/published" within_table "Published" do expect(page).to have_table_row({ "Subject" => "Email 1 (sent)", "Emailed" => "1", "Opened" => "100%", "Clicks" => "123", "Views" => "n/a" }) cell = find(:table_cell, "Clicks", text: "123", visible: :all).find("[aria-describedby]", visible: :all) expect(cell).to have_tooltip(text: url1, visible: false) expect(cell).to have_tooltip(text: url2.truncate(70), visible: false) expect(page).to have_table_row({ "Subject" => "Email 3 (sent)", "Emailed" => "--", "Opened" => "--", "Clicks" => "0", "Views" => "0" }) expect(page).to_not have_table_row({ "Subject" => "Email 2 (draft)" }) expect(page).to_not have_table_row({ "Subject" => "Email 4 (draft)" }) expect(page).to_not have_table_row({ "Subject" => "Email 5 (scheduled)" }) expect(page).to_not have_table_row({ "Subject" => "Email 6 (scheduled)" }) end # Opens a sidebar drawer with additional information of the selected email find(:table_row, { "Subject" => "Email 1 (sent)" }).click within_modal "Email 1 (sent)" do expect(page).to have_text("Sent #{installment1.published_at.in_time_zone(seller.timezone).strftime("%-m/%-d/%Y, %-I:%M:%S %p")}", normalize_ws: true) expect(page).to have_text("Emailed 1", normalize_ws: true) expect(page).to have_text("Opened 1 (100%)", normalize_ws: true) expect(page).to have_text("Clicks 123 (12,300%)", normalize_ws: true) expect(page).to have_text("Views n/a", normalize_ws: true) expect(page).to have_link("Duplicate") expect(page).to have_link("Edit") expect(page).to have_button("Delete") expect(page).to_not have_link("View post") # Allows sending the email preview for the email that was created with "Send email" channel click_on "View email" end wait_for_ajax expect(page).to have_alert(text: "A preview has been sent to your email.") # Allows closing the sidebar drawer within_modal "Email 1 (sent)" do click_on "Close" end expect(page).to_not have_modal find(:table_row, { "Subject" => "Email 3 (sent)" }).click within_modal "Email 3 (sent)" do expect(page).to have_text("Sent #{installment3.published_at.in_time_zone(seller.timezone).strftime("%-m/%-d/%Y, %-I:%M:%S %p")}", normalize_ws: true) expect(page).to have_text("Emailed --", normalize_ws: true) expect(page).to have_text("Opened --", normalize_ws: true) expect(page).to have_text("Clicks --", normalize_ws: true) expect(page).to have_text("Views 0", normalize_ws: true) expect(page).to have_link("Duplicate") expect(page).to have_link("Edit") expect(page).to have_button("Delete") expect(page).to have_button("View email") # Allows previwing the post in a window for the email that was created with "Shown on profile" channel new_window = window_opened_by { click_on "View post" } within_window new_window do expect(page).to have_text("Email 3 (sent)") end click_on "Close" end # Ensures that the "Views" count is incremented when a buyer views the post Capybara.using_session(:buyer_session) do login_as buyer visit custom_domain_view_post_url(host: seller.subdomain_with_protocol, slug: installment3.slug) wait_for_ajax end refresh expect(page).to have_table_row({ "Subject" => "Email 3 (sent)", "Emailed" => "--", "Opened" => "--", "Clicks" => "0", "Views" => "1" }) end it "loads more emails" do stub_const("PaginatedInstallmentsPresenter::PER_PAGE", 2) visit "#{emails_path}/published" wait_for_ajax expect(page).to have_table_row({ "Subject" => "Email 1 (sent)" }) expect(page).to have_table_row({ "Subject" => "Email 3 (sent)" }) expect(page).to_not have_button("Load more") create(:installment, name: "Hello world!", seller:, link: product, published_at: 10.days.ago) refresh expect(page).to have_table_row({ "Subject" => "Email 1 (sent)" }) expect(page).to have_table_row({ "Subject" => "Email 3 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Hello world!" }) click_on "Load more" wait_for_ajax expect(page).to have_table_row({ "Subject" => "Email 1 (sent)" }) expect(page).to have_table_row({ "Subject" => "Email 3 (sent)" }) expect(page).to have_table_row({ "Subject" => "Hello world!" }) expect(page).to_not have_button("Load more") end it "deletes an email" do visit "#{emails_path}/published" find(:table_row, { "Subject" => "Email 1 (sent)" }).click within_modal "Email 1 (sent)" do click_on "Delete" end within_modal "Delete email?" do expect(page).to have_text("Are you sure you want to delete the email \"Email 1 (sent)\"? Customers who had access will no longer be able to see it. This action cannot be undone.") click_on "Delete email" end wait_for_ajax expect(page).to have_alert(text: "Email deleted!") expect(page).to_not have_table_row({ "Subject" => "Email 1 (sent)" }) expect(installment1.reload.deleted_at).to_not be_nil end end describe "scheduled emails" do it "shows scheduled emails" do installment7 = create(:scheduled_installment, seller:, name: "Email 7 (scheduled)", message: "test", link: nil, installment_type: Installment::AUDIENCE_TYPE, created_at: 1.hour.ago) installment7.installment_rule.update!(to_be_published_at: 1.day.from_now) visit "#{emails_path}/scheduled" wait_for_ajax within_table "Scheduled for #{installment5.installment_rule.to_be_published_at.in_time_zone(seller.timezone).strftime("%b %-d, %Y")}" do expect(page).to have_table_row({ "Subject" => "Email 5 (scheduled)", "Sent to" => "Customers of Product name", "Audience" => "1" }) expect(page).to have_table_row({ "Subject" => "Email 6 (scheduled)", "Sent to" => "Customers of Product name", "Audience" => "1" }) end within_table "Scheduled for #{installment7.installment_rule.to_be_published_at.in_time_zone(seller.timezone).strftime("%b %-d, %Y")}" do expect(page).to have_table_row({ "Subject" => "Email 7 (scheduled)", "Sent to" => "Your customers and followers", "Audience" => "1" }) end expect(page).to_not have_table_row({ "Subject" => "Email 1 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Email 2 (draft)" }) expect(page).to_not have_table_row({ "Subject" => "Email 3 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Email 4 (draft)" }) end it "deletes an email" do visit "#{emails_path}/scheduled" wait_for_ajax find(:table_row, { "Subject" => "Email 5 (scheduled)" }).click within_modal "Email 5 (scheduled)" do click_on "Delete" end within_modal "Delete email?" do expect(page).to have_text("Are you sure you want to delete the email \"Email 5 (scheduled)\"? This action cannot be undone.") click_on "Delete email" end wait_for_ajax expect(page).to have_alert(text: "Email deleted!") expect(page).to_not have_table_row({ "Subject" => "Email 5 (scheduled)" }) expect(installment5.reload.deleted_at).to_not be_nil end end describe "draft emails" do it "shows draft emails" do visit "#{emails_path}/drafts" wait_for_ajax expect(page).to have_table_row({ "Subject" => "Email 2 (draft)", "Sent to" => "Customers of Product name", "Audience" => "1" }) expect(page).to have_table_row({ "Subject" => "Email 4 (draft)", "Sent to" => "Customers of Product name", "Audience" => "1" }) expect(page).to_not have_table_row({ "Subject" => "Email 1 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Email 3 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Email 5 (scheduled)" }) expect(page).to_not have_table_row({ "Subject" => "Email 6 (scheduled)" }) end it "paginates emails ordered by recently updated first" do stub_const("PaginatedInstallmentsPresenter::PER_PAGE", 2) visit "#{emails_path}/drafts" wait_for_ajax expect(page).to have_table_row({ "Subject" => "Email 2 (draft)" }) expect(page).to have_table_row({ "Subject" => "Email 4 (draft)" }) expect(page).to_not have_button("Load more") create(:installment, name: "Hello world!", seller:, link: product) refresh expect(page).to have_table_row({ "Subject" => "Hello world!", "Sent to" => "Customers of Product name", "Audience" => "1" }) expect(page).to have_table_row({ "Subject" => "Email 2 (draft)" }) expect(page).to_not have_table_row({ "Subject" => "Email 4 (draft)" }) click_on "Load more" wait_for_ajax expect(page).to have_table_row({ "Subject" => "Hello world!" }) expect(page).to have_table_row({ "Subject" => "Email 2 (draft)" }) expect(page).to have_table_row({ "Subject" => "Email 4 (draft)" }) expect(page).to_not have_button("Load more") end it "deletes an email" do visit "#{emails_path}/drafts" wait_for_ajax find(:table_row, { "Subject" => "Email 2 (draft)" }).click within_modal "Email 2 (draft)" do click_on "Delete" end within_modal "Delete email?" do expect(page).to have_text("Are you sure you want to delete the email \"Email 2 (draft)\"? This action cannot be undone.") click_on "Delete email" end wait_for_ajax expect(page).to have_alert(text: "Email deleted!") expect(page).to_not have_table_row({ "Subject" => "Email 2 (draft)" }) expect(installment2.reload.deleted_at).to_not be_nil end end describe "search" do it "displays filtered and paginated emails for the search query" do stub_const("PaginatedInstallmentsPresenter::PER_PAGE", 1) create(:installment, name: "Hello world", seller:, link: product, published_at: 10.days.ago) # does not match 'name' or 'message' create(:installment, name: "Thank you!", message: "Thank you email", seller:, link: product, published_at: 1.month.ago) # matches the 'message' create(:installment, name: "Email 7 (sent)", published_at: 10.days.ago) # another seller's email, so won't match visit "#{emails_path}/published" wait_for_ajax select_disclosure "Toggle Search" do fill_in "Search emails", with: "email" end wait_for_ajax expect(page).to have_table_row({ "Subject" => "Thank you!" }) expect(page).to_not have_table_row({ "Subject" => "Email 1 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Email 2 (draft)" }) expect(page).to_not have_table_row({ "Subject" => "Email 3 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Email 4 (draft)" }) expect(page).to_not have_table_row({ "Subject" => "Email 5 (scheduled)" }) expect(page).to_not have_table_row({ "Subject" => "Email 6 (scheduled)" }) expect(page).to_not have_table_row({ "Subject" => "Email 7 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Hello world" }) click_on "Load more" wait_for_ajax expect(page).to have_table_row({ "Subject" => "Thank you!" }) expect(page).to have_table_row({ "Subject" => "Email 3 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Email 1 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Email 2 (draft)" }) expect(page).to_not have_table_row({ "Subject" => "Email 4 (draft)" }) expect(page).to_not have_table_row({ "Subject" => "Email 5 (scheduled)" }) expect(page).to_not have_table_row({ "Subject" => "Email 6 (scheduled)" }) expect(page).to_not have_table_row({ "Subject" => "Email 7 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Hello world" }) click_on "Load more" wait_for_ajax expect(page).to have_table_row({ "Subject" => "Thank you!" }) expect(page).to have_table_row({ "Subject" => "Email 3 (sent)" }) expect(page).to have_table_row({ "Subject" => "Email 1 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Email 2 (draft)" }) expect(page).to_not have_table_row({ "Subject" => "Email 4 (draft)" }) expect(page).to_not have_table_row({ "Subject" => "Email 5 (scheduled)" }) expect(page).to_not have_table_row({ "Subject" => "Email 6 (scheduled)" }) expect(page).to_not have_table_row({ "Subject" => "Email 7 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Hello world" }) expect(page).to_not have_button("Load more") end it "searches emails for the corresponding tab" do create(:installment, name: "Published post", seller:, link: product, published_at: 10.days.ago) create(:installment, seller:, link: product, name: "Draft post", message: "test", created_at: 1.hour.ago) create(:scheduled_installment, seller:, link: product, name: "Scheduled Post") visit "#{emails_path}/published" wait_for_ajax select_disclosure "Toggle Search" do fill_in "Search emails", with: "email" end wait_for_ajax expect(page).to have_table_row(count: 3) # including header row expect(page).to have_table_row({ "Subject" => "Email 1 (sent)" }) expect(page).to have_table_row({ "Subject" => "Email 3 (sent)" }) expect(page).to_not have_table_row({ "Subject" => "Published post" }) # Reset the search fill_in "Search emails", with: "" wait_for_ajax expect(page).to have_table_row(count: 4) # including header row expect(page).to have_table_row({ "Subject" => "Email 1 (sent)" }) expect(page).to have_table_row({ "Subject" => "Email 3 (sent)" }) expect(page).to have_table_row({ "Subject" => "Published post" }) select_tab "Scheduled" wait_for_ajax select_disclosure "Toggle Search" do fill_in "Search emails", with: "email" end wait_for_ajax expect(page).to have_table_row(count: 3) # including header row expect(page).to have_table_row({ "Subject" => "Email 5 (scheduled)" }) expect(page).to have_table_row({ "Subject" => "Email 6 (scheduled)" }) expect(page).to_not have_table_row({ "Subject" => "Scheduled Post" }) # Reset the search fill_in "Search emails", with: "" wait_for_ajax expect(page).to have_table_row(count: 4) # including header row expect(page).to have_table_row({ "Subject" => "Email 5 (scheduled)" }) expect(page).to have_table_row({ "Subject" => "Email 6 (scheduled)" }) expect(page).to have_table_row({ "Subject" => "Scheduled Post" }) select_tab "Drafts" wait_for_ajax select_disclosure "Toggle Search" do fill_in "Search emails", with: "email" end wait_for_ajax expect(page).to have_table_row(count: 3) # including header row expect(page).to have_table_row({ "Subject" => "Email 2 (draft)" }) expect(page).to have_table_row({ "Subject" => "Email 4 (draft)" }) expect(page).to_not have_table_row({ "Subject" => "Draft post" }) # Reset the search fill_in "Search emails", with: "" wait_for_ajax expect(page).to have_table_row(count: 4) # including header row expect(page).to have_table_row({ "Subject" => "Email 2 (draft)" }) expect(page).to have_table_row({ "Subject" => "Email 4 (draft)" }) expect(page).to have_table_row({ "Subject" => "Draft post" }) 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/emails/edit_spec.rb
spec/requests/emails/edit_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Email Editing Flow", :js, :elasticsearch_wait_for_refresh, type: :system) do include EmailHelpers let(:seller) { create(:named_seller) } let(:product) { create(:product, name: "Sample product", user: seller) } let!(:product2) { create(:product, name: "Another product", user: seller) } let!(:purchase) { create(:purchase, link: product) } let!(:installment) { create(:installment, seller:, name: "Original email", message: "Original message", bought_products: [product.unique_permalink, product2.unique_permalink], link_id: nil, installment_type: "seller", created_after: "2024-01-01T00:00:00Z", created_before: "2024-01-02T23:59:59Z", paid_more_than_cents: 100, paid_less_than_cents: 1000, bought_from: "Canada", shown_on_profile: false, allow_comments: false) } include_context "with switching account to user as admin for seller" before do seller.update!(timezone: "UTC") recreate_model_indices(Purchase) index_model_records(Purchase) allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE) create(:payment_completed, user: seller) end it "allows editing an unpublished email" do # Ensure that an archived product with successful sales is shown in the "Bought", "Has not yet bought", etc. filters product.update!(archived: true) visit emails_path select_tab "Drafts" wait_for_ajax find(:table_row, { "Subject" => "Original email" }).click click_on "Edit" expect(page).to have_text("Edit email") # Check that the form is filled in correctly and update some of the fields expect(page).to have_radio_button "Customers only", checked: true expect(page).to have_text("Audience 0 / 1", normalize_ws: true) expect(page).to have_checked_field("Send email") uncheck "Send email" expect(page).to have_unchecked_field("Post to profile") check "Post to profile" within :fieldset, "Bought" do expect(page).to have_button("Sample product") expect(page).to have_button("Another product") click_on "Another product" expect(page).to have_button("Sample product") expect(page).to_not have_button("Another product") end find(:combo_box, "Has not yet bought").click expect(page).to have_combo_box("Has not yet bought", expanded: true, with_options: ["Another product"]) select_combo_box_option("Another product", from: "Has not yet bought") expect(page).to have_field("Paid more than", with: "1") fill_in "Paid more than", with: "2" expect(page).to have_field("Paid less than", with: "10") fill_in "Paid less than", with: "15" expect(page).to have_field("After", with: "2024-01-01") expect(page).to have_field("Before", with: "2024-01-02") expect(page).to have_select("From", selected: "Canada") select "United States", from: "From" expect(page).to have_unchecked_field("Allow comments") check "Allow comments" expect(page).to have_field("Title", with: "Original email") fill_in "Title", with: "Updated email" expect(page).to_not have_field("Publish date") within find("[aria-label='Email message']") do expect(page).to have_text "Original message" end set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Updated message") sleep 0.5 # Wait for the message editor to update attach_file(file_fixture("test.jpg")) do click_on "Insert image" end wait_for_ajax upload_attachment("test.mp4") within find_attachment("test") do click_on "Edit" attach_file("Add subtitles", Rails.root.join("spec/support/fixtures/sample.srt"), visible: false) end expect(page).to have_unchecked_field("Disable file downloads (stream only)") expect(page).to have_button("Save", disabled: false) create(:seller_profile_posts_section, seller:) # Create a profile section click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") installment.reload expect(installment.name).to eq("Updated email") expect(installment.message).to include("<p>Updated message</p>") expect(installment.seller_type?).to be(false) expect(installment.product_type?).to be(true) expect(installment.link).to eq(product) expect(installment.base_variant).to be_nil expect(installment.seller).to eq(seller) expect(installment.published?).to be(false) expect(installment.ready_to_publish?).to be(false) # Although the 'product' is archived (with successful sales), it is kept on save expect(installment.bought_products).to eq([product.unique_permalink]) expect(installment.bought_variants).to be_nil expect(installment.not_bought_products).to eq([product2.unique_permalink]) expect(installment.not_bought_variants).to be_nil expect(installment.affiliate_products).to be_nil expect(installment.send_emails).to be(false) expect(installment.shown_on_profile).to be(true) expect(installment.paid_more_than_cents).to eq(200) expect(installment.paid_less_than_cents).to eq(1500) expect(installment.bought_from).to eq("United States") expect(installment.allow_comments).to be(true) expect(installment.product_files.alive.map(&:s3_filename)).to eq(["test.mp4"]) subtitle = installment.product_files.alive.last.subtitle_files.alive.sole expect(subtitle.url).to include("sample.srt") expect(subtitle.language).to include("English") expect(installment.stream_only?).to be(false) expect(page).to have_current_path("#{emails_path}/#{installment.external_id}/edit") end it "allows editing and scheduling a draft email" do visit emails_path select_tab "Drafts" wait_for_ajax find(:table_row, { "Subject" => "Original email" }).click click_on "Edit" expect(page).to have_text("Edit email") expect(page).to have_checked_field("Send email") expect(page).to have_unchecked_field("Post to profile") expect(page).to have_field("Title", with: "Original email") fill_in "Title", with: "Updated email" expect(page).to_not have_field("Publish date") expect(page).to_not have_disclosure("Publish") # Try scheduling the email with an invalid date select_disclosure "Send" do expect(page).to have_button("Send now") expect(page).to_not have_button("Publish now") fill_in "Schedule date", with: "01/01/2021\t04:00PM" click_on "Schedule" end wait_for_ajax expect(page).to have_alert("Please select a date and time in the future.") expect(installment.reload.name).to eq("Original email") expect(installment.ready_to_publish?).to be(false) # Try scheduling the email with a valid date check "Post to profile" expect(page).to_not have_disclosure("Send") select_disclosure "Publish" do expect(page).to have_button("Publish now") expect(page).to_not have_button("Send now") fill_in "Schedule date", with: "01/01/#{Date.today.year.next}\t04:00PM" click_on "Schedule" end expect(page).to have_alert("Email successfully scheduled!") wait_until_true { installment.reload.ready_to_publish? } expect(installment.ready_to_publish?).to be(true) expect(installment.installment_rule.to_be_published_at.to_date.to_s).to eq("#{Date.today.year.next}-01-01") wait_until_true { installment.name == "Updated email" } expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) expect(installment.published?).to be(false) end it "allows editing and publishing an email" do scheduled_installment = create(:scheduled_installment, seller:, name: "Scheduled email") scheduled_installment.installment_rule.update!(to_be_published_at: 1.year.from_now) visit emails_path # Ensure that the "Scheduled" tab is open by default on accessing the /emails page where there's at least one scheduled email expect(page).to have_current_path("#{emails_path}/scheduled") expect(page).to have_tab_button("Scheduled", open: true) find(:table_row, { "Subject" => "Scheduled email" }).click click_on "Edit" expect(page).to have_current_path("#{emails_path}/#{scheduled_installment.external_id}/edit") expect(page).to have_checked_field("Send email") expect(page).to have_unchecked_field("Post to profile") expect(page).to have_field("Title", with: "Scheduled email") fill_in "Title", with: "Updated scheduled email" expect(page).to_not have_field("Publish date") # Publish the scheduled email select_disclosure "Send" do expect(page).to have_button("Schedule") click_on "Send now" end wait_for_ajax expect(page).to have_alert(text: "Email successfully sent!") expect(scheduled_installment.reload.name).to eq("Updated scheduled email") expect(scheduled_installment.send_emails).to be(true) expect(scheduled_installment.shown_on_profile).to be(false) expect(scheduled_installment.published?).to be(true) expect(scheduled_installment.has_been_blasted?).to be(true) expect(scheduled_installment.ready_to_publish?).to be(true) expect(scheduled_installment.installment_rule.deleted?).to be(true) expect(SendPostBlastEmailsJob).to have_enqueued_sidekiq_job(PostEmailBlast.sole.id) # Check that the publish date is displayed expect(page).to have_current_path("#{emails_path}/published") find(:table_row, { "Subject" => "Updated scheduled email" }).click click_on "Edit" expect(page).to have_checked_field("Send email", disabled: true) expect(page).to have_field("Publish date", with: scheduled_installment.published_at.to_date.to_s) click_on "Cancel" # Check that the email is removed from the "Scheduled" tab select_tab "Scheduled" expect(page).to have_current_path("#{emails_path}/scheduled") expect(page).to_not have_table_row({ "Subject" => "Scheduled email" }) expect(page).to_not have_table_row({ "Subject" => "Updated scheduled email" }) expect(page).to have_text("Set it and forget it.") expect(page).to have_text("Schedule an email to be sent exactly when you want.") select_tab "Drafts" find(:table_row, { "Subject" => "Original email" }).click click_on "Edit" expect(page).to have_current_path("#{emails_path}/#{installment.external_id}/edit") expect(page).to have_checked_field("Send email") expect(page).to have_unchecked_field("Post to profile") check "Post to profile" expect(page).to have_field("Title", with: "Original email") fill_in "Title", with: "Updated email" expect(page).to_not have_field("Publish date") # Publish the draft email select_disclosure "Publish" do expect(page).to have_button("Schedule") click_on "Publish now" end expect(page).to have_alert(text: "Email successfully sent!") wait_until_true { installment.reload.name == "Updated email" } expect(installment.name).to eq("Updated email") expect(installment.published?).to be(true) expect(installment.has_been_blasted?).to be(true) expect(installment.ready_to_publish?).to be(false) expect(installment.installment_rule).to be_nil expect(SendPostBlastEmailsJob).to have_enqueued_sidekiq_job(PostEmailBlast.last!.id) expect(PostEmailBlast.count).to eq(2) # Check that the publish date is displayed expect(page).to have_current_path("#{emails_path}/published") find(:table_row, { "Subject" => "Updated email" }).click click_on "Edit" expect(page).to have_checked_field("Send email", disabled: true) expect(page).to have_field("Publish date", with: installment.published_at.to_date.to_s) click_on "Cancel" # Check that the email is removed from the "Drafts" tab select_tab "Drafts" expect(page).to have_current_path("#{emails_path}/drafts") expect(page).to_not have_table_row({ "Subject" => "Original email" }) expect(page).to_not have_table_row({ "Subject" => "Updated email" }) expect(page).to have_text("Manage your drafts") expect(page).to have_text("Drafts allow you to save your emails and send whenever you're ready!") end it "allows editing certain fields of a published email" do published_installment = create(:published_installment, name: "Hello", seller: seller, published_at: "2024-01-01 12:00") original_published_at = published_installment.published_at visit emails_path # Ensure that the "Published" tab is open by default on accessing the /emails page where there are no scheduled emails expect(page).to have_tab_button("Published", open: true) find(:table_row, { "Subject" => "Hello" }).click click_on "Edit" expect(page).to have_current_path("#{emails_path}/#{published_installment.external_id}/edit") expect(page).to have_text("Edit email") expect(page).to have_radio_button("Customers only", checked: true, disabled: true) expect(page).to have_radio_button("Everyone", checked: false, disabled: true) # Until the email is blasted, the "Send email" field is NOT disabled expect(page).to have_checked_field("Send email", disabled: false) uncheck "Send email" expect(page).to have_unchecked_field("Post to profile", disabled: false) check "Post to profile" expect(page).to have_field("Paid more than", with: "", disabled: true) expect(page).to have_field("Paid less than", with: "", disabled: true) expect(page).to have_field("After", with: "", disabled: true) expect(page).to have_field("Before", with: "", disabled: true) expect(page).to have_select("From", disabled: true) expect(page).to have_checked_field("Allow comments", disabled: false) uncheck "Allow comments" fill_in "Title", with: "Hello - edit 1" # Ensure that the publish date is displayed expect(page).to have_field("Publish date", with: "2024-01-01") click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") published_installment.reload expect(published_installment.name).to eq "Hello - edit 1" # It does not modify the publish date if it was unchanged expect(published_installment.published_at).to eq original_published_at expect(published_installment.send_emails).to be(false) expect(published_installment.shown_on_profile).to be(true) expect(published_installment.allow_comments).to be(false) check "Send email" # Ensure that it does not accept an invalid publish date and reject other changes as well on save fill_in "Publish date", with: "01/01/#{2.years.from_now.year}" fill_in "Title", with: "Hello - edit 2" click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Please enter a publish date in the past.") published_installment.reload expect(published_installment.published_at).to eq original_published_at expect(published_installment.name).to eq "Hello - edit 1" expect(published_installment.send_emails).to be(false) expect(published_installment.shown_on_profile).to be(true) expect(published_installment.allow_comments).to be(false) # Try setting the publish date to a valid date fill_in "Publish date", with: "01/01/2021" click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") published_installment.reload expect(published_installment.published_at.to_date.to_s).to eq "2021-01-01" expect(published_installment.name).to eq "Hello - edit 2" expect(published_installment.send_emails).to be(true) expect(published_installment.shown_on_profile).to be(true) expect(published_installment.has_been_blasted?).to be(false) expect(published_installment.allow_comments).to be(false) expect(page).to have_checked_field("Send email", disabled: false) expect(page).to have_checked_field("Post to profile", disabled: false) # Try publishing the already published email fill_in "Title", with: "Hello - edit 3" set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Updated message") sleep 0.5 # Wait for the message editor to update select_disclosure "Publish" do expect(page).to have_button("Schedule", disabled: true) click_on "Publish now" end expect(page).to have_alert(text: "Email successfully sent!") published_installment.reload expect(published_installment.published_at).to be_within(5.second).of(DateTime.current) expect(published_installment.has_been_blasted?).to be(true) expect(published_installment.name).to eq "Hello - edit 3" expect(published_installment.message).to eq("<p>Updated message</p>") # The "Send email" field is disabled after the email is blasted (which happens when the email is published) expect(page).to have_current_path("#{emails_path}/published") find(:table_row, { "Subject" => "Hello - edit 3" }).click click_on "Edit" expect(page).to have_checked_field("Send email", disabled: true) expect(page).to have_checked_field("Post to profile", disabled: false) expect(page).to have_field("Publish date", with: published_installment.published_at.to_date.to_s) expect(SendPostBlastEmailsJob).to have_enqueued_sidekiq_job(PostEmailBlast.last!.id) end it "allows editing and previewing an email" do allow_any_instance_of(Installment).to receive(:send_preview_email).with(user_with_role_for_seller) visit emails_path select_tab "Drafts" find(:table_row, { "Subject" => "Original email" }).click click_on "Edit" # Ensure that it saves the edited fields and sends a preview email fill_in "Title", with: "Updated original email", fill_options: { clear: :backspace } expect(page).to have_checked_field("Send email") expect(page).to have_unchecked_field("Post to profile") # When only one channel (either "Send email" or "Post to profile") is checked, the "Preview" button is not disclousre expect(page).to_not have_disclosure("Preview") click_on "Preview" wait_for_ajax expect(page).to have_alert(text: "A preview has been sent to your email.") expect(installment.reload.name).to eq("Updated original email") expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(false) expect(installment.published?).to be(false) expect(installment.has_been_blasted?).to be(false) expect(installment.ready_to_publish?).to be(false) # When both channels are unchecked, it does not allow saving and previewing fill_in "Title", with: "Updated original email - edit 2", fill_options: { clear: :backspace } uncheck "Send email" click_on "Preview" wait_for_ajax expect(page).to have_alert(text: "Please set at least one channel for your update.") # Opens the post in a new window when the "Post to profile" channel is checked set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Updated message") sleep 0.5 # Wait for the message editor to update expect(installment.reload.name).to eq("Updated original email") check "Post to profile" new_window = window_opened_by do click_on "Preview" expect(page).to have_alert(text: "Preview link opened.") end within_window new_window do wait_for_ajax expect(page).to have_text("Updated original email - edit 2") expect(page).to have_text("Updated message") end new_window.close expect(installment.reload.name).to eq("Updated original email - edit 2") expect(installment.message).to eq("<p>Updated message</p>") expect(installment.send_emails).to be(false) expect(installment.shown_on_profile).to be(true) expect(installment.published?).to be(false) expect(installment.has_been_blasted?).to be(false) expect(installment.ready_to_publish?).to be(false) click_on "Cancel" wait_until_true { find(:table_row, { "Subject" => "Updated original email - edit 2" }).present? } find(:table_row, { "Subject" => "Updated original email - edit 2" }).click click_on "Edit" wait_until_true { find_field("Title").present? } # Schedule the email fill_in "Title", with: "Updated original email - scheduled", fill_options: { clear: :backspace } set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Scheduled message") sleep 0.5 # Wait for the title editor to update select_disclosure "Publish" do click_on "Schedule" end expect(page).to have_alert(text: "Email successfully scheduled!") expect(installment.reload.name).to eq("Updated original email - scheduled") expect(installment.message).to eq("<p>Scheduled message</p>") expect(installment.ready_to_publish?).to be(true) # When both channels are checked, the "Preview" button is disclosure expect(page).to have_current_path("#{emails_path}/scheduled") find(:table_row, { "Subject" => "Updated original email - scheduled" }).click click_on "Edit" check "Send email" fill_in "Title", with: "Updated original email - scheduled - edit 2" select_disclosure "Preview" do click_on "Preview Email" end wait_for_ajax expect(page).to have_alert(text: "A preview has been sent to your email.") expect(installment.reload.name).to eq("Updated original email - scheduled - edit 2") # Publish the email fill_in "Title", with: "Updated original email - published", fill_options: { clear: :backspace } set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Published message") sleep 0.5 # Wait for the message editor to update select_disclosure "Publish" do click_on "Publish now" end expect(page).to have_alert(text: "Email successfully sent!") expect(installment.reload.name).to eq("Updated original email - published") expect(installment.message).to eq("<p>Published message</p>") expect(installment.published?).to be(true) expect(installment.has_been_blasted?).to be(true) expect(installment.ready_to_publish?).to be(true) expect(installment.send_emails).to be(true) expect(installment.shown_on_profile).to be(true) # Preview the published post in a new window expect(page).to have_current_path("#{emails_path}/published") find(:table_row, { "Subject" => "Updated original email - published" }).click click_on "Edit" expect(page).to have_checked_field("Send email", disabled: true) expect(page).to have_checked_field("Post to profile", disabled: false) expect(page).to have_field("Publish date", with: installment.published_at.to_date.to_s) fill_in "Title", with: "Updated original email - published - edit 2", fill_options: { clear: :backspace } set_rich_text_editor_input(find("[aria-label='Email message']"), to_text: "Published message 2") sleep 0.5 # Wait for the message editor to update new_window = window_opened_by do select_disclosure "Preview" do click_on "Preview Post" end expect(page).to have_alert(text: "Preview link opened.") end within_window new_window do wait_for_ajax expect(page).to have_text("Updated original email - published - edit 2") expect(page).to have_text("Published message") end new_window.close end it "generates a new product files archive when the email name is changed" do follower_installment = create(:follower_installment, seller: seller, published_at: "2021-01-02 12:00") create(:active_follower, user: seller) visit "#{emails_path}/#{follower_installment.external_id}/edit" expect(page).to have_radio_button("Followers only", checked: true) fill_in "Title", with: "Updated Follower Post", fill_options: { clear: :backspace } click_on "Save" wait_until_true { follower_installment.reload.product_files_archives.alive.any? } expect(follower_installment.reload.product_files_archives.alive.sole.url.split("/").last).to eq("Updated_Follower_Post.zip") end it "allows choosing which profile post sections to show an audience post in" do visit "#{emails_path}/#{installment.external_id}/edit" expect(page).to have_radio_button("Customers only", checked: true) expect(page).to have_unchecked_field("Post to profile") expect(page).to_not have_text("You currently have no sections in your profile to display this") expect(page).to_not have_text("The post will be shown in the selected profile sections once it is published.") check "Post to profile" expect(page).to_not have_text("You currently have no sections in your profile to display this") expect(page).to_not have_text("The post will be shown in the selected profile sections once it is published.") choose "Everyone" expect(page).to have_text("You currently have no sections in your profile to display this, create one here") expect(page).to_not have_text("The post will be shown in the selected profile sections once it is published.") section1 = create(:seller_profile_posts_section, seller:, header: "Posts section 1", shown_posts: [installment.id]) section2 = create(:seller_profile_posts_section, seller:, shown_posts: []) refresh expect(page).to_not have_field("Posts section 1") expect(page).to_not have_field("Unnamed section") choose "Everyone" expect(page).to_not have_field("Posts section 1") expect(page).to_not have_field("Unnamed section") check "Post to profile" within_fieldset "Channel" do expect(page).to_not have_text("You currently have no sections in your profile to display this, create one here") expect(page).to have_checked_field("Posts section 1") expect(page).to have_unchecked_field("Unnamed section") expect(page).to have_text("The post will be shown in the selected profile sections once it is published.") end uncheck "Posts section 1" check "Unnamed section" toggle_disclosure "Publish" do click_on "Publish now" end wait_for_ajax expect(page).to have_alert(text: "Email successfully sent!") expect(section1.reload.shown_posts).to be_empty expect(section2.reload.shown_posts).to eq([installment.id]) find(:table_row, { "Subject" => "Original email" }).click click_on "Edit" expect(page).to have_unchecked_field("Posts section 1") expect(page).to have_checked_field("Unnamed section") expect(page).to_not have_text("The post will be shown in the selected profile sections once it is published.") uncheck "Post to profile" click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(installment.reload.shown_on_profile).to be(false) expect(section1.reload.shown_posts).to be_empty expect(section2.reload.shown_posts).to be_empty end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/admin/sales_reports_spec.rb
spec/requests/admin/sales_reports_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Admin::SalesReportsController", type: :system, js: true do let(:admin) { create(:admin_user) } before do login_as(admin) end describe "GET /admin/sales_reports" do it "displays the sales reports page" do visit admin_sales_reports_path # displays the sales reports page expect(page).to have_text("Sales reports") # shows no jobs message expect(page).to have_text("Generate your first sales report") expect(page).to have_text("Create a report to view sales data by country for a specified date range.") # shows new report button expect(page).to have_button("New report") end context "when there are no jobs in history" do it "shows no jobs message" do allow($redis).to receive(:lrange).and_return([]) visit admin_sales_reports_path expect(page).to have_text("Generate your first sales report") end end context "when there are jobs in history" do before do job_data = [ { job_id: "123", country_code: "GB", start_date: "2023-01-01", end_date: "2023-03-31", sales_type: "all_sales", enqueued_at: Time.current.to_s, status: "processing" }.to_json, { job_id: "124", country_code: "JP", start_date: "2023-01-01", end_date: "2023-06-30", sales_type: "discover_sales", enqueued_at: Time.current.to_s, status: "processing" }.to_json ] allow($redis).to receive(:lrange).with(RedisKey.sales_report_jobs, 0, 19).and_return(job_data) end it "displays job history table" do visit admin_sales_reports_path expect(page).to have_table expect(page).to have_text("United Kingdom") expect(page).to have_text("2023-01-01 - 2023-03-31") expect(page).to have_text("All sales") expect(page).to have_text("Processing") expect(page).to have_text("Japan") expect(page).to have_text("2023-01-01 - 2023-06-30") expect(page).to have_text("Discover sales") expect(page).to have_text("Processing") end end end describe "POST /admin/sales_reports" do before do allow($redis).to receive(:lpush) allow($redis).to receive(:ltrim) end # TODO: Fix this test xit "enqueues a job when form is submitted" do visit admin_sales_reports_path select "United Kingdom", from: "sales_report[country_code]" fill_in "sales_report[start_date]", with: "2023-01-01" fill_in "sales_report[end_date]", with: "2023-03-31" select "All sales", from: "sales_report[sales_type]" click_button "Generate" wait_for_ajax expect(GenerateSalesReportJob).to have_enqueued_sidekiq_job( "GB", "2023-01-01", "2023-03-31", GenerateSalesReportJob::ALL_SALES, true, nil ) expect(page).to have_text("Sales report job enqueued successfully!") 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/search_spec.rb
spec/requests/admin/search_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Admin::SearchController Scenario", type: :system, js: true do let(:admin) { create(:admin_user) } before do sign_in admin end describe "purchases" do describe "product_title_query" do let(:product_title_query) { "design" } let!(:product) { create(:product, name: "Graphic Design Course") } let!(:purchase) { create(:purchase, link: product, email: "user@example.com") } before do create(:purchase, link: create(:product, name: "Different Product")) # Create another purchase with same email and same product to avoid redirect create(:purchase, email: "user@example.com", link: product) end it "filters by product title" do visit admin_search_purchases_path(query: "user@example.com", product_title_query:) expect(page).to have_content("Graphic Design Course") expect(page).not_to have_content("Different Product") end it "renders the page for legacy search purchases URL" do visit admin_legacy_search_purchases_path(query: "user@example.com", product_title_query:) expect(page).to have_content("Graphic Design Course") expect(page).not_to have_content("Different Product") end it "shows clear button and clears product title filter" do different_product = create(:product, name: "Different Product") create(:purchase, email: "user@example.com", link: different_product) visit admin_search_purchases_path(query: "user@example.com", product_title_query:) click_link("Clear") expect(page).to have_current_path(admin_search_purchases_path(query: "user@example.com")) expect(page).to have_content("Graphic Design Course") expect(page).to have_content("Different 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/admin/pages_spec.rb
spec/requests/admin/pages_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Admin Pages Scenario", type: :system, js: true do let(:admin) { create(:named_user, :admin) } before do allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000) login_as(admin) end describe "Navigation" do context "with switching account to user as admin for seller" do let(:seller) { create(:named_seller) } include_context "with switching account to user as admin for seller" do let(:user_with_role_for_seller) { admin } end it "uses logged_in_user for navigation" do purchase = create(:purchase) visit admin_purchase_path(purchase) wait_for_ajax expect(page).to have_content user_with_role_for_seller.name end end end describe "Purchase" do it "shows the correct currency symbol" do product = create(:product, price_cents: 649, price_currency_type: "aud", name: "Tim Tam") purchase = create(:purchase, link: product, displayed_price_currency_type: :aud) visit admin_purchase_path(purchase) expect(page).to have_text("A$6.49 for Tim Tam") end end describe "Search" do let(:purchase) { create(:purchase) } before do visit admin_purchase_path(purchase) select_disclosure "Toggle Search" end it "searches users by query field" do fill_in "Search users (email, name, ID)", with: "joe@example.com\n" expect(page).to have_selector("h1", text: "Search for joe@example.com") end it "searches cards by all fields" do select("Visa", from: "card_type") fill_in("transaction_date", with: "02/22/2022") fill_in("last_4", with: "1234") fill_in("expiry_date", with: "02/22") fill_in("price", with: "9.99") click_on("Search") expect(page).to have_current_path(admin_search_purchases_path, ignore_query: true) query_values = Addressable::URI.parse(page.current_url).query_values expect(query_values["card_type"]).to eq("visa") expect(query_values["transaction_date"]).to eq("02/22/2022") expect(query_values["last_4"]).to eq("1234") expect(query_values["expiry_date"]).to eq("02/22") expect(query_values["price"]).to eq("9.99") end it "allows admins to search purchases by email" do product = create(:product, price_cents: 600, price_currency_type: "eur") offer_code = create(:offer_code, products: [product], amount_cents: 200, max_purchase_count: 1, currency_type: "eur") email = "searchme@gumroad.com" purchase = create(:purchase, link: product, email:, gumroad_tax_cents: 154, displayed_price_currency_type: :eur, rate_converted_to_usd: "0.86") offer_code.purchases << purchase visit admin_purchase_path(purchase) select_disclosure "Toggle Search" fill_in "Search purchases (email, IP, card, external ID)", with: "#{email}\n" expect(page).to have_selector("h2", text: "€6 + €1.32 VAT for #{product.name}") end it "allows admins to search purchases by credit card fingerprint" do purchase = create(:purchase, email: "foo@example.com", stripe_fingerprint: "FINGERPRINT_ONE") create(:purchase, email: "bar@example.com", stripe_fingerprint: "FINGERPRINT_ONE") create(:purchase, email: "baz@example.com", stripe_fingerprint: "FINGERPRINT_TWO") visit admin_purchase_path(purchase) click_link "VISA" expect(page).to have_content "foo@example.com" expect(page).to have_content "bar@example.com" expect(page).to have_no_content "baz@example.com" end it "shows external fingerprint link only for Stripe" do purchase = create(:purchase, stripe_fingerprint: "MY_FINGERPRINT") visit admin_purchase_path(purchase) expect(page).to have_content "MY_FINGERPRINT" purchase = create(:purchase, stripe_fingerprint: "MY_FINGERPRINT", charge_processor_id: BraintreeChargeProcessor.charge_processor_id) visit admin_purchase_path(purchase) expect(page).to have_no_content "MY_FINGERPRINT" end it "allows admins to infinitely scroll through purchase search results" do email = "searchme@gumroad.com" 30.times do |i| link = create(:product, name: "product ##{i}") create(:purchase, link:, email:, created_at: Time.current + i.hours) end visit admin_purchase_path(purchase) select_disclosure "Toggle Search" fill_in "Search purchases (email, IP, card, external ID)", with: "#{email}\n" expect(page).to have_text("product #29") expect(page).to have_text("product #28") expect(page).not_to have_text("product #0") first("main").scroll_to :bottom expect(page).to have_text("product #0") end end context "user products" do let(:creator) { create(:user) } it "displays product analytics stats", :sidekiq_inline, :elasticsearch_wait_for_refresh do product = create(:product_with_pdf_file, user: creator) recreate_model_index(ProductPageView) 2.times { add_page_view(product) } purchases = create_list(:purchase, 4, link: product) purchases.each do |purchase| create(:purchase_event, purchase:) end visit admin_user_path(creator) click_on "Products" expect(page).to have_text(product.name) expect(page).to have_text("2 views") expect(page).to have_text("4 sales") 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/products_spec.rb
spec/requests/admin/products_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Admin::LinksController Scenario", type: :system, js: true do let(:admin_user) { create(:admin_user) } let(:product) { create(:product) } before do login_as(admin_user) end it "renders the product page", :sidekiq_inline, :elasticsearch_wait_for_refresh do # It renders stats purchases = Purchase.where(link: product) Event.destroy_by(purchase: purchases) purchases.destroy_all recreate_model_index(ProductPageView) 2.times { add_page_view(product) } 25.times { create(:purchase_event, purchase: create(:purchase, link: product, price_cents: 200)) } visit admin_product_path(product.external_id) expect(page).to have_text(product.name) expect(page).to have_text("2 views") expect(page).to have_text("25 sales") expect(page).to have_text("$50 total") # With purchases, it renders purchases list toggle_disclosure("Purchases") wait_for_ajax click_on("Load more") wait_for_ajax expect(page).to_not have_text("Load more") expect(page).to have_text("$2", count: 25) # Product files display regular_file = create(:product_file, link: product, position: 1) external_link_file = create(:product_file, link: product, position: 2, filetype: "link", url: "https://example.com/external-resource") page.refresh expect(page).to have_link(regular_file.s3_filename) expect(page).to have_link(external_link_file.external_id) # It marks the product as staff-picked product = create(:product, :recommendable) visit admin_product_path(product.external_id) within_section(product.name, section_element: :article) do accept_confirm do click_on("Mark as staff-picked") end end wait_for_ajax expect(page).to have_alert(text: "Marked as staff-picked!") expect(product.reload.staff_picked?).to eq(true) # It deletes the product within_section(product.name, section_element: :article) do accept_confirm do click_on("Delete") end end wait_for_ajax expect(page).to have_alert(text: "Deleted!") expect(product.reload.deleted_at?).to eq(true) # It restores the product page.refresh within_section(product.name, section_element: :article) do accept_confirm do click_on("Undelete") end end wait_for_ajax expect(page).to have_alert(text: "Undeleted!") expect(product.reload.deleted_at?).to eq(false) # It publishes the product product.update!(purchase_disabled_at: Time.current) page.refresh within_section(product.name, section_element: :article) do accept_confirm do click_on("Publish") end end wait_for_ajax expect(page).to have_alert(text: "Published!") expect(product.reload.purchase_disabled_at?).to eq(false) # It unpublishes the product page.refresh within_section(product.name, section_element: :article) do accept_confirm do click_on("Unpublish") end end wait_for_ajax expect(page).to have_alert(text: "Unpublished!") expect(product.reload.purchase_disabled_at?).to eq(true) # It marks the product as adult within_section(product.name, section_element: :article) do accept_confirm do click_on("Make adult") end end wait_for_ajax expect(page).to have_alert(text: "It's adult!") expect(product.reload.is_adult?).to eq(true) # It marks the product as non-adult page.refresh within_section(product.name, section_element: :article) do accept_confirm do click_on("Make non-adult") end end wait_for_ajax expect(page).to have_alert(text: "It's not adult!") expect(product.reload.is_adult?).to eq(false) # it shows and post comments within_section(product.name, section_element: :article) do toggle_disclosure("0 comments") expect(page).to have_text("No comments created") fill_in("comment[content]", with: "Good article!") accept_confirm do click_on("Add comment") end wait_for_ajax expect(page).to have_text("1 comment") expect(page).to have_text("Good article!") end expect(page).to have_alert(text: "Successfully added comment.") end describe "mass refund for fraud" do let!(:purchase1) { create(:purchase, link: product) } let!(:purchase2) { create(:purchase, link: product) } it "allows selecting purchases and refunding for fraud" do visit admin_product_path(product.external_id) toggle_disclosure("Purchases") expect(page).to have_text("Select purchases to refund for fraud") expect(page).to have_button("Refund for Fraud", disabled: true) checkboxes = all("input[type='checkbox']") checkboxes.first.check expect(page).to have_text("1 purchase selected") expect(page).to have_button("Refund for Fraud", disabled: false) expect(page).to have_button("Clear selection") end it "allows selecting all purchases" do visit admin_product_path(product.external_id) toggle_disclosure("Purchases") expect(page).to have_text("Select purchases to refund for fraud") click_on("Select all") expect(page).to have_text("2 purchases selected") expect(page).to have_button("Clear selection") expect(page).not_to have_button("Select all") end it "clears selection when clicking clear selection" do visit admin_product_path(product.external_id) toggle_disclosure("Purchases") expect(page).to have_text("Select purchases to refund for fraud") click_on("Select all") expect(page).to have_text("2 purchases selected") click_on("Clear selection") expect(page).to have_text("Select purchases to refund for fraud") expect(page).to have_button("Refund for Fraud", disabled: true) end it "enqueues mass refund job when confirmed" do visit admin_product_path(product.external_id) toggle_disclosure("Purchases") expect(page).to have_text("Select purchases to refund for fraud") click_on("Select all") expect(page).to have_text("2 purchases selected") accept_confirm do click_on("Refund for Fraud") end expect(page).to have_alert(text: "Processing 2 fraud refunds") expect(MassRefundForFraudJob).to have_enqueued_sidekiq_job( product.id, array_including(purchase1.external_id, purchase2.external_id), admin_user.id ).on("default") 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/unreviewed_users_spec.rb
spec/requests/admin/unreviewed_users_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Admin::UnreviewedUsersController", type: :system, js: true do let(:admin) { create(:admin_user) } before do login_as(admin) end describe "GET /admin/unreviewed_users" do context "when no cached data exists" do before do $redis.del(RedisKey.unreviewed_users_data) end it "shows empty state message" do visit admin_unreviewed_users_path expect(page).to have_text("No unreviewed users with unpaid balance found") end end context "when cached data exists" do let!(:user_with_balance) do user = create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago, name: "Test Creator") create(:balance, user:, amount_cents: 5000) user end before do Admin::UnreviewedUsersService.cache_users_data! end it "displays the unreviewed users page" do visit admin_unreviewed_users_path expect(page).to have_text("Unreviewed users") end it "displays user information" do visit admin_unreviewed_users_path expect(page).to have_text(user_with_balance.external_id) expect(page).to have_text(user_with_balance.email) expect(page).to have_text("$50") end it "links to the user's admin page" do visit admin_unreviewed_users_path expect(page).to have_link(user_with_balance.external_id, href: admin_user_path(user_with_balance.external_id)) end it "shows the cutoff date in the header" do visit admin_unreviewed_users_path expect(page).to have_text("created since 2024-01-01") end end context "with revenue source badges" do let(:user) { create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) } let!(:balance) { create(:balance, user:, amount_cents: 5000) } it "shows sales badge when user has sales" do product = create(:product, user:) create(:purchase, seller: user, link: product, purchase_success_balance: balance) Admin::UnreviewedUsersService.cache_users_data! visit admin_unreviewed_users_path expect(page).to have_text("sales") end it "shows affiliate badge 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) Admin::UnreviewedUsersService.cache_users_data! visit admin_unreviewed_users_path expect(page).to have_text("affiliate") end it "shows collaborator badge 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) Admin::UnreviewedUsersService.cache_users_data! visit admin_unreviewed_users_path expect(page).to have_text("collaborator") end end context "filters out reviewed users" do let!(:user) do create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago) end before do create(:balance, user:, amount_cents: 5000) Admin::UnreviewedUsersService.cache_users_data! user.update!(user_risk_state: "compliant") end it "does not show users who were reviewed after caching" do visit admin_unreviewed_users_path expect(page).to have_text("No unreviewed users with unpaid balance found") 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/impersonate_spec.rb
spec/requests/admin/impersonate_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Impersonate", type: :system, js: true do include StripeMerchantAccountHelper let(:admin) { create(:admin_user, name: "Gumlord") } let(:seller) do user = create(:named_seller) create(:merchant_account, user:, charge_processor_merchant_id: create_verified_stripe_account(country: "US").id) user end before do login_as(admin) end it "impersonates and unimpersonates a seller using email" do impersonate_and_verify(seller, seller.email) end it "impersonates and unimpersonates a seller using username" do impersonate_and_verify(seller, seller.username) end it "impersonates and unimpersonates a seller using Stripe account ID" do impersonate_and_verify(seller, seller.merchant_accounts.sole.charge_processor_merchant_id) end def impersonate_and_verify(seller, identifier) visit "/admin" fill_in "Enter user email, username, or Stripe account ID", with: identifier click_on "Impersonate user" wait_for_ajax visit settings_main_path wait_for_ajax within_section "User details", section_element: :section do expect(page).to have_input_labelled "Email", with: seller.email end within "nav[aria-label='Main']" do toggle_disclosure(seller.display_name) click_on "Unbecome" wait_for_ajax expect(page.current_path).to eq(admin_path) 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/affiliates_spec.rb
spec/requests/admin/affiliates_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Admin::AffiliatesController Scenario", type: :system, js: true do let(:admin) { create(:admin_user) } let(:affiliate_user) { create(:affiliate_user) } before do login_as(admin) end context "when user has no affiliated products" do before do create(:direct_affiliate, affiliate_user:) end it "shows no products alert" do visit admin_affiliate_path(affiliate_user) click_on "Products" expect(page).to have_text("No affiliated products.") end end context "when user has affiliated products" do before do product_a = create(:product, unique_permalink: "a", name: "Product a", created_at: 1.minute.ago, updated_at: 1.minute.ago) product_b = create(:product, unique_permalink: "b", name: "Product b", created_at: 2.minutes.ago, updated_at: 2.minutes.ago) product_c = create(:product, unique_permalink: "c", name: "Product c", created_at: 3.minutes.ago, updated_at: 3.minutes.ago) create(:direct_affiliate, affiliate_user:, products: [product_a, product_b, product_c]) stub_const("Admin::Users::ListPaginatedProducts::PRODUCTS_PER_PAGE", 2) end it "shows products" do visit admin_affiliate_path(affiliate_user) click_on "Products" expect(page).to have_text("Product a") expect(page).to have_text("Product b") expect(page).not_to have_text("Product c") within("[aria-label='Pagination']") { click_on("2") } expect(page).not_to have_text("Product a") expect(page).not_to have_text("Product b") expect(page).to have_text("Product c") within("[aria-label='Pagination']") { expect(page).to have_command("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/admin/users_spec.rb
spec/requests/admin/users_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Admin::UsersController Scenario", type: :system, js: true do let(:admin) { create(:admin_user) } let(:user) { create(:user) } let!(:user_compliance_info) { create(:user_compliance_info, user:) } before do login_as(admin) end context "when user has no products" do it "shows no products alert" do visit admin_user_path(user.id) click_on "Products" expect(page).to have_text("No products created.") end end context "when user has products" do before do create(:product, user:, unique_permalink: "a", name: "Product a", created_at: 1.minute.ago) create(:product, user:, unique_permalink: "b", name: "Product b", created_at: 2.minutes.ago) create(:product, user:, unique_permalink: "c", name: "Product c", created_at: 3.minutes.ago) stub_const("Admin::Users::ListPaginatedProducts::PRODUCTS_PER_PAGE", 2) end it "shows products" do visit admin_user_path(user.id) click_on "Products" expect(page).to have_text("Product a") expect(page).to have_text("Product b") expect(page).not_to have_text("Product c") within("[aria-label='Pagination']") { click_on("2") } expect(page).not_to have_text("Product a") expect(page).not_to have_text("Product b") expect(page).to have_text("Product c") within("[aria-label='Pagination']") { expect(page).to have_button("1") } end end describe "user memberships" do context "when the user has no user memberships" do it "doesn't render user memberships" do visit admin_user_path(user.id) expect(page).not_to have_text("User memberships") end end context "when the user has user memberships" do let(:seller_one) { create(:user, :without_username) } let(:seller_two) { create(:user) } let(:seller_three) { create(:user) } let!(:team_membership_owner) { user.create_owner_membership_if_needed! } let!(:team_membership_one) { create(:team_membership, user:, seller: seller_one) } let!(:team_membership_two) { create(:team_membership, user:, seller: seller_two) } let!(:team_membership_three) { create(:team_membership, user:, seller: seller_three, deleted_at: 1.hour.ago) } it "renders user memberships" do visit admin_user_path(user.id) find_and_click "h3", text: "User memberships" expect(page).to have_text(seller_one.display_name(prefer_email_over_default_username: true)) expect(page).to have_text(seller_two.display_name(prefer_email_over_default_username: true)) expect(page).not_to have_text(seller_three.display_name(prefer_email_over_default_username: true)) end end end describe "custom fees" do context "when the user has a custom fee set" do before do user.update!(custom_fee_per_thousand: 50) end it "shows the custom fee percentage" do visit admin_user_path(user.id) expect(page).to have_text("Custom fee: 5.0%") end end context "when the user does not have a custom fee set" do it "does not show the custom fee heading" do visit admin_user_path(user.id) expect(page).not_to have_text("Custom fee:") end end it "allows setting new custom fee" do expect(user.reload.custom_fee_per_thousand).to be_nil visit admin_user_path(user.id) find_and_click "h3", text: "Custom fee" fill_in "custom_fee_percent", with: "2.5" click_on "Submit" accept_browser_dialog wait_for_ajax expect(user.reload.custom_fee_per_thousand).to eq(25) end it "allows updating the existing custom fee" do user.update(custom_fee_per_thousand: 50) expect(user.reload.custom_fee_per_thousand).to eq(50) visit admin_user_path(user.id) find_and_click "h3", text: "Custom fee" fill_in "custom_fee_percent", with: "2.5" click_on "Submit" accept_browser_dialog wait_for_ajax expect(user.reload.custom_fee_per_thousand).to eq(25) end it "allows clearing the existing custom fee" do user.update(custom_fee_per_thousand: 75) expect(user.reload.custom_fee_per_thousand).to eq(75) visit admin_user_path(user.id) find_and_click "h3", text: "Custom fee" fill_in "custom_fee_percent", with: "" click_on "Submit" accept_browser_dialog wait_for_ajax expect(user.reload.custom_fee_per_thousand).to be_nil end end describe "toggle adult products" do context "when the user is not marked as adult" do before do user.update!(all_adult_products: false) end it "shows 'Mark as adult' button" do visit admin_user_path(user.id) expect(page).to have_button("Mark as adult") expect(page).not_to have_button("Unmark as adult") end it "allows marking user as adult" do expect(user.reload.all_adult_products).to be(false) visit admin_user_path(user.id) click_on "Mark as adult" accept_browser_dialog wait_for_ajax expect(user.reload.all_adult_products).to be(true) expect(page).to have_button("Unmark as adult") expect(page).not_to have_button("Mark as adult") end end context "when the user is marked as adult" do before do user.update!(all_adult_products: true) end it "shows 'Unmark as adult' button" do visit admin_user_path(user.id) expect(page).to have_button("Unmark as adult") expect(page).not_to have_button("Mark as adult") end it "allows unmarking user as adult" do expect(user.reload.all_adult_products).to be(true) visit admin_user_path(user.id) click_on "Unmark as adult" accept_browser_dialog wait_for_ajax expect(user.reload.all_adult_products).to be(false) expect(page).to have_button("Mark as adult") expect(page).not_to have_button("Unmark as adult") end end context "when the user's all_adult_products is nil" do before do user.all_adult_products = nil user.save! end it "shows 'Mark as adult' button" do visit admin_user_path(user.id) expect(page).to have_button("Mark as adult") expect(page).not_to have_button("Unmark as adult") end it "allows marking user as adult" do visit admin_user_path(user.id) click_on "Mark as adult" accept_browser_dialog wait_for_ajax expect(user.reload.all_adult_products).to be(true) expect(page).to have_button("Unmark as adult") expect(page).not_to have_button("Mark as adult") end end end describe "blocked user indicator" do before { BlockedObject.delete_all } after { BlockedObject.delete_all } it "shows blocked user indicator with appropriate tooltips for email and domain blocks" do # Initially no block should exist visit admin_user_path(user.id) expect(page).not_to have_css(".icon-solid-shield-exclamation") # Block by email BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email], user.form_email, admin.id) page.refresh # Verify icon appears and tooltip shows email block expect(page).to have_css(".icon-solid-shield-exclamation") icon = find(".icon-solid-shield-exclamation") icon.hover expect(page).to have_text("Email blocked") expect(page).to have_text("block created") # Add domain block BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], user.form_email_domain, admin.id) page.refresh # Verify icon still appears and tooltip shows both blocks expect(page).to have_css(".icon-solid-shield-exclamation") icon = find(".icon-solid-shield-exclamation") icon.hover expect(page).to have_text("Email blocked") expect(page).to have_text("#{user.form_email_domain} blocked") expect(page).to have_text("block created") 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/purchases_spec.rb
spec/requests/admin/purchases_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Admin::PurchasesController Scenario", type: :system, js: true do let(:admin) { create(:admin_user) } let(:purchase) { create(:purchase, purchaser: create(:user), is_deleted_by_buyer: true) } before do login_as(admin) end describe "undelete functionality" do it "shows undelete button for deleted purchases" do visit admin_purchase_path(purchase.id) expect(page).to have_button("Undelete") end it "does not show undelete button for non-deleted purchases" do purchase.update!(is_deleted_by_buyer: false) visit admin_purchase_path(purchase.id) expect(page).not_to have_button("Undelete") end it "allows undeleting purchase" do expect(purchase.reload.is_deleted_by_buyer).to be(true) visit admin_purchase_path(purchase.id) click_on "Undelete" accept_browser_dialog wait_for_ajax expect(purchase.reload.is_deleted_by_buyer).to be(false) expect(page).to have_button("Undeleted!") end end describe "resend receipt functionality" do let(:new_email) { "newemail@example.com" } before do purchase.update!(is_deleted_by_buyer: false) end def resend_receipt(email: nil) fill_in "resend_receipt[email_address]", with: email click_on "Send" accept_browser_dialog wait_for_ajax end it "successfully resends receipt with a valid email" do visit admin_purchase_path(purchase.id) find("summary", text: "Resend receipt").click # With the original email resend_receipt expect(page).to have_alert(text: "Receipt sent successfully.") expect(purchase.reload.email).to eq(purchase.email) # With a new email new_email = "newemail@example.com" resend_receipt(email: new_email) expect(page).to have_alert(text: "Receipt sent successfully.") expect(purchase.reload.email).to eq(new_email) # With an invalid email, fails with validation error error = ActiveRecord::RecordInvalid.new(purchase) allow(error).to receive(:message).and_return("Validation failed: Email is invalid") allow_any_instance_of(Purchase).to receive(:save!).and_raise(error) resend_receipt(email: "test@example.com") expect(page).to have_alert(text: "Validation failed: Email is invalid") expect(purchase.reload.email).to eq(purchase.email) end end describe "tip display" do it "shows tip amount correctly when purchase has a tip" do create(:tip, purchase: purchase, value_usd_cents: 500) visit admin_purchase_path(purchase.id) expect(page).to have_content("Tip $5", normalize_ws: true) end end describe "seller support email display" do it "shows seller support email when present" do support_email = "support@seller.com" purchase.seller.update!(support_email: support_email) visit admin_purchase_path(purchase.id) within_section("Info", section_element: :div, exact: true, match: :first) do expect(page).to have_content("Seller support email") expect(page).to have_content(support_email) end end it "does not show seller support email when not present" do purchase.seller.update!(support_email: nil) visit admin_purchase_path(purchase.id) within_section("Info", section_element: :div, exact: true, match: :first) do expect(page).not_to have_content("Seller support email") expect(page).to have_content("Seller email") end end end it "shows custom fields" do create(:purchase_custom_field, purchase:) create(:purchase_custom_field, purchase:, name: "Boolean field", field_type: CustomField::TYPE_CHECKBOX, value: true) visit admin_purchase_path(purchase.id) expect(page).to have_content("Custom field custom field value (custom field) Boolean field true (custom field)", normalize_ws: true) end describe "update giftee email functionality" do let(:giftee_email) { "original_giftee@example.com" } let(:new_giftee_email) { "new_giftee@example.com" } let(:gifter_purchase) { create(:purchase, :gift_sender) } let(:giftee_purchase) { create(:purchase, :gift_receiver, email: giftee_email) } let!(:gift) { create(:gift, gifter_email: gifter_purchase.email, giftee_email: giftee_email, gifter_purchase: gifter_purchase, giftee_purchase: giftee_purchase) } it "allows updating giftee email for a gift purchase" do visit admin_purchase_path(gifter_purchase.id) select_disclosure "Edit giftee email" do fill_in "giftee_email", with: new_giftee_email click_on "Update" end expect(page).to have_alert(text: "Successfully updated the giftee email.") expect(gift.reload.giftee_email).to eq(new_giftee_email) expect(giftee_purchase.reload.email).to eq(new_giftee_email) end end describe "discount display" do it "displays discount code when offer_code has a code" do product = create(:product, price_cents: 1000) offer_code = create(:percentage_offer_code, products: [product], amount_percentage: 20, code: "SAVE20") purchase = create(:purchase, link: product) offer_code.purchases << purchase visit admin_purchase_path(purchase) expect(page).to have_text("Discount code") expect(page).to have_text("SAVE20 for 20% off") end it "displays discount without code when offer_code.code is nil" do seller = create(:user) product = create(:product, user: seller, price_cents: 1000) upsell_offer_code = OfferCode.new( user: seller, code: nil, amount_percentage: 15, universal: false ) upsell_offer_code.products << product upsell_offer_code.save!(validate: false) create(:upsell, seller: seller, product: product, cross_sell: true, offer_code: upsell_offer_code) purchase = create(:purchase, link: product) upsell_offer_code.purchases << purchase visit admin_purchase_path(purchase) expect(page).not_to have_text("Discount code") expect(page).to have_text("Discount") expect(page).to have_text("15% off") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/subscription/tiered_membership_payment_updates_specs.rb
spec/requests/subscription/tiered_membership_payment_updates_specs.rb
# frozen_string_literal: true require "spec_helper" describe "Tiered Membership Spec for Payment/Settings updates", type: :system, js: true do include ManageSubscriptionHelpers include ProductWantThisHelpers include CurrencyHelper let(:gift) { null } before do setup_subscription(gift:) travel_to(@originally_subscribed_at + 1.month) setup_subscription_token end context "updating card on file" do it "triggers the reCAPTCHA verification" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" # Assert that the reCAPTCHA iframe is rendered expect(page).to have_selector("#payButtonRecaptcha iframe") expect(page).to have_alert(text: "Your membership has been updated.") end context "with a valid card" do it "updates the card" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to_not have_text("Your first charge will be on") expect(page).to_not have_text("Your membership is paid up until") expect(page).to_not have_text("Add your own payment method below to ensure that your membership renews.") click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" expect(page).to have_alert(text: "Your membership has been updated.") @subscription.reload @user.reload expect(@subscription.credit_card).to be expect(@subscription.credit_card).not_to eq @credit_card expect(@user.credit_card).to be expect(@user.credit_card).not_to eq @credit_card end context "when the price has changed" do before do @original_tier_quarterly_price.update!(price_cents: 1000) end it "updates the card without changing the price" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.current_plan_displayed_price_cents).to eq(599) end end context "when the price has changed and is now 0" do before do @original_tier_quarterly_price.update!(price_cents: 0) end it "still allows updating the card" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.current_plan_displayed_price_cents).to eq(599) end end end context "with an invalid card" do it "does not update the card and returns an error message" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:decline)) click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Please check your card information, we couldn't verify it.") @subscription.reload @user.reload expect(@subscription.credit_card).to be expect(@subscription.credit_card).to eq @credit_card expect(@user.credit_card).to be expect(@user.credit_card).to eq @credit_card end end context "for a test subscription" do it "does not let the user update the card when signed in" do @subscription.update!(is_test_subscription: true) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_selector(".test_card") expect(page).not_to have_selector(".use_different_card") end end end context "switching from PayPal to credit card" do it "allows switching even if the creator does not have pay with PayPal enabled" do allow_any_instance_of(User).to receive(:pay_with_paypal_enabled?).and_return(false) paypal_card = create(:credit_card, chargeable: build(:paypal_chargeable)) @subscription.update!(credit_card: paypal_card) @subscription.user.update!(credit_card: paypal_card) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Pay with card instead?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" expect(page).to have_alert(text: "Your membership has been updated.") @subscription.reload @user.reload expect(@subscription.credit_card).to be expect(@subscription.credit_card).not_to eq paypal_card expect(@user.credit_card).to be expect(@user.credit_card).not_to eq paypal_card end end context "setting additional information" do context "when the product requires shipping info" do before :each do @product.update!(require_shipping: true) @original_purchase.update!(full_name: "Jim Gumroad", street_address: "805 St Cloud Road", city: "Los Angeles", state: "CA", zip_code: "11111", country: "United States") end it "allows the user to set their name, email, and address" do buyer_email = generate(:email) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" fill_in "Email", with: buyer_email fill_in "Full name", with: "Jane Gumroad" fill_in "Street address", with: "100 Main St" fill_in "City", with: "San Francisco" select "CA", from: "state" fill_in "ZIP code", with: "00000" select "United States", from: "country" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") @original_purchase.reload expect(@original_purchase.email).to eq buyer_email expect(@original_purchase.full_name).to eq "Jane Gumroad" expect(@original_purchase.street_address).to eq "100 Main St" expect(@original_purchase.city).to eq "San Francisco" expect(@original_purchase.state).to eq "CA" expect(@original_purchase.zip_code).to eq "00000" expect(@original_purchase.country).to eq "United States" end it "requires address to be present" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" fill_in "Full name", with: "" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Full name can't be blank") fill_in "Full name", with: @original_purchase.full_name fill_in "Street address", with: "" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Street address can't be blank") fill_in "Street address", with: @original_purchase.street_address fill_in "City", with: "" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "City can't be blank") fill_in "City", with: @original_purchase.city fill_in "ZIP code", with: "" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Zip code can't be blank") end end context "when the product does not require shipping info" do it "only allows the user to set their email" do new_email = generate(:email) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).not_to have_field("Full name") expect(page).not_to have_field("Street address") expect(page).not_to have_field("City") expect(page).not_to have_field("State") expect(page).not_to have_field("State Select") expect(page).not_to have_field("Country") expect(page).not_to have_field("ZIP code") fill_in "Email", with: new_email click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") @original_purchase.reload expect(@original_purchase.email).to eq new_email end end it "requires email to be present" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" fill_in "Email", with: "" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Validation failed: valid email required") end end context "coming from a declined charge email and charge fails again" do it "does not enqueue declined card tasks" do allow(ChargeProcessor).to receive(:create_payment_intent_or_charge!).and_raise ChargeProcessorCardError, "unknown error" expect(CustomerLowPriorityMailer).to_not receive(:subscription_card_declined) visit "/subscriptions/#{@subscription.external_id}/manage?declined=true" click_on "Second Tier" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Please check your card information, we couldn't verify it.") end end it "allows updating the membership's credit card to an Indian card which requires SCA and mandate" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success_indian_card_mandate)) click_on "Update membership" wait_for_ajax sleep 1 within_sca_frame do find_and_click("button:enabled", text: /COMPLETE/) end expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.credit_card).not_to eq @credit_card expect(@subscription.credit_card).to be expect(@subscription.credit_card.stripe_setup_intent_id).to be_present expect(Stripe::SetupIntent.retrieve(@subscription.credit_card.stripe_setup_intent_id).mandate).to be_present end context "giftee using the manage membership" do let(:gift) { create(:gift, giftee_email: "giftee@gumroad.com") } it "displays a notice about the card, updates the card on file, and upgrades membership" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_text("Your membership is paid up until") expect(page).to have_text("Add your own payment method below to ensure that your membership renews.") expect(find_field("Email").value).to eq @subscription.email expect(@subscription.credit_card).to be_nil fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" expect(page).to have_alert(text: "Your membership has been updated.") @subscription.reload expect(@subscription.credit_card).to be_present travel_to(@subscription.end_time_of_subscription + 1.day) @subscription.charge! visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" click_on "Update membership" expect(page).to have_button("Update membership", disabled: false) expect(page).to have_alert(text: "Your membership has been updated.") @subscription.reload expect(@subscription.gift?).to be true expect(@subscription.true_original_purchase).to have_attributes( is_gift_sender_purchase: true, price_cents: 599 ) expect(@subscription.original_purchase).to have_attributes( is_gift_sender_purchase: false, price_cents: 1050 ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/subscription/installment_plan_spec.rb
spec/requests/subscription/installment_plan_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Installment Plans", type: :system, js: true do include ManageSubscriptionHelpers let(:seller) { create(:user) } let(:buyer) { create(:user) } let(:credit_card) { create(:credit_card) } let(:product) { create(:product, :with_installment_plan, user: seller, price_cents: 30_00) } RSpec.shared_context "setup installment plan subscription" do |started_at: Time.current| let(:subscription) { create(:subscription, is_installment_plan: true, credit_card:, user: buyer, link: product) } let(:purchase) { create(:installment_plan_purchase, subscription:, link: product, credit_card:, purchaser: buyer) } before do travel_to(started_at) do subscription purchase end setup_subscription_token(subscription:) end end context "paid in full" do include_context "setup installment plan subscription" it "404s when the installment plan has been paid in full" do subscription.end_subscription! visit manage_subscription_path(subscription.external_id, token: subscription.token) expect(page).to have_text("Not Found") end end context "active with overdue charges" do include_context "setup installment plan subscription", started_at: 33.days.ago it "allows updating the installment plan's credit card and charges the new card" do visit manage_subscription_path(subscription.external_id, token: subscription.token) click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) expect(page).to have_text "You'll be charged US$10 today." expect do click_on "Update installment plan" wait_for_ajax expect(page).to have_alert(text: "Your installment plan has been updated") end .to change { subscription.purchases.successful.count }.by(1) .and change { subscription.reload.credit_card }.from(credit_card).to(be_present) end end context "active with no overdue charges" do include_context "setup installment plan subscription" it "displays the payment method that'll be used for future charges" do visit manage_subscription_path(subscription.external_id, token: subscription.token) expect(page).to have_selector("[aria-label=\"Saved credit card\"]", text: /#{ChargeableVisual.get_card_last4(credit_card.visual)}$/) end it "allows updating the installment plan's credit card" do visit manage_subscription_path(subscription.external_id, token: subscription.token) click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) expect do click_on "Update installment plan" wait_for_ajax expect(page).to have_alert(text: "Your installment plan has been updated.") end .to change { subscription.purchases.successful.count }.by(0) .and change { subscription.reload.credit_card }.from(credit_card).to(be_present) end it "does not allow cancelling" do visit manage_subscription_path(subscription.external_id, token: subscription.token) expect(page).not_to have_button("Cancel") end end context "failed" do include_context "setup installment plan subscription", started_at: 40.days.ago before { subscription.unsubscribe_and_fail! } it "allows updating the installment plan's credit card and charges the new card" do visit manage_subscription_path(subscription.external_id, token: subscription.token) click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) expect(page).to have_text "You'll be charged US$10 today." expect do click_on "Restart installment plan" wait_for_ajax expect(page).to have_alert(text: "Installment plan restarted") end .to change { subscription.purchases.successful.count }.by(1) .and change { subscription.reload.credit_card }.from(credit_card).to(be_present) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/subscription/non_tiered_membership_spec.rb
spec/requests/subscription/non_tiered_membership_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Non Tiered Membership Subscriptions", type: :system, js: true do include ManageSubscriptionHelpers include ProductWantThisHelpers context "that are active" do before :each do @originally_subscribed_at = Time.utc(2020, 04, 01) travel_to @originally_subscribed_at do product = create(:subscription_product, user: create(:user), name: "This is a subscription product", subscription_duration: BasePrice::Recurrence::MONTHLY, price_cents: 12_99) @variant = create(:variant, variant_category: create(:variant_category, link: product)) @monthly_price = product.prices.find_by!(recurrence: BasePrice::Recurrence::MONTHLY) @quarterly_price = create(:price, link: product, recurrence: BasePrice::Recurrence::QUARTERLY, price_cents: 30_00) @yearly_price = create(:price, link: product, recurrence: BasePrice::Recurrence::YEARLY, price_cents: 99_99) @subscription_without_purchaser = create(:subscription, user: nil, credit_card: create(:credit_card, card_type: "paypal", braintree_customer_id: "blah", visual: "test@gum.co"), link: product) create(:purchase, is_original_subscription_purchase: true, link: product, subscription: @subscription_without_purchaser, credit_card: @subscription_without_purchaser.credit_card) @purchaser = create(:user, credit_card: create(:credit_card, chargeable: build(:chargeable, card: StripePaymentMethodHelper.success_charge_decline))) @credit_card = create(:credit_card) @subscription_with_purchaser = create(:subscription, credit_card: @credit_card, user: @purchaser, link: product, price: @quarterly_price) @purchase = create(:purchase, is_original_subscription_purchase: true, link: product, subscription: @subscription_with_purchaser, credit_card: @credit_card, price: @quarterly_price, variant_attributes: [@variant], price_cents: @quarterly_price.price_cents) end allow_any_instance_of(Stripe::SetupIntentsController).to receive(:mandate_options_for_stripe).and_return({ payment_method_options: { card: { mandate_options: { reference: StripeChargeProcessor::MANDATE_PREFIX + SecureRandom.hex, amount_type: "maximum", amount: 100_00, currency: "usd", start_date: Time.current.to_i, interval: "sporadic", supported_types: ["india"] } } } }) travel_to @originally_subscribed_at + 1.month setup_subscription_token(subscription: @subscription_with_purchaser) end it "displays the payment method that'll be used for future charges" do visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" expect(page).to have_selector("[aria-label=\"Saved credit card\"]", text: /#{ChargeableVisual.get_card_last4(@credit_card.visual)}$/) end it "allows updating the subscription's credit card" do visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription_with_purchaser.reload.credit_card).not_to eq @credit_card expect(@subscription_with_purchaser.credit_card).to be_present expect(@subscription_with_purchaser.price.id).to eq(@quarterly_price.id) # Make sure recurring charges with the new card succeed expect do travel_to(@subscription_with_purchaser.end_time_of_subscription + 1.day) do @subscription_with_purchaser.charge! end end.to change { @subscription_with_purchaser.purchases.successful.count }.by(1) end it "allows updating the subscription's credit card to an SCA-enabled card" do visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success_with_sca)) click_on "Update membership" wait_for_ajax sleep 1 within_sca_frame do find_and_click("button:enabled", text: /COMPLETE/) end expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription_with_purchaser.reload.credit_card).not_to eq @credit_card expect(@subscription_with_purchaser.credit_card).to be # Make sure recurring charges with the new card succeed expect do travel_to(@subscription_with_purchaser.end_time_of_subscription + 1.day) do @subscription_with_purchaser.charge! end end.to change { @subscription_with_purchaser.purchases.successful.count }.by(1) end it "does not update the subscription's credit card if SCA fails" do visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success_with_sca)) click_on "Update membership" wait_for_ajax sleep 1 within_sca_frame do find_and_click("button:enabled", text: /FAIL/) end expect(page).to have_alert(text: "We are unable to authenticate your payment method. Please choose a different payment method and try again.") expect(@subscription_with_purchaser.reload.credit_card).to eq @credit_card end it "allows updating the subscription's credit card to an Indian card which requires SCA and mandate" do visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success_indian_card_mandate)) click_on "Update membership" wait_for_ajax sleep 1 within_sca_frame do find_and_click("button:enabled", text: /COMPLETE/) end expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription_with_purchaser.reload.credit_card).not_to eq @credit_card expect(@subscription_with_purchaser.credit_card).to be expect(@subscription_with_purchaser.credit_card.stripe_setup_intent_id).to be_present expect(Stripe::SetupIntent.retrieve(@subscription_with_purchaser.credit_card.stripe_setup_intent_id).mandate).to be_present end context "changing plans" do it "allows upgrading the subscription recurrence" do visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" select "Yearly", from: "Recurrence" expect(page).to have_text "You'll be charged US$80.21 today" # prorated price 1 month into the billing period expect do click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") end.to change { @subscription_with_purchaser.purchases.successful.count }.by(1) .and change { @subscription_with_purchaser.purchases.not_charged.count }.by(1) expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(@subscription_with_purchaser.purchases.last.id).on("critical") price = @subscription_with_purchaser.reload.price expect(price.id).to eq(@yearly_price.id) expect(price.recurrence).to eq(BasePrice::Recurrence::YEARLY) purchase = @subscription_with_purchaser.purchases.last expect(purchase.successful?).to eq(true) expect(purchase.id).to_not eq(@purchase.id) expect(purchase.displayed_price_cents).to eq(80_21) expect(@purchase.reload.is_archived_original_subscription_purchase?).to eq true new_template_purchase = @subscription_with_purchaser.original_purchase expect(new_template_purchase.id).not_to eq @purchase.id expect(new_template_purchase.displayed_price_cents).to eq 99_99 expect(new_template_purchase.variant_attributes).to eq [@variant] end it "allows downgrading the subscription recurrence" do visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" select "Monthly", from: "Recurrence" expect(page).not_to have_text "You'll be charged" expect do expect do click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") end.not_to have_enqueued_mail(CustomerMailer, :receipt) end.to change { @subscription_with_purchaser.purchases.successful.count }.by(0) .and change { @subscription_with_purchaser.purchases.not_charged.count }.by(0) expect(@subscription_with_purchaser.reload.subscription_plan_changes.count).to eq 1 expect(@subscription_with_purchaser.price.recurrence).to eq "quarterly" expect(@subscription_with_purchaser.original_purchase.displayed_price_cents).to eq 30_00 plan_change = @subscription_with_purchaser.subscription_plan_changes.first expect(plan_change.recurrence).to eq "monthly" expect(plan_change.perceived_price_cents).to eq 12_99 end end it "allow to cancel and restart membership" do visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" click_on "Cancel membership" wait_for_ajax expect(page).to have_button("Cancelled", disabled: true) expect(page).to have_button("Restart membership") click_on "Restart membership" wait_for_ajax expect(page).to(have_alert(text: "Membership restarted")) expect(page).to have_button("Update membership") expect(page).to have_button("Cancel membership") end end context "that are inactive" do before do travel_to(1.month.ago) do product = create(:subscription_product) @credit_card = create(:credit_card, chargeable: build(:chargeable, card: StripePaymentMethodHelper.success)) @subscription_without_purchaser = create(:subscription, user: nil, credit_card: @credit_card, link: product, cancelled_at: 1.week.from_now, deactivated_at: 1.week.from_now, cancelled_by_buyer: true) create(:purchase, is_original_subscription_purchase: true, link: product, subscription: @subscription_without_purchaser, created_at: 1.month.ago, credit_card: @credit_card) @purchaser = create(:user, credit_card: @credit_card) @subscription_with_purchaser = create(:subscription, credit_card: @credit_card, user: @purchaser, link: product, failed_at: Time.current, deactivated_at: Time.current) create(:purchase, is_original_subscription_purchase: true, link: product, subscription: @subscription_with_purchaser, created_at: 1.month.ago, credit_card: @credit_card) create(:purchase, link: product, subscription: @subscription_with_purchaser, purchase_state: "failed", credit_card: @credit_card) end setup_subscription_token(subscription: @subscription_with_purchaser) setup_subscription_token(subscription: @subscription_without_purchaser) end it "displays existing payment method and does not show cancel membership button" do visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" expect(page).to have_selector("[aria-label=\"Saved credit card\"]", text: /#{ChargeableVisual.get_card_last4(@credit_card.visual)}$/) expect(page).not_to have_button("Cancel") end it "restarts membership with existing payment method" do visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" click_on "Restart membership" wait_for_ajax expect(page).to(have_alert(text: "Membership restarted")) expect(@subscription_with_purchaser.reload.alive?(include_pending_cancellation: false)).to be(true) expect(@subscription_with_purchaser.purchases.successful.count).to eq(2) end it "restarts membership when product has required custom fields" do product = @subscription_with_purchaser.link product.custom_fields.create!( name: "Favorite Color", required: true, field_type: "text", seller_id: product.user.id ) product.custom_fields.create!( name: "http://example.com/terms", required: true, field_type: "terms", seller_id: product.user.id ) visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" click_on "Restart membership" wait_for_ajax expect(page).to(have_alert(text: "Membership restarted")) expect(@subscription_with_purchaser.reload.alive?(include_pending_cancellation: false)).to be(true) expect(@subscription_with_purchaser.purchases.successful.count).to eq(2) end it "restarts membership with new payment method and updates the card for the subscription but not the user's card" do visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Restart membership" wait_for_ajax expect(page).to(have_alert(text: "Membership restarted")) expect(@subscription_with_purchaser.reload.alive?(include_pending_cancellation: false)).to be(true) expect(@subscription_with_purchaser.purchases.successful.count).to eq(2) expect(@subscription_with_purchaser.credit_card_id).not_to eq @credit_card.id expect(@subscription_with_purchaser.user.credit_card_id).to eq @credit_card.id end it "does not restart if charge fails on existing card" do credit_card = create(:credit_card, chargeable: build(:chargeable, card: StripePaymentMethodHelper.success_charge_decline)) @subscription_with_purchaser.update!(credit_card:) @purchaser.update!(credit_card:) visit "/subscriptions/#{@subscription_with_purchaser.external_id}/manage?token=#{@subscription_with_purchaser.token}" click_on "Restart membership" wait_for_ajax expect(page).to have_alert(text: "Your card was declined.") expect(@subscription_with_purchaser.reload.alive?(include_pending_cancellation: false)).to be(false) expect(@subscription_with_purchaser.purchases.successful.count).to eq(1) expect(@subscription_with_purchaser.purchases.failed.count).to eq(1) end context "without a purchaser" do it "restarts membership with the existing payment method" do visit "/subscriptions/#{@subscription_without_purchaser.external_id}/manage?token=#{@subscription_without_purchaser.token}" click_on "Restart membership" wait_for_ajax expect(page).to(have_alert(text: "Membership restarted")) expect(@subscription_without_purchaser.reload.alive?(include_pending_cancellation: false)).to be(true) expect(@subscription_without_purchaser.purchases.successful.count).to eq(2) expect(@subscription_without_purchaser.credit_card_id).to eq @credit_card.id end it "restarts membership with new payment method and updates the card for user" do visit "/subscriptions/#{@subscription_without_purchaser.external_id}/manage?token=#{@subscription_without_purchaser.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Restart membership" expect(page).to(have_alert(text: "Membership restarted")) expect(@subscription_without_purchaser.reload.alive?(include_pending_cancellation: false)).to be(true) expect(@subscription_without_purchaser.purchases.successful.count).to eq(2) expect(@subscription_without_purchaser.credit_card_id).not_to eq @credit_card.id end end it "does not restart if charge fails on existing card" do credit_card = create(:credit_card, chargeable: build(:chargeable, card: StripePaymentMethodHelper.success_charge_decline)) @subscription_without_purchaser.update!(credit_card:) visit "/subscriptions/#{@subscription_without_purchaser.external_id}/manage?token=#{@subscription_without_purchaser.token}" click_on "Restart membership" wait_for_ajax expect(page).to have_alert(text: "Your card was declined.") expect(@subscription_without_purchaser.reload.alive?(include_pending_cancellation: false)).to be(false) expect(@subscription_without_purchaser.purchases.count).to eq(1) end it "does not restart membership or update card if charge fails on new card" do visit "/subscriptions/#{@subscription_without_purchaser.external_id}/manage?token=#{@subscription_without_purchaser.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success_charge_decline)) click_on "Restart membership" wait_for_ajax expect(page).to have_alert(text: "Your card was declined.") expect(@subscription_without_purchaser.reload.alive?(include_pending_cancellation: false)).to be(false) expect(@subscription_without_purchaser.purchases.count).to eq(1) end end context "that are overdue for charge but not inactive" do it "allows the user to update their card and charges the new card" do travel_to(1.month.ago) product = create(:subscription_product) credit_card = create(:credit_card, chargeable: build(:chargeable, card: StripePaymentMethodHelper.success)) subscription = create(:subscription, user: nil, credit_card:, link: product) create(:purchase, is_original_subscription_purchase: true, link: product, subscription:, created_at: 1.month.ago, credit_card:) create(:purchase, link: product, subscription:, purchase_state: "failed", credit_card:) travel_back setup_subscription_token(subscription: subscription) visit "/subscriptions/#{subscription.external_id}/manage?token=#{subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(subscription.reload.credit_card).not_to eq credit_card expect(subscription.credit_card).to be_present expect(subscription.purchases.successful.count).to eq 2 end end context "that are for physical products" do # we have some historical physical subscription products before do product = create(:physical_product, price_cents: 27_00, subscription_duration: "monthly") product.is_recurring_billing = true product.save(validate: false) price = product.prices.first price.update!(recurrence: "monthly") @credit_card = create(:credit_card) @subscription = create(:subscription, link: product, credit_card: @credit_card, price:) create(:physical_purchase, link: product, subscription: @subscription, is_original_subscription_purchase: true, variant_attributes: [product.skus.first]) setup_subscription_token end it "allows updating the subscription's credit card" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" click_on "Yes, it is" # verify shipping address wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.credit_card).not_to eq @credit_card expect(@subscription.credit_card).to be_present end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/subscription/tiered_membership_fixed_length_spec.rb
spec/requests/subscription/tiered_membership_fixed_length_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Tiered Memberships Fixed Length Spec", type: :system, js: true do include ManageSubscriptionHelpers before :each do setup_subscription @subscription.update!(charge_occurrence_count: 4) travel_to(@originally_subscribed_at + 1.month) setup_subscription_token end it "allows the user to update the credit card" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" expect(page).to have_alert(text: "Your membership has been updated.") @subscription.reload @user.reload expect(@subscription.credit_card).to be expect(@subscription.credit_card).not_to eq @credit_card expect(@user.credit_card).to be expect(@user.credit_card).to eq @credit_card end it "allows the user to set their name, email, and address when applicable" do @product.update!(require_shipping: true) @original_purchase.update!(full_name: "Jim Gumroad", street_address: "805 St Cloud Road", city: "Los Angeles", state: "CA", zip_code: "11111", country: "United States") buyer_email = generate(:email) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" fill_in "Email", with: buyer_email fill_in "Full name", with: "Jane Gumroad" fill_in "Street address", with: "100 Main St" fill_in "City", with: "San Francisco" select "CA", from: "State" fill_in "ZIP code", with: "00000" select "United States", from: "Country" click_on "Update membership" click_on "Yes, it is" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") @original_purchase.reload expect(@original_purchase.email).to eq buyer_email expect(@original_purchase.full_name).to eq "Jane Gumroad" expect(@original_purchase.street_address).to eq "100 Main St" expect(@original_purchase.city).to eq "San Francisco" expect(@original_purchase.state).to eq "CA" expect(@original_purchase.zip_code).to eq "00000" expect(@original_purchase.country).to eq "United States" end it "does not allow the user to change tier" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$6.55" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Changing plans for fixed-length subscriptions is not currently supported.") end it "does not allow the user to change recurrence" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" select("Yearly", from: "Recurrence") # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$6.05" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Changing plans for fixed-length subscriptions is not currently supported.") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/subscription/magic_link_page_spec.rb
spec/requests/subscription/magic_link_page_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Membership magic link page", type: :system, js: true do include ManageSubscriptionHelpers before { setup_subscription } context "when the buyer is logged in" do it "allows the user to access the manage page" do sign_in @subscription.user visit "/subscriptions/#{@subscription.external_id}/manage" expect(page).to_not have_current_path(magic_link_subscription_path(@subscription.external_id)) end end context "when the logged in user is admin" do it "allows the user to access the manage page" do admin = create(:user, is_team_member: true) sign_in admin visit "/subscriptions/#{@subscription.external_id}/manage" expect(page).to_not have_current_path(magic_link_subscription_path(@subscription.external_id)) end end context "when the encrypted cookie is present" do it "allows the user to access the manage page" do # first visit using a token to get the cookie setup_subscription_token visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" # second visit without token, using the cookie visit "/subscriptions/#{@subscription.external_id}/manage" expect(page).to_not have_current_path(magic_link_subscription_path(@subscription.external_id)) end end context "when the logged in user is the seller" do it "doesn't allow the user to access the manage page" do sign_in @subscription.seller visit "/subscriptions/#{@subscription.external_id}/manage" expect(page).to have_current_path(magic_link_subscription_path(@subscription.external_id)) end end context "when the token is invalid" do it "shows the magic link page with the right message" do setup_subscription_token visit "/subscriptions/#{@subscription.external_id}/manage?token=invalid" expect(page).to have_current_path(magic_link_subscription_path(@subscription.external_id, invalid: true)) expect(page).to have_text "Your magic link has expired" expect(page).to have_text "Send magic link" end end context "when there's only one email linked to the subscription" do it "asks to use a magic link to access the manage page" do visit "/subscriptions/#{@subscription.external_id}/manage" expect(page).to have_current_path(magic_link_subscription_path(@subscription.external_id)) expect(page).to have_text "You're currently not signed in" expect(page).to have_text @subscription.link.name expect(page).to_not have_text @subscription.email expect(page).to have_text EmailRedactorService.redact(@subscription.email) expect(page).to have_text "Send magic link" mail_double = double allow(mail_double).to receive(:deliver_later) expect(CustomerMailer).to receive(:subscription_magic_link).with(@subscription.id, @subscription.email).and_return(mail_double) click_on "Send magic link" expect(page).to have_current_path(magic_link_subscription_path(@subscription.external_id)) expect(page).to have_text "We've sent a link to" expect(page).to have_text "Resend magic link" end it "resends the magic link" do visit "/subscriptions/#{@subscription.external_id}/manage" mail_double = double allow(mail_double).to receive(:deliver_later) expect(CustomerMailer).to receive(:subscription_magic_link).with(@subscription.id, @subscription.email).and_return(mail_double) click_on "Send magic link" expect(page).to have_current_path(magic_link_subscription_path(@subscription.external_id)) expect(page).to have_text "We've sent a link to" expect(page).to have_text "Resend magic link" expect(CustomerMailer).to receive(:subscription_magic_link).with(@subscription.id, @subscription.email).and_return(mail_double) click_on "Resend magic link" expect(page).to have_alert "Magic link resent to" end context "when the token is expired" do it "shows the magic link page with the right message" do setup_subscription_token travel_to(2.day.from_now) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_current_path(magic_link_subscription_path(@subscription.external_id, invalid: true)) expect(page).to have_text "Your magic link has expired" expect(page).to have_text "Send magic link" end end end context "when there's more than one different emails linked to the subscription" do before do @subscription.original_purchase.update!(email: "purchase@email.com") end it "asks to use a magic link to access the manage page" do visit "/subscriptions/#{@subscription.external_id}/manage" expect(page).to have_current_path(magic_link_subscription_path(@subscription.external_id)) expect(page).to have_text "You're currently not signed in" expect(page).to have_text "choose one of the emails associated with your account to receive a magic link" expect(page).to have_text "Choose an email" expect(page).to_not have_text @subscription.email expect(page).to_not have_text @subscription.original_purchase.email expect(page).to have_text EmailRedactorService.redact(@subscription.email) expect(page).to have_text EmailRedactorService.redact(@subscription.original_purchase.email) expect(page).to have_text "Send magic link" end it "doesn't show the same email twice" do visit "/subscriptions/#{@subscription.external_id}/manage" expect(page).to have_current_path(magic_link_subscription_path(@subscription.external_id)) expect(page).to have_text "You're currently not signed in" expect(page).to have_text "choose one of the emails associated with your account to receive a magic link" expect(page).to have_text "Choose an email" expect(page).to have_text(EmailRedactorService.redact(@subscription.email), count: 1) expect(page).to have_text(EmailRedactorService.redact(@subscription.original_purchase.email), count: 1) expect(page).to have_text "Send magic link" end context "when the user picks the subscription email" do it "sends the magic link to the subscription email" do visit "/subscriptions/#{@subscription.external_id}/manage" redacted_subscription_email = EmailRedactorService.redact(@subscription.email) expect(page).to have_text redacted_subscription_email expect(page).to have_text EmailRedactorService.redact(@subscription.original_purchase.email) expect(page).to have_text "Send magic link" mail_double = double allow(mail_double).to receive(:deliver_later) expect(CustomerMailer).to receive(:subscription_magic_link).with(@subscription.id, @subscription.email).and_return(mail_double) choose redacted_subscription_email click_on "Send magic link" end end context "when the user picks the purchase email" do it "sends the magic link to the purchase email" do visit "/subscriptions/#{@subscription.external_id}/manage" redacted_purchase_email = EmailRedactorService.redact(@subscription.original_purchase.email) expect(page).to have_text EmailRedactorService.redact(@subscription.email) expect(page).to have_text redacted_purchase_email expect(page).to have_text "Send magic link" mail_double = double allow(mail_double).to receive(:deliver_later) expect(CustomerMailer).to receive(:subscription_magic_link).with(@subscription.id, @subscription.original_purchase.email).and_return(mail_double) choose "#{redacted_purchase_email}" click_on "Send magic link" end end context "when the token is invalid" do it "shows the magic link page with the right message" do visit "/subscriptions/#{@subscription.external_id}/manage?token=invalid" expect(page).to have_current_path(magic_link_subscription_path(@subscription.external_id, invalid: true)) expect(page).to have_text "Your magic link has expired" expect(page).to have_text "choose one of the emails associated with your account to receive a magic link" expect(page).to have_text "Choose an email" expect(page).to_not have_text @subscription.email expect(page).to_not have_text @subscription.original_purchase.email expect(page).to have_text EmailRedactorService.redact(@subscription.email) expect(page).to have_text EmailRedactorService.redact(@subscription.original_purchase.email) expect(page).to have_text "Send magic link" 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/subscription/tiered_membership_price_changes_spec.rb
spec/requests/subscription/tiered_membership_price_changes_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Tiered Membership Price Changes Spec", type: :system, js: true do include ManageSubscriptionHelpers include ProductWantThisHelpers include CurrencyHelper before :each do setup_subscription allow_any_instance_of(Purchase).to receive(:mandate_options_for_stripe).and_return({ payment_method_options: { card: { mandate_options: { reference: StripeChargeProcessor::MANDATE_PREFIX + SecureRandom.hex, amount_type: "maximum", amount: 100_00, start_date: Time.current.to_i, interval: "sporadic", supported_types: ["india"] } } } }) travel_to(@originally_subscribed_at + 1.month) setup_subscription_token end context "changing tier" do context "to a more expensive tier" do it "upgrades the user" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$6.55" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 6_55 expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] end it "creates a new mandate on Stripe if payment method requires a mandate" do indian_cc = create(:credit_card, user: @user, chargeable: create(:chargeable, card: StripePaymentMethodHelper.success_indian_card_mandate)) @subscription.credit_card = indian_cc @subscription.save! visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$6.55" click_on "Update membership" wait_for_ajax within_sca_frame do find_and_click("button:enabled", text: /COMPLETE/) end expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.successful.last.displayed_price_cents).to eq 6_55 expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] expect(@subscription.reload.credit_card).to eq indian_cc expect(@subscription.credit_card.stripe_payment_intent_id).to be_present payment_intent = Stripe::PaymentIntent.retrieve(@subscription.credit_card.stripe_payment_intent_id) mandate_id = Stripe::Charge.retrieve(payment_intent.latest_charge).payment_method_details.card.mandate expect(Stripe::Mandate.retrieve(mandate_id)).to be_present end it "preserves existing tier and price if SCA fails for card requiring mandate" do indian_cc = create(:credit_card, user: @user, chargeable: create(:chargeable, card: StripePaymentMethodHelper.success_indian_card_mandate)) @subscription.credit_card = indian_cc @subscription.save! visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$6.55" click_on "Update membership" wait_for_ajax within_sca_frame do find_and_click("button:enabled", text: /FAIL/) end wait_for_ajax expect(page).not_to have_alert(text: "Your membership has been updated.") expect(@subscription.original_purchase.variant_attributes).to eq [@original_tier] expect(@subscription.reload.credit_card).to eq indian_cc expect(@subscription.credit_card.stripe_payment_intent_id).to be_present end end context "to a less expensive tier" do it "does not immediately upgrade the user" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Tier 3" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") expect(@subscription.reload.purchases.count).to eq 1 expect(@subscription.subscription_plan_changes.count).to eq 1 expect(@subscription.original_purchase.variant_attributes).to eq [@original_tier] end end context "to a different tier with the same price" do it "upgrades and charges the user" do @new_tier_quarterly_price.update!(price_cents: @original_tier_quarterly_price.price_cents) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$2.04" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 2_04 expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] end end context "to the current tier" do it "makes no changes and does not charge the user" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Tier 3" choose "First Tier" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.count).to eq 1 end end context "to a PWYW tier" do before :each do @new_tier.update!(customizable_price: true) end context "paying more than the current subscription" do it "does not let the user enter a price that is too low" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" fill_in "Name a fair price", placeholder: "10.50+", with: "10" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Please enter an amount greater than or equal to the minimum.") end it "allows the user to enter a valid price" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" fill_in "Name a fair price", with: "11" # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$7.05" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 7_05 expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] expect(@subscription.original_purchase.displayed_price_cents).to eq 11_00 end end context "paying less than the current subscription" do it "does not charge the user or upgrade them immediately" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" select("Monthly", from: "Recurrence") # shows prorated price if PWYW price is greater than current price pwyw_input = find_field "Name a fair price" pwyw_input.fill_in with: "11" expect(page).to have_text "You'll be charged US$7.05" # does not show price tag if PWYW price is less than current price pwyw_input.fill_in with: "5" expect(page).not_to have_text "You'll be charged" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") expect(@subscription.reload.purchases.count).to eq 1 expect(@subscription.subscription_plan_changes.count).to eq 1 expect(@subscription.recurrence).to eq "quarterly" expect(@subscription.original_purchase.displayed_price_cents).to eq 5_99 end end end end context "changing payment option" do context "to a more expensive payment option" do it "upgrades the user" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" select("Every 2 years", from: "Recurrence") # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$14.05" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 14_05 expect(@subscription.recurrence).to eq "every_two_years" expect(@subscription.original_purchase.displayed_price_cents).to eq 18_00 end end context "to a less expensive payment option" do it "does not immediately upgrade the user" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" select("Monthly", from: "Recurrence") click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") expect(@subscription.reload.purchases.count).to eq 1 expect(@subscription.subscription_plan_changes.count).to eq 1 expect(@subscription.recurrence).to eq "quarterly" expect(@subscription.original_purchase.displayed_price_cents).to eq 5_99 end end end context "membership price has increased" do before :each do @original_tier_quarterly_price.update!(price_cents: 6_99) end it "displays the preexisting subscription price and does not charge the user on save" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).not_to have_text "You'll be charged" expect(page).to have_radio_button("First Tier", checked: true, text: "$5.99") within find(:radio_button, text: "First Tier") do expect(page).to have_selector("[role='status']", text: "Your current plan is $5.99 every 3 months, based on previous pricing.") end click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.count).to eq 1 end context "upgrading" do it "calculates the prorated amount based on the preexisting subscription price" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" expect(page).to have_text "You'll be charged US$6.55" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 6_55 end end end context "membership price has decreased" do before :each do @original_tier_quarterly_price.update!(price_cents: 4_99) end it "displays the preexisting subscription price and does not record a plan change for the user on save" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).not_to have_text "You'll be charged" expect(page).to have_radio_button("First Tier", checked: true, text: "$5.99") within find(:radio_button, text: "First Tier") do expect(page).to have_selector("[role='status']", text: "Your current plan is $5.99 every 3 months, based on previous pricing.") end click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.count).to eq 1 expect(@subscription.subscription_plan_changes.count).to eq 0 end context "upgrading" do it "calculates the prorated amount based on the preexisting subscription price" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" expect(page).to have_text "You'll be charged US$6.55" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 6_55 end end end context "when current tier has been deleted" do before do @original_tier.mark_deleted! end it "can still select that tier" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_radio_button("First Tier", checked: true) choose "Second Tier" choose "First Tier" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.count).to eq 1 end it "cannot select different recurrences for that tier" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_radio_button("First Tier", checked: true) select("Yearly", from: "Recurrence") expect(page).to have_radio_button("First Tier", checked: true, disabled: true) end end context "when current payment option has been deleted" do before do @quarterly_product_price.mark_deleted! @original_tier_quarterly_price.mark_deleted! @new_tier_quarterly_price.mark_deleted! @lower_tier_quarterly_price.mark_deleted! end it "can still select that payment option" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_field("Recurrence", with: "quarterly") expect(page).to have_radio_button("First Tier", checked: true, text: "$5.99") select("Yearly", from: "Recurrence") select("Quarterly", from: "Recurrence") click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.count).to eq 1 end it "cannot select deleted payment options for other tiers" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_radio_button(@new_tier.name, disabled: true) expect(page).to have_radio_button(@lower_tier.name, disabled: true) expect(page).to_not have_radio_button(@new_tier.name, disabled: false) expect(page).to_not have_radio_button(@lower_tier.name, disabled: false) select("Yearly", from: "Recurrence") expect(page).to_not have_radio_button(@new_tier.name, disabled: true) expect(page).to_not have_radio_button(@lower_tier.name, disabled: true) expect(page).to have_radio_button(@new_tier.name, disabled: false) expect(page).to have_radio_button(@lower_tier.name, disabled: false) end end context "changing seat count and/or billing frequency" do before do setup_subscription(quantity: 2) setup_subscription_token end context "when increasing the seat count" do it "does not display a warning notice regarding the seat change" do visit manage_subscription_path(@subscription.external_id, token: @subscription.token) fill_in "Seats", with: 3 expect(page).to_not have_selector("[role='status']", text: "Changing the number of seats will update your subscription to the current price of") end end context "when increasing the billing frequency" do it "does not display a warning notice regarding the billing frequency" do visit manage_subscription_path(@subscription.external_id, token: @subscription.token) select("Monthly", from: "Recurrence") expect(page).to_not have_selector("[role='status']", text: "Changing the billing frequency will update your subscription to the current price of") end end context "when decreasing the seat count and decreasing the billing frequency" do it "does not display a warning notice regarding the seat and billing frequency change" do visit manage_subscription_path(@subscription.external_id, token: @subscription.token) select("Yearly", from: "Recurrence") fill_in "Seats", with: 1 expect(page).to_not have_selector("[role='status']", text: "Changing the number of seats and adjusting the billing frequency will update your subscription to the current price of") end end context "when the price of the user's current tier has changed" do before do @subscription.original_purchase.variant_attributes.first.prices.find_by!(recurrence: "monthly").update!(price_cents: 3000) @subscription.original_purchase.variant_attributes.first.prices.find_by!(recurrence: "quarterly").update!(price_cents: 4000) @subscription.original_purchase.variant_attributes.first.prices.find_by!(recurrence: "yearly").update!(price_cents: 5000) end context "when decreasing the seat count" do it "displays a warning notice regarding the seat change" do visit manage_subscription_path(@subscription.external_id, token: @subscription.token) fill_in "Seats", with: 1 expect(page).to have_selector("[role='status']", text: "Changing the number of seats will update your subscription to the current price of $40 every 3 months per seat.") end end context "when decreasing the billing frequency" do it "displays a warning notice regarding the billing frequency" do visit manage_subscription_path(@subscription.external_id, token: @subscription.token) select("Yearly", from: "Recurrence") expect(page).to have_selector("[role='status']", text: "Changing the billing frequency will update your subscription to the current price of $50 a year per seat.") end end context "when increasing the seat count and increasing the billing frequency" do it "displays a warning notice regarding the seat and billing frequency change" do visit manage_subscription_path(@subscription.external_id, token: @subscription.token) select("Monthly", from: "Recurrence") fill_in "Seats", with: 3 expect(page).to have_selector("[role='status']", text: "Changing the number of seats and adjusting the billing frequency will update your subscription to the current price of $30 a month per seat.") end end end end context "when the subscription is overdue for charge" do before do @subscription.last_purchase.update(succeeded_at: 1.year.ago) @subscription.original_purchase.variant_attributes.first.prices.find_by!(recurrence: "quarterly").update!(price_cents: 5000) end it "charges the existing subscription price" do visit manage_subscription_path(@subscription.external_id, token: @subscription.token) within find(:radio_button, text: "First Tier") do expect(page).to_not have_selector("[role='status']", text: "Your current plan is $5.99 every 3 months, based on previous pricing.") expect(page).to have_text("$5.99 every 3 months") end click_on "Update membership" expect(page).to have_alert(text: "Your membership has been updated.") visit manage_subscription_path(@subscription.external_id, token: @subscription.token) within find(:radio_button, text: "First Tier") do expect(page).to have_selector("[role='status']", text: "Your current plan is $5.99 every 3 months, based on previous pricing.") expect(page).to have_text("$50 every 3 months") 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/subscription/tiered_membership_spec.rb
spec/requests/subscription/tiered_membership_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Tiered Membership Spec", type: :system, js: true do include ManageSubscriptionHelpers include ProductWantThisHelpers include CurrencyHelper before :each do setup_subscription travel_to(@originally_subscribed_at + 1.month) setup_subscription_token end it "displays the currently selected tier, payment option, and card on file" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_field("Recurrence", with: "quarterly") expect(page).to have_selector("[aria-label=\"Saved credit card\"]", text: ChargeableVisual.get_card_last4(@credit_card.visual)) # initially hides payment blurb, as user owes nothing for current selection expect(page).not_to have_text "You'll be charged" expect(page).to have_radio_button("First Tier", checked: true, text: "$5.99") end it "displays the correct prices when toggling between options" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" wait_for_ajax expect(page).to have_text "You'll be charged US$6.55" choose "Tier 3" wait_for_ajax expect(page).not_to have_text "You'll be charged" choose "First Tier" wait_for_ajax expect(page).not_to have_text "You'll be charged" select("Yearly", from: "Recurrence") wait_for_ajax expect(page).to have_text "You'll be charged US$6.05" select("Monthly", from: "Recurrence") wait_for_ajax expect(page).not_to have_text "You'll be charged" end context "inactive membership" do before :each do travel_to(@originally_subscribed_at + 4.months) @subscription.update!(cancelled_at: 1.week.ago, deactivated_at: 1.week.ago, cancelled_by_buyer: true) setup_subscription_token end it "allows the user to restart their membership, and charges them" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Restart membership" wait_for_ajax expect(page).to have_alert(text: "Membership restarted") expect(@subscription.reload.purchases.successful.count).to eq 2 expect(@subscription.cancelled_at).to be_nil end it "allows the user to restart their membership when product has required custom fields" do @product.custom_fields.create!( name: "Favorite Color", required: true, field_type: "text", seller_id: @product.user.id ) @product.custom_fields.create!( name: "http://example.com/terms", required: true, field_type: "terms", seller_id: @product.user.id ) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Restart membership" wait_for_ajax expect(page).to have_alert(text: "Membership restarted") expect(@subscription.reload.purchases.successful.count).to eq 2 expect(@subscription.cancelled_at).to be_nil end context "when the price has changed" do it "charges the pre-existing price" do old_price_cents = @original_tier_quarterly_price.price_cents @original_tier_quarterly_price.update!(price_cents: old_price_cents + 500) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_text "You'll be charged US$5.99" click_on "Restart membership" wait_for_ajax expect(page).to have_alert(text: "Membership restarted") expect(@subscription.reload.purchases.successful.count).to eq 2 expect(@subscription.purchases.last.displayed_price_cents).to eq old_price_cents end end context "when the discount is expired" do let!(:offer_code) { create(:offer_code, products: [@product], amount_cents: 100, code: "limited", duration_in_billing_cycles: 1) } it "charges the full price" do @subscription.original_purchase.update!(offer_code:, displayed_price_cents: 499, price_cents: 499) @subscription.original_purchase.create_purchase_offer_code_discount!(offer_code:, duration_in_billing_cycles: 1, pre_discount_minimum_price_cents: 599, offer_code_amount: 100) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" within find(:radio_button, text: "First Tier") do expect(page).to have_text("$5.99 every 3 months") end expect(page).to have_text("You'll be charged US$5.99") click_on "Restart membership" wait_for_ajax expect(page).to have_alert(text: "Membership restarted") expect(@subscription.reload.purchases.successful.count).to eq 2 expect(@subscription.purchases.last.displayed_price_cents).to eq 599 end end end context "pending cancellation membership" do before do @subscription.update!(cancelled_at: @subscription.end_time_of_subscription, cancelled_by_buyer: true) end it "allows the user to restart their membership and does not charge them" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).not_to have_text "You'll be charged" expect do click_on "Restart membership" wait_for_ajax end.not_to change { Purchase.count } expect(page).to have_alert(text: "Membership restarted") expect(@subscription.reload.cancelled_at).to be_nil end end context "overdue for charge but not inactive" do before do travel_back end it "allows the user to update their card and charges the new card" do travel_to(@originally_subscribed_at + 4.months) setup_subscription_token visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_text "You'll be charged US$5.99" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.credit_card).not_to eq @credit_card expect(@subscription.credit_card).to be_present expect(@subscription.purchases.successful.count).to eq 2 end it "correctly displays costs for different plans" do travel_to(@originally_subscribed_at + 4.months) setup_subscription_token visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" wait_for_ajax expect(page).to have_text "You'll be charged US$10.50" choose "Tier 3" wait_for_ajax expect(page).to have_text "You'll be charged US$4" choose "First Tier" wait_for_ajax expect(page).to have_text "You'll be charged US$5.99" select("Yearly", from: "Recurrence") wait_for_ajax expect(page).to have_text "You'll be charged US$10" select("Monthly", from: "Recurrence") wait_for_ajax expect(page).to have_text "You'll be charged US$3" end context "for a monthly subscription begun in February" do it "displays the correct charge and updates successfully despite the 28 day billing period" do setup_subscription(originally_subscribed_at: Time.utc(2021, 02, 01), recurrence: "monthly") travel_to(Time.utc(2021, 03, 01)) setup_subscription_token visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_text "You'll be charged US$3" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.credit_card).not_to eq @credit_card expect(@subscription.credit_card).to be_present expect(@subscription.purchases.successful.count).to eq 2 end end end context "test purchase" do it "creates a new test purchase when upgrading" do @product.update!(user: @user) @original_purchase.update!(seller: @user, purchase_state: "test_successful") @subscription.update!(is_test_subscription: true) login_as @user visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" expect(page).to have_text "You'll be charged US$6.55" click_on "Update membership" expect(page).to have_selector("h1", text: "Library") upgrade_purchase = @subscription.reload.purchases.last expect(upgrade_purchase.purchase_state).to eq "test_successful" expect(upgrade_purchase.displayed_price_cents).to eq 6_55 expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] end end context "upgrade charge is less than product price minimum" do before do travel_back end it "rounds up to the minimum" do @new_tier_quarterly_price.update!(price_cents: 6_25) travel_to(@originally_subscribed_at + 1.hour) do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" expect(page).to have_text "You'll be charged US$0.99" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 99 expect(@subscription.original_purchase.displayed_price_cents).to eq 6_25 end end context "when updating a PWYW price" do it "rounds up to the minimum" do setup_subscription(pwyw: true) setup_subscription_token expect(@original_purchase.displayed_price_cents).to eq 6_99 travel_to(@originally_subscribed_at + 1.hour) do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" pwyw_input = find_field "Name a fair price" pwyw_input.fill_in with: "" pwyw_input.fill_in with: "7.50" wait_for_ajax expect(page).to have_text "You'll be charged US$0.99" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 99 expect(@subscription.original_purchase.displayed_price_cents).to eq 7_50 end end end context "when changing to a PWYW tier" do it "rounds up to the minimum" do @new_tier.update!(customizable_price: true) @new_tier_quarterly_price.update!(price_cents: 6_09) # $0.10 more than existing plan travel_to(@originally_subscribed_at + 1.hour) do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" pwyw_input = find_field("Name a fair price") pwyw_input.fill_in with: "6.50" wait_for_ajax expect(page).to have_text "You'll be charged US$0.99" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 99 expect(@subscription.original_purchase.displayed_price_cents).to eq 6_50 end end end context "for non-USD currency" do it "rounds up to the minimum product price for that currency" do currency = "cad" change_membership_product_currency_to(@product, currency) set_tier_price_difference_below_min_upgrade_price(currency) displayed_upgrade_charge_in_usd = formatted_price("usd", get_usd_cents(currency, @min_price_in_currency)) travel_to(@originally_subscribed_at + 1.hour) do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" expect(page).to have_text "You'll be charged US#{displayed_upgrade_charge_in_usd}" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq @min_price_in_currency expect(@subscription.original_purchase.displayed_price_cents).to eq @new_price end end end end context "when product has custom fields" do before :each do @product.custom_fields.create!( name: "Favorite Color", required: false, field_type: "text", seller_id: @product.user.id ) @product.custom_fields.create!( name: "Subscribe to Newsletter", required: false, field_type: "checkbox", seller_id: @product.user.id ) end it "hides custom fields on manage membership page and preserves original custom field values when updating membership" do color_field = @product.custom_fields.find_by(name: "Favorite Color") newsletter_field = @product.custom_fields.find_by(name: "Subscribe to Newsletter") @subscription.original_purchase.purchase_custom_fields.create!( custom_field: color_field, name: color_field.name, field_type: color_field.field_type, value: "Blue" ) @subscription.original_purchase.purchase_custom_fields.create!( custom_field: newsletter_field, name: newsletter_field.name, field_type: newsletter_field.field_type, value: "true" ) visit manage_subscription_path(@subscription.external_id, token: @subscription.token) expect(page).not_to have_text "Favorite Color" expect(page).not_to have_text "Subscribe to Newsletter" expect(page).to have_field("Recurrence", with: "quarterly") expect(page).to have_button("Update membership") choose "Second Tier" wait_for_ajax click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") @subscription.reload expect(@subscription.original_purchase.purchase_custom_fields.find_by(custom_field: color_field).value).to eq("Blue") expect(@subscription.original_purchase.purchase_custom_fields.find_by(custom_field: newsletter_field).value).to eq(true) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/subscription/missing_tiered_membership_spec.rb
spec/requests/subscription/missing_tiered_membership_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Missing Tiered Membership Spec", type: :system, js: true do include ManageSubscriptionHelpers include ProductWantThisHelpers include CurrencyHelper before :each do setup_subscription travel_to(@originally_subscribed_at + 1.month) setup_subscription_token @original_purchase.update!(variant_attributes: []) end it "allows the user to update their subscription" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_field("Recurrence", with: "quarterly") expect(page).to have_selector("[aria-label=\"Saved credit card\"]", text: ChargeableVisual.get_card_last4(@credit_card.visual)) # initially hides payment blurb, as user owes nothing for current selection expect(page).not_to have_text "You'll be charged" expect(page).to have_radio_button("First Tier", checked: true, text: "$5.99") fill_in "Email", with: "edgarg@gumroad.com" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@original_purchase.reload.email).to eq "edgarg@gumroad.com" end it "allows the user to upgrade their plan" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$6.55" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 6_55 expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] end it "allows the user to downgrade their plan" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Tier 3" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") expect(@subscription.reload.purchases.count).to eq 1 expect(@subscription.subscription_plan_changes.count).to eq 1 expect(@subscription.original_purchase.variant_attributes).to eq [@original_tier] end context "and membership price has changed" do before :each do @original_tier_quarterly_price.update!(price_cents: 6_99) end it "displays the preexisting subscription price and does not charge the user on save" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).not_to have_text "You'll be charged" expect(page).to have_radio_button("First Tier", checked: true, text: "$5.99") click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.count).to eq 1 end context "upgrading" do it "calculates the prorated amount based on the preexisting subscription price" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" expect(page).to have_text "You'll be charged US$6.55" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 6_55 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/subscription/tiered_membership_free_trial_spec.rb
spec/requests/subscription/tiered_membership_free_trial_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Tiered Membership Free Trial Spec", type: :system, js: true do include ManageSubscriptionHelpers include ProductWantThisHelpers let(:is_pwyw) { false } before :each do setup_subscription(free_trial: true, pwyw: is_pwyw) setup_subscription_token end context "during the free trial" do before do travel_to @subscription.free_trial_ends_at - 1.day setup_subscription_token end it "does not display payment blurb" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).not_to have_text "You'll be charged" end it "does not display prices when toggling between options" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" wait_for_ajax expect(page).not_to have_text "You'll be charged" choose "Tier 3" wait_for_ajax expect(page).not_to have_text "You'll be charged" choose "First Tier" wait_for_ajax expect(page).not_to have_text "You'll be charged" select("Yearly", from: "Recurrence") wait_for_ajax expect(page).not_to have_text "You'll be charged" select("Monthly", from: "Recurrence") wait_for_ajax expect(page).not_to have_text "You'll be charged" end context "upgrading" do it "upgrades the user immediatedly and does not charge them" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" wait_for_ajax expect(page).not_to have_text "You'll be charged" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.is_free_trial_purchase).to eq true expect(updated_purchase.purchase_state).to eq "not_charged" expect(updated_purchase.variant_attributes).to eq [@new_tier] expect(updated_purchase.displayed_price_cents).to eq 10_50 end context "when the initial purchase was free" do let(:is_pwyw) { true } before do @original_tier_quarterly_price.update!(price_cents: 0) @original_purchase.update!(displayed_price_cents: 0) @credit_card.destroy! end it "requires a credit card" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).not_to have_text "Pay with" choose "Second Tier" expect(page).to have_text "Pay with" expect(page).not_to have_text "You'll be charged" # no charge today fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) expect do click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") end.to change { @subscription.reload.purchases.count }.from(1).to(2) .and change { @subscription.original_purchase.id } expect(@subscription.original_purchase.displayed_price_cents).to eq 10_50 expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] end end end context "downgrading" do it "downgrades the user immediately and does not charge them" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Tier 3" wait_for_ajax expect(page).not_to have_text "You'll be charged" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.is_free_trial_purchase).to eq true expect(updated_purchase.purchase_state).to eq "not_charged" expect(updated_purchase.variant_attributes).to eq [@lower_tier] expect(updated_purchase.displayed_price_cents).to eq 4_00 end end context "updating credit card" do it "succeeds" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.credit_card).not_to eq @credit_card expect(@subscription.credit_card).to be # Make sure recurring charges with the new card succeed expect do @subscription.charge! end.to change { @subscription.purchases.successful.count }.by(1) end it "succeeds with an SCA-enabled card" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success_with_sca)) click_on "Update membership" wait_for_ajax sleep 1 within_sca_frame do find_and_click("button:enabled", text: /COMPLETE/) end expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.credit_card).not_to eq @credit_card expect(@subscription.credit_card).to be # Make sure recurring charges with the new card succeed expect do @subscription.charge! end.to change { @subscription.purchases.successful.count }.by(1) end end context "updating PWYW price" do let(:is_pwyw) { true } it "succeeds and does not charge the user when increasing price" do expect do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" pwyw_input = find_field "Name a fair price" pwyw_input.fill_in with: "" pwyw_input.fill_in with: "9.99" wait_for_ajax expect(page).not_to have_text "You'll be charged" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.original_purchase.displayed_price_cents).to eq 9_99 end.not_to change { @subscription.purchases.successful.count } end it "succeeds and does not charge the user when decreasing price" do expect do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" pwyw_input = find_field "Name a fair price" pwyw_input.fill_in with: "" pwyw_input.fill_in with: "6.00" wait_for_ajax expect(page).not_to have_text "You'll be charged" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.original_purchase.displayed_price_cents).to eq 6_00 end.not_to change { @subscription.purchases.successful.count } end end context "when overdue for charge" do it "charges the user" do travel_back travel_to(@subscription.free_trial_ends_at + 1.day) do setup_subscription_token expect do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") end.to change { @subscription.purchases.successful.count }.by(1) end end end end context "after the free trial" do before do travel_to(@subscription.free_trial_ends_at + 1.day) do # assume the subscription was charged properly at the end of the free trial @subscription.charge! end travel_to(@originally_subscribed_at + 1.month) setup_subscription_token end context "upgrading" do it "upgrades the user immediately and charges them" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" expect(page).to have_content "You'll be charged US$6.02 today." click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.is_free_trial_purchase).to eq true expect(updated_purchase.purchase_state).to eq "not_charged" expect(updated_purchase.variant_attributes).to eq [@new_tier] expect(updated_purchase.displayed_price_cents).to eq 10_50 upgrade_charge = @subscription.purchases.successful.last expect(upgrade_charge.displayed_price_cents).to eq 6_02 end end context "downgrading" do it "does not downgrade the user immediately" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Tier 3" wait_for_ajax expect(page).not_to have_text "You'll be charged" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") expect(@subscription.reload.purchases.count).to eq 2 expect(@subscription.subscription_plan_changes.count).to eq 1 expect(@subscription.original_purchase.variant_attributes).to eq [@original_tier] end end context "when the product no longer has free trial enabled" do before do @product.update!(free_trial_enabled: false, free_trial_duration_unit: nil, free_trial_duration_amount: nil) end it "allows the subscriber to modify the subscription" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" expect(page).to have_content "You'll be charged US$6.02 today." click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.id).not_to eq @original_purchase.id expect(updated_purchase.is_free_trial_purchase).to eq true expect(updated_purchase.purchase_state).to eq "not_charged" 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/subscription/tiered_membership_pwyw_spec.rb
spec/requests/subscription/tiered_membership_pwyw_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Tiered Membership Spec for a PWYW tier", type: :system, js: true do include ManageSubscriptionHelpers include ProductWantThisHelpers include CurrencyHelper before :each do setup_subscription travel_to(@originally_subscribed_at + 1.month) setup_subscription_token end it "displays the price the user is currently paying" do @original_tier.update!(customizable_price: true) @original_purchase.update!(displayed_price_cents: 7_50) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_field("Name a fair price", with: "7.50") # shows the correct price in the label expect(page).to have_radio_button("First Tier", checked: true, text: "$5.99+") end it "displays the correct prices when toggling between options" do # PWYW tier already selected @original_tier.update!(customizable_price: true) # PWYW tier @new_tier.update!(customizable_price: true) @new_tier.prices.find_by(recurrence: BasePrice::Recurrence::QUARTERLY).update!(price_cents: 5_00, suggested_price_cents: 6_50) # with suggested price set @new_tier.prices.find_by(recurrence: BasePrice::Recurrence::MONTHLY).update!(price_cents: 1_50, suggested_price_cents: nil) # without suggested price set visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" expect(page).to have_field("Name a fair price", with: nil) # just shows placeholder fill_in "Name a fair price", with: "11.50" wait_for_ajax expect(page).to have_text "You'll be charged US$7.55" # prorated_discount_price_cents select("Monthly", from: "Recurrence") expect(page).to have_field("Name a fair price", with: nil) # clears the entered price select("Quarterly", from: "Recurrence") choose "Tier 3" wait_for_ajax expect(page).not_to have_text "You'll be charged" choose "First Tier" wait_for_ajax expect(page).to have_field("Name a fair price", with: "5.99") # shows existing price you're paying expect(page).not_to have_text "You'll be charged" end it "displays the correct price owed when changing PWYW price" do @original_tier.update!(customizable_price: true) @original_purchase.update!(displayed_price_cents: 7_50) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" pwyw_input = find_field("Name a fair price") pwyw_input.fill_in with: "" # Sometimes the next value isn't filled in correctly without this pwyw_input.fill_in with: "10" wait_for_ajax expect(page).to have_text "You'll be charged US$5.05" pwyw_input.fill_in with: "" pwyw_input.fill_in with: "5" wait_for_ajax expect(page).not_to have_text "You'll be charged" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/subscription/tiered_membership_offer_codes_spec.rb
spec/requests/subscription/tiered_membership_offer_codes_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Tiered Membership Offer code Spec", type: :system, js: true do include ManageSubscriptionHelpers context "when the subscription has an offer code applied" do let(:offer_code) { create(:universal_offer_code, amount_cents: 200) } before do setup_subscription(offer_code:, is_multiseat_license: true) travel_to(@originally_subscribed_at + 1.month) setup_subscription_token end it "applies the same offer code when upgrading" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$5.87" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 5_87 expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] expect(@subscription.original_purchase.offer_code_id).to eq offer_code.id end it "applies the same offer code when downgrading" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose @lower_tier.name expect(page).not_to have_text "You'll be charged" expect do click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") end.to change { SubscriptionPlanChange.count }.from(0).to(1) plan_change = @subscription.subscription_plan_changes.first expect(plan_change.perceived_price_cents).to eq 2_00 # ensure offer code is applied appropriately travel_back travel_to @subscription.end_time_of_subscription + 1.hour do expect do RecurringChargeWorker.new.perform(@subscription.id) end.to change { @subscription.reload.original_purchase.id } expect(@subscription.offer_code).to eq offer_code end end it "applies the code correctly when changing the number of seats" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" fill_in "Seats", with: 2 click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") @subscription.reload expect(@subscription.purchases.last.displayed_price_cents).to eq 5_35 expect(@subscription.original_purchase.displayed_price_cents).to eq 7_98 expect(@subscription.original_purchase.quantity).to eq 2 expect(@subscription.original_purchase.offer_code_id).to eq offer_code.id visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" fill_in "Seats", with: 1 click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") plan_change = @subscription.subscription_plan_changes.first expect(plan_change.perceived_price_cents).to eq 3_99 expect(plan_change.quantity).to eq 1 expect(@subscription.original_purchase.offer_code_id).to eq offer_code.id end context "for a PWYW product" do before do [@original_tier, @new_tier, @lower_tier].each do |tier| tier.update!(customizable_price: true) end @original_purchase.update!(displayed_price_cents: 7_50) end it "applies the code correctly when increasing the PWYW amount" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).to have_field("Name a fair price", with: "7.50") fill_in "Name a fair price", with: "9.50" wait_for_ajax expect(page).to have_text "You'll be charged US$4.55" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 4_55 expect(@subscription.original_purchase.displayed_price_cents).to eq 9_50 expect(@subscription.original_purchase.offer_code_id).to eq offer_code.id end it "applies the code correctly when decreasing the PWYW amount" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" fill_in "Name a fair price", with: "5.50" wait_for_ajax expect(page).not_to have_text "You'll be charged" expect do click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") end.to change { SubscriptionPlanChange.count }.from(0).to(1) plan_change = @subscription.subscription_plan_changes.first expect(plan_change.perceived_price_cents).to eq 5_50 end it "applies the offer code correctly when upgrading tiers" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" fill_in "Name a fair price", with: "11.50" wait_for_ajax expect(page).to have_text "You'll be charged US$6.55" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 6_55 expect(@subscription.original_purchase.displayed_price_cents).to eq 11_50 expect(@subscription.original_purchase.offer_code_id).to eq offer_code.id expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] end it "applies the offer code correctly when downgrading tiers" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose @lower_tier.name fill_in "Name a fair price", with: "2.50" wait_for_ajax expect(page).not_to have_text "You'll be charged" expect do click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") end.to change { SubscriptionPlanChange.count }.from(0).to(1) plan_change = @subscription.subscription_plan_changes.first expect(plan_change.perceived_price_cents).to eq 2_50 # ensure offer code is applied appropriately travel_back travel_to @subscription.end_time_of_subscription + 1.hour do expect do RecurringChargeWorker.new.perform(@subscription.id) end.to change { @subscription.reload.original_purchase.id } expect(@subscription.offer_code).to eq offer_code end end it "applies the code correctly when changing the number of seats" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" fill_in "Seats", with: 2 click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") @subscription.reload expect(@subscription.purchases.last.displayed_price_cents).to eq 10_05 expect(@subscription.original_purchase.displayed_price_cents).to eq 15_00 expect(@subscription.original_purchase.quantity).to eq 2 expect(@subscription.original_purchase.offer_code_id).to eq offer_code.id visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" fill_in "Seats", with: 1 click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") plan_change = @subscription.subscription_plan_changes.first expect(plan_change.perceived_price_cents).to eq 7_50 expect(plan_change.quantity).to eq 1 expect(@subscription.original_purchase.offer_code_id).to eq offer_code.id end end context "and the price has changed since the subscription was purchased" do it "correctly applies the offer code when restarting an expired membership" do @original_tier_quarterly_price.update!(price_cents: @original_tier_quarterly_price.price_cents + 500) ended_at = @subscription.end_time_of_subscription @subscription.update!( cancelled_at: ended_at, deactivated_at: ended_at, cancelled_by_buyer: true, token_expires_at: ended_at + 2.days ) travel_back travel_to(ended_at + 1.day) visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" # shows the correct price on the current plan expect(page).to have_radio_button("First Tier", checked: true, text: "$5.99 $3.99", normalize_ws: true) # shows the price to be charged today expect(page).to have_text "You'll be charged US$3.99" click_on "Restart membership" wait_for_ajax expect(page).to have_alert(text: "Membership restarted") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 3_99 end end context "but the offer code is now deleted" do before do offer_code.mark_deleted! end it "does not apply the offer code when upgrading tiers" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # shows the prorated price without discount to be charged today expect(page).to have_text "You'll be charged US$7.87" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 7_87 expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] expect(@subscription.original_purchase.offer_code_id).to eq offer_code.id expect(@subscription.original_purchase.displayed_price_cents).to eq 10_50 end it "does not apply the offer code when downgrading tiers" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" select("Monthly", from: "Recurrence") choose @lower_tier.name expect(page).not_to have_text "You'll be charged" expect do click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership will be updated at the end of your current billing cycle.") end.to change { SubscriptionPlanChange.count }.from(0).to(1) plan_change = @subscription.subscription_plan_changes.first expect(plan_change.perceived_price_cents).to eq 2_50 end it "does not error when not changing plans" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" click_on "Use a different card?" fill_in_credit_card(number: CardParamsSpecHelper.card_number(:success)) click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") end end context "and the offer code has changed since the subscription was purchased" do before do offer_code.update!(amount_cents: nil, amount_percentage: 10) end context "and the subscription has cached offer code details" do it "uses the old offer code attributes when updating" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$5.87" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 5_87 expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] expect(@subscription.original_purchase.offer_code_id).to eq offer_code.id new_discount = @subscription.original_purchase.purchase_offer_code_discount expect(new_discount).to be expect(new_discount.offer_code).to eq offer_code expect(new_discount.offer_code_amount).to eq 200 expect(new_discount.offer_code_is_percent).to eq false expect(new_discount.pre_discount_minimum_price_cents).to eq @new_tier_quarterly_price.price_cents end end context "but the subscription does not have cached offer code details" do it "uses the new offer code attributes when updating" do @original_purchase.purchase_offer_code_discount.destroy! visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # shows the prorated price to be charged today expect(page).to have_text "You'll be charged US$6.82" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") expect(@subscription.reload.purchases.last.displayed_price_cents).to eq 6_82 expect(@subscription.original_purchase.variant_attributes).to eq [@new_tier] expect(@subscription.original_purchase.offer_code_id).to eq offer_code.id expect(@subscription.original_purchase.displayed_price_cents).to eq 9_45 # 10% off $10.50 new_discount = @subscription.original_purchase.purchase_offer_code_discount expect(new_discount).to be expect(new_discount.offer_code).to eq offer_code expect(new_discount.offer_code_amount).to eq 10 expect(new_discount.offer_code_is_percent).to eq true expect(new_discount.pre_discount_minimum_price_cents).to eq @new_tier_quarterly_price.price_cents end end end describe "100% off offer codes" do let(:offer_code) { create(:offer_code, amount_cents: nil, amount_percentage: 100) } before do @subscription.credit_card.destroy! end it "allows updating the membership without entering credit card details" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" expect(page).not_to have_content "Card Number" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") end context "when the subscription has cached offer code details" do it "displays the price based on the cached pre-discount price and allows upgrading" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" # shows the correct plan prices expect(page).to have_radio_button("First Tier", checked: true, text: /\$5\.99\s+\$0/) expect(page).to have_radio_button("Second Tier", text: /\$10\.50\s+\$0/) expect(page).to have_radio_button("Tier 3", text: /\$4\s+\$0/) choose "Second Tier" expect(page).not_to have_text "You'll be charged" # does not show payment blurb since cost is $0 with offer code click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") new_original_purchase = @subscription.reload.original_purchase expect(new_original_purchase.variant_attributes).to eq [@new_tier] expect(new_original_purchase.offer_code_id).to eq offer_code.id new_discount = @subscription.original_purchase.purchase_offer_code_discount expect(new_discount).to be expect(new_discount.offer_code).to eq offer_code expect(new_discount.offer_code_amount).to eq 100 expect(new_discount.offer_code_is_percent).to eq true expect(new_discount.pre_discount_minimum_price_cents).to eq @new_tier_quarterly_price.price_cents end end context "when the subscription does not have cached offer code details" do it "displays the price based on the current subscription price and allows upgrading" do @original_purchase.purchase_offer_code_discount.destroy! visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" # shows the correct plan prices expect(page).to have_radio_button("First Tier", checked: true, text: "$0") expect(page).to have_radio_button("Second Tier", text: /\$10\.50\s+\$0/) expect(page).to have_radio_button("Tier 3", text: /\$4\s+\$0/) choose "Second Tier" expect(page).not_to have_text "You'll be charged" # does not show payment blurb since cost is $0 with offer code click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") new_original_purchase = @subscription.reload.original_purchase expect(new_original_purchase.variant_attributes).to eq [@new_tier] expect(new_original_purchase.offer_code_id).to eq offer_code.id new_discount = @subscription.original_purchase.purchase_offer_code_discount expect(new_discount).to be expect(new_discount.offer_code).to eq offer_code expect(new_discount.offer_code_amount).to eq 100 expect(new_discount.offer_code_is_percent).to eq true expect(new_discount.pre_discount_minimum_price_cents).to eq 10_50 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/subscription/tiered_membership_vat_spec.rb
spec/requests/subscription/tiered_membership_vat_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Tiered Membership VAT Spec", type: :system, js: true do include ManageSubscriptionHelpers include ProductWantThisHelpers before :each do setup_subscription travel_to(@originally_subscribed_at + 1.month) setup_subscription_token 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) create(:zip_tax_rate, country: "FR", zip_code: nil, state: nil, combined_rate: 0.20, is_seller_responsible: false) allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("2.47.255.255") # Italy end context "when original purchase was not charged VAT" do it "does not charge VAT even if has EU IP address" do visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # does not show VAT expect(page).to have_text "You'll be charged US$6.55" expect(page).not_to have_selector(".payment-blurb .js-tax-amount") click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") # updated original purchase has correct tax info updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.gumroad_tax_cents).to eq 0 expect(updated_purchase.total_transaction_cents).to eq 10_50 expect(updated_purchase.purchase_sales_tax_info.ip_country_code).to be_nil expect(updated_purchase.purchase_sales_tax_info.ip_address).not_to eq "2.47.255.255" # upgrade purchase has correct tax info last_purchase = @subscription.purchases.last expect(last_purchase.displayed_price_cents).to eq 6_55 expect(last_purchase.total_transaction_cents).to eq 6_55 expect(last_purchase.gumroad_tax_cents).to eq 0 expect(last_purchase.purchase_sales_tax_info.ip_country_code).to be_nil expect(last_purchase.purchase_sales_tax_info.ip_address).not_to eq "2.47.255.255" end end context "when the original purchase was charged VAT" do it "uses the original purchase's country and VAT" do travel_back setup_subscription_with_vat travel_to(@originally_subscribed_at + 1.month) setup_subscription_token visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" # shows the prorated price to be charged today, including VAT expect(page).to have_text "You'll be charged US$7.86 today, including US$1.31 for VAT in France" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") # updated original purchase has correct taxes - $10.50 * 0.20 = $2.10 updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.gumroad_tax_cents).to eq 2_10 expect(updated_purchase.total_transaction_cents).to eq 12_60 expect(updated_purchase.purchase_sales_tax_info.country_code).to eq "FR" expect(updated_purchase.purchase_sales_tax_info.ip_address).to eq "2.16.255.255" # upgrade purchase has correct taxes - $6.55 * 0.20 = $1.31 last_purchase = @subscription.purchases.last expect(last_purchase.displayed_price_cents).to eq 6_55 expect(last_purchase.total_transaction_cents).to eq 7_86 expect(last_purchase.gumroad_tax_cents).to eq 1_31 expect(last_purchase.purchase_sales_tax_info.country_code).to eq "FR" expect(last_purchase.purchase_sales_tax_info.ip_address).to eq "2.16.255.255" end end context "when the original purchase had a VAT ID set" do it "uses the same VAT ID for the new subscription" do allow_any_instance_of(VatValidationService).to receive(:process).and_return(true) travel_back setup_subscription_with_vat(vat_id: "FR123456789") travel_to(@originally_subscribed_at + 1.month) setup_subscription_token visit "/subscriptions/#{@subscription.external_id}/manage?token=#{@subscription.token}" choose "Second Tier" expect(page).to have_text "You'll be charged US$6.55" click_on "Update membership" wait_for_ajax expect(page).to have_alert(text: "Your membership has been updated.") # updated original purchase has correct taxes updated_purchase = @subscription.reload.original_purchase expect(updated_purchase.gumroad_tax_cents).to eq 0 expect(updated_purchase.total_transaction_cents).to eq 10_50 expect(updated_purchase.purchase_sales_tax_info.business_vat_id).to eq "FR123456789" # upgrade purchase has correct taxes - $6.55 * 0.20 = $1.31 last_purchase = @subscription.purchases.last expect(last_purchase.gumroad_tax_cents).to eq 0 expect(last_purchase.total_transaction_cents).to eq 6_55 expect(last_purchase.purchase_sales_tax_info.business_vat_id).to eq "FR123456789" end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/checkout/form_spec.rb
spec/requests/checkout/form_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" require "shared_examples/creator_dashboard_page" describe("Checkout form page", type: :system, js: true) do let(:seller) { create(:named_seller, recommendation_type: User::RecommendationType::OWN_PRODUCTS) } include_context "with switching account to user as admin for seller" it_behaves_like "creator dashboard page", "Checkout" do let(:path) { checkout_form_path } end describe "discounts" do it "allows updating the visibility of the offer code field" do visit checkout_form_path choose "Only if a discount is available" in_preview do expect(page).to have_field("Discount code") end click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.display_offer_code_field).to eq(true) visit checkout_form_path choose "Never" in_preview do expect(page).to_not have_field("Discount code") end click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.display_offer_code_field).to eq(false) end end describe "custom fields" do it "allows managing custom fields" do visit checkout_form_path click_on "Add custom field" select "Checkbox", from: "Type of field" click_on "Save changes" expect(find_field("Label")["aria-invalid"]).to eq "true" expect(page).to have_alert(text: "Please complete all required fields.") fill_in "Label", with: "You should totally check this - out!" in_preview do expect(page).to have_unchecked_field("You should totally check this - out!") end check "Required" click_on "Save changes" expect(find_field("Label")["aria-invalid"]).to eq "false" expect(find_field("Products")["aria-invalid"]).to eq "true" expect(page).to have_alert(text: "Please complete all required fields.") check "All products" click_on "Save changes" expect(find_field("Products")["aria-invalid"]).to eq "false" expect(page).to have_alert(text: "Changes saved!") expect(seller.custom_fields.count).to eq(1) field = seller.custom_fields.last expect(field.name).to eq "You should totally check this - out!" expect(field.type).to eq "checkbox" expect(field.required).to eq true expect(field.global).to eq true visit checkout_form_path select "Terms", from: "Type of field" expect(page).to have_field "Terms URL", with: "You should totally check this - out!" click_on "Save changes" expect(find_field("Terms URL")["aria-invalid"]).to eq "true" fill_in "Terms URL", with: "https://www.gumroad.com" in_preview do expect(page).to have_unchecked_field("I accept") end click_on "Save changes" expect(find_field("Terms URL")["aria-invalid"]).to eq "false" expect(page).to have_alert(text: "Changes saved!") expect(field.reload.type).to eq "terms" expect(field.name).to eq "https://www.gumroad.com" visit checkout_form_path within_section "Custom fields", section_element: :section do click_on "Remove" end in_preview do expect(page).to_not have_field("I accept") end click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(page).to_not have_field("Type of field") expect(seller.custom_fields.count).to eq(0) end context "when a product is archived" do let(:product1) { create(:product, name: "Product 1", user: seller, price_cents: 1000, archived: true) } let(:product2) { create(:product, name: "Product 2", user: seller, price_cents: 500) } it "doens't include the product in the product list" do visit checkout_form_path click_on "Add custom field" find(:label, "Products").click expect(page).to have_combo_box "Products", options: ["Product 2"] end end end describe "more like this" do it "allows updating the recommendation type" do visit checkout_form_path in_preview do expect(page).to have_section("Customers who bought this item also bought") within_section("Customers who bought this item also bought") do expect(page).to have_section("A Sample Product") end end choose "Don't recommend any products" in_preview do expect(page).to_not have_section("Customers who bought this item also bought") end click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.recommendation_type).to eq(User::RecommendationType::NO_RECOMMENDATIONS) visit checkout_form_path choose "Recommend my products" in_preview do expect(page).to have_section("Customers who bought this item also bought") within_section("Customers who bought this item also bought") do expect(page).to have_section("A Sample Product") end end click_on "Save changes" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.recommendation_type).to eq(User::RecommendationType::OWN_PRODUCTS) choose "Recommend all products and earn a commission with Gumroad Affiliates" in_preview do expect(page).to have_section("Customers who bought this item also bought") within_section("Customers who bought this item also bought") do expect(page).to have_section("A Sample Product") end end click_on "Save changes" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.recommendation_type).to eq(User::RecommendationType::GUMROAD_AFFILIATES_PRODUCTS) choose "Recommend my products and products I'm an affiliate of" in_preview do expect(page).to have_section("Customers who bought this item also bought") within_section("Customers who bought this item also bought") do expect(page).to have_section("A Sample Product") end end click_on "Save changes" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.recommendation_type).to eq(User::RecommendationType::DIRECTLY_AFFILIATED_PRODUCTS) end end describe "tipping" do it "allows updating the tipping setting" do visit checkout_form_path find_field("Allow customers to add tips to their orders", checked: false).check in_preview do expect(page).to have_text("Add a tip") expect(page).to have_radio_button("0%", checked: true) expect(page).to have_radio_button("10%", checked: false) expect(page).to have_radio_button("20%", checked: false) expect(page).to have_radio_button("Other", checked: false) end click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.tipping_enabled).to eq(true) refresh in_preview do expect(page).to have_text("Add a tip") expect(page).to have_radio_button("0%", checked: true) expect(page).to have_radio_button("10%", checked: false) expect(page).to have_radio_button("20%", checked: false) expect(page).to have_radio_button("Other", checked: false) end find_field("Allow customers to add tips to their orders", checked: true).uncheck click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(seller.reload.tipping_enabled).to eq(false) end end describe "preview" do context "when the user has alive products" do let!(:product1) { create(:product, user: seller, name: "Product 1") } let!(:product2) { create(:product, user: seller, name: "Product 2") } it "displays the product that was created first" do visit checkout_form_path in_preview do within_cart_item "Product 1" do expect(page).to have_text("Seller") expect(page).to have_text("Qty: 1") expect(page).to have_text("US$1") end end end end context "when the user has no products" do it "displays a placeholder product" do visit checkout_form_path in_preview do within_cart_item "A Sample Product" do expect(page).to have_text("Gumroadian") expect(page).to have_text("Qty: 1") expect(page).to have_text("US$1") 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/checkout/multi_item_receipt_spec.rb
spec/requests/checkout/multi_item_receipt_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Multi-item receipt", :js, type: :system do include ActiveJob::TestHelper let(:seller_one) { create(:user) } let(:product_one) { create(:product, user: seller_one, price_cents: 110, name: "Product One") } let(:seller_two) { create(:user) } let(:product_two) { create(:product, user: seller_two, price_cents: 120, name: "Product Two") } let(:product_three) { create(:product, user: seller_two, price_cents: 130, name: "Product Three") } before do visit product_one.long_url add_to_cart(product_one) visit product_two.long_url add_to_cart(product_two) visit product_three.long_url add_to_cart(product_three) end it "sends one receipt per seller", :sidekiq_inline do allow(CustomerMailer).to receive(:receipt).with(nil, anything).exactly(2).times.and_call_original # It doesn't matter which product is being passed, it works with multiple products check_out(product_one) expect(CustomerMailer).to have_received(:receipt).with(nil, product_one.sales.first.charge.id) expect(CustomerMailer).to have_received(:receipt).with(nil, product_two.sales.first.charge.id) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/checkout/bundle_spec.rb
spec/requests/checkout/bundle_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Checkout bundles", :js, type: :system do let(:seller) { create(:named_seller) } let(:bundle) { create(:product, user: seller, is_bundle: true, price_cents: 1000) } let(:product) { create(:product, user: seller, name: "Product", price_cents: 500) } let!(:bundle_product) { create(:bundle_product, bundle:, product:) } let(:versioned_product) { create(:product_with_digital_versions, user: seller, name: "Versioned product") } let!(:versioned_bundle_product) { create(:bundle_product, bundle:, product: versioned_product, variant: versioned_product.alive_variants.first, quantity: 3) } before do product.product_files << create(:readable_document, pdf_stamp_enabled: true) end it "allows purchasing the bundle" do visit bundle.long_url add_to_cart(bundle) within_cart_item "This bundle contains..." do within_cart_item "Product" do expect(page).to have_text("Qty: 1") end within_cart_item "Versioned product" do expect(page).to have_text("Qty: 3") expect(page).to have_text("Version: Untitled 1") end end fill_checkout_form(bundle) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful!") expect(page).to_not have_link("Product") expect(page).to have_section("Product") expect(page).to have_link("Versioned product - Untitled 1", href: Purchase.last.url_redirect.download_page_url) expect(page).to_not have_link("Bundle") end context "when the buyer is logged in" do it "redirects to the library after purchase" do buyer = create(:buyer_user) login_as buyer visit bundle.long_url add_to_cart(bundle) fill_checkout_form(bundle, logged_in_user: buyer) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful!") expect(page.current_url).to eq(library_url({ bundles: bundle.external_id, host: UrlService.domain_with_protocol })) end end context "when the bundle changes mid-purchase" do it "displays an error and allows purchase on retry" do visit bundle.long_url add_to_cart(bundle) versioned_bundle_product.update!(quantity: 2) check_out(bundle, error: true) expect(page).to have_alert(text: "The bundle's contents have changed. Please refresh the page!") visit current_path fill_checkout_form(bundle) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful!") end end context "when the bundle has a physical product" do let(:physical_bundle) { create(:product, :bundle, user: seller) } let(:physical_product) { create(:physical_product, user: seller, name: "Physical product", skus: [create(:sku)]) } let!(:physical_bundle_product) { create(:bundle_product, bundle: physical_bundle, product: physical_product, variant: physical_product.skus.first, quantity: 3) } it "collects the shipping information" do visit physical_bundle.long_url add_to_cart(physical_bundle) fill_checkout_form(physical_bundle, address: { street: "2031 7th Ave", state: "WA", city: "Seattle", zip_code: "98121" }) click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful!") purchase = Purchase.last expect(purchase.street_address).to eq("2031 7TH AVE") expect(purchase.city).to eq("SEATTLE") expect(purchase.state).to eq("WA") expect(purchase.zip_code).to eq("98121") end end context "when the bundle products have custom fields" do let(:custom_fields_bundle) { create(:product, :with_custom_fields, is_bundle: true, user: seller, name: "Bundle") } let(:product1) { create(:product, :with_custom_fields, user: seller, name: "Product 1") } let!(:product1_bundle_product) { create(:bundle_product, bundle: custom_fields_bundle, product: product1) } let(:product2) { create(:product, :with_custom_fields, user: seller, name: "Product 2") } let!(:product2_bundle_product) { create(:bundle_product, bundle: custom_fields_bundle, product: product2) } it "records custom fields for all bundle products" do visit custom_fields_bundle.long_url add_to_cart(custom_fields_bundle) fill_checkout_form(custom_fields_bundle) click_on "Pay" within "[aria-label='Payment form']" do within_section "Bundle" do fill_in "Text field", aria: { invalid: "false" }, with: "Bundle" check "Checkbox field", aria: { invalid: "true" } check "I accept", aria: { invalid: "true" } end within_section "Product 1" do fill_in "Text field", aria: { invalid: "false" }, with: "Product 1" check "Checkbox field", aria: { invalid: "true" } check "I accept", aria: { invalid: "true" } end within_section "Product 2" do fill_in "Text field", aria: { invalid: "false" }, with: "Product 2" check "Checkbox field", aria: { invalid: "true" } check "I accept", aria: { invalid: "true" } end end click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful!") bundle_purchase = Purchase.third_to_last expect(bundle_purchase).to be_successful expect(bundle_purchase.custom_fields).to eq( [ { name: "Text field", value: "Bundle", type: CustomField::TYPE_TEXT }, { name: "Checkbox field", value: true, type: CustomField::TYPE_CHECKBOX }, { name: "http://example.com", value: true, type: CustomField::TYPE_TERMS }, ] ) product1_purchase = Purchase.second_to_last expect(product1_purchase).to be_successful expect(product1_purchase.custom_fields).to eq( [ { name: "Text field", value: "Product 1", type: CustomField::TYPE_TEXT }, { name: "Checkbox field", value: true, type: CustomField::TYPE_CHECKBOX }, { name: "http://example.com", value: true, type: CustomField::TYPE_TERMS }, ] ) product2_purchase = Purchase.last expect(product2_purchase).to be_successful expect(product2_purchase.custom_fields).to eq( [ { name: "Text field", value: "Product 2", type: CustomField::TYPE_TEXT }, { name: "Checkbox field", value: true, type: CustomField::TYPE_CHECKBOX }, { name: "http://example.com", value: true, type: CustomField::TYPE_TERMS }, ] ) end end context "gifting bundles with license keys" do let(:bundle_with_licensed_product) { create(:product, user: seller, is_bundle: true) } let(:licensed_product) { create(:product, user: seller, name: "Licensed product", is_licensed: true) } let!(:licensed_bundle_product) { create(:bundle_product, bundle: bundle_with_licensed_product, product: licensed_product) } let(:giftee_email) { "giftee@gumroad.com" } it "only generates a license key for the giftee" do visit bundle_with_licensed_product.long_url add_to_cart(bundle_with_licensed_product) check_out(bundle_with_licensed_product, gift: { email: giftee_email, note: "Gifting licensed bundle!" }) expect(Purchase.all_success_states.count).to eq 4 expect(Gift.successful.where(link_id: bundle_with_licensed_product.id, gifter_email: "test@gumroad.com", giftee_email:).count).to eq 1 gifter_purchase = bundle_with_licensed_product.sales.is_gift_sender_purchase.sole giftee_purchase = bundle_with_licensed_product.sales.is_gift_receiver_purchase.sole expect(gifter_purchase.product_purchases.sole.license).to be_nil expect(giftee_purchase.product_purchases.sole.license).to_not be_nil expect(giftee_purchase.product_purchases.sole.license_key).to be_present # Both sender and receiver receipts should load properly visit gifter_purchase.receipt_url expect(page).to have_text("Gift sent to") visit giftee_purchase.receipt_url expect(page).to have_text("You've received a gift!") end end context "test purchase" do it "displays the temporary library on purchase" do login_as seller visit bundle.long_url add_to_cart(bundle) fill_in "ZIP code", with: "12345" click_on "Pay" expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to seller@example.com.") purchases = Purchase.last(3) purchases.each do |purchase| expect(purchase.purchase_state).to eq("test_successful") expect(purchase.is_test_purchase?).to eq(true) end expect(page).to_not have_link("Product") expect(page).to have_section("Product") expect(page).to have_link("Versioned product - Untitled 1", href: purchases.last.url_redirect.download_page_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/checkout/cart_spec.rb
spec/requests/checkout/cart_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Checkout cart", :js, type: :system do before do @product = create(:product, price_cents: 1000, quantity_enabled: true) @pwyw_product = create(:product, price_cents: 1000, customizable_price: true, thumbnail: create(:thumbnail)) @versioned_product = create(:product_with_digital_versions, thumbnail: create(:thumbnail)) @membership_product = create(:membership_product_with_preset_tiered_pricing, recurrence_price_values: [ { "monthly": { enabled: true, price: 2 }, "yearly": { enabled: true, price: 4 } }, { "monthly": { enabled: true, price: 5 }, "yearly": { enabled: true, price: 10 } } ]) @rental_product = create(:product, purchase_type: "buy_and_rent", price_cents: 500, rental_price_cents: 300) end describe "edit popover" do it "updates the option" do @variant1 = @versioned_product.variant_categories.first.variants.first @variant2 = @versioned_product.variant_categories.first.variants.second @variant2.update!(price_difference_cents: 100) visit @versioned_product.long_url add_to_cart(@versioned_product, option: @variant1.name) within_cart_item(@versioned_product.name) do expect(page).to have_link(@versioned_product.name, href: @versioned_product.long_url) expect(page).to have_selector("a[href='#{@versioned_product.long_url}'] > img[src='#{@versioned_product.thumbnail.url}']") expect(page).to have_text("US$1") select_disclosure "Edit" do choose @variant2.name click_on "Save changes" end end within_cart_item(@versioned_product.name) do expect(page).to have_link(@versioned_product.name, href: @versioned_product.long_url) expect(page).to have_selector("a[href='#{@versioned_product.long_url}'] > img[src='#{@versioned_product.thumbnail.url}']") expect(page).to have_text("US$2") expect(page).to have_text("Version: #{@variant2.name}") end visit @versioned_product.long_url add_to_cart(@versioned_product, option: @variant1.name) within_cart_item(@versioned_product.name) do select_disclosure "Edit" do choose @variant2.name click_on "Save changes" end expect(page).to have_alert(text: "You already have this item in your cart.") choose @variant1.name expect(page).to_not have_alert end check_out(@versioned_product, cart_item_count: 2) end it "updates the recurrence" do visit @membership_product.long_url add_to_cart(@membership_product, recurrence: "Yearly", option: @membership_product.variant_categories.first.variants.first.name) within_cart_item(@membership_product.name) do expect(page).to have_link(@membership_product.name, href: @membership_product.long_url) expect(page).to have_selector("a[href='#{@membership_product.long_url}'] > img") expect(page).to have_text("US$4 Yearly", normalize_ws: true) select_disclosure "Edit" do select "Monthly", from: "Recurrence" click_on "Save changes" end end within_cart_item(@membership_product.name) do expect(page).to have_link(@membership_product.name, href: @membership_product.long_url) expect(page).to have_text("US$2 Monthly", normalize_ws: true) end check_out(@membership_product) end it "updates the quantity" do visit @product.long_url add_to_cart(@product) within_cart_item(@product.name) do expect(page).to have_link(@product.name, href: @product.long_url) expect(page).to have_selector("a[href='#{@product.long_url}'] > img") expect(page).to have_text("US$10") select_disclosure "Edit" do fill_in "Quantity", with: 4 click_on "Save changes" end end within_cart_item(@product.name) do expect(page).to have_link(@product.name, href: @product.long_url) expect(page).to have_text("US$40") expect(page).to have_text("Qty: 4") end check_out(@product) end it "updates the PWYW price" do visit @pwyw_product.long_url add_to_cart(@pwyw_product, pwyw_price: 10) within_cart_item(@pwyw_product.name) do expect(page).to have_link(@pwyw_product.name, href: @pwyw_product.long_url) expect(page).to have_selector("a[href='#{@pwyw_product.long_url}'] > img[src='#{@pwyw_product.thumbnail.url}']") expect(page).to have_text("US$10") select_disclosure "Edit" do fill_in "Name a fair price", with: "5" click_on "Save changes" expect(find_field("Name a fair price")["aria-invalid"]).to eq("true") fill_in "Name a fair price", with: "20" click_on "Save changes" end end within_cart_item(@pwyw_product.name) do expect(page).to have_link(@pwyw_product.name, href: @pwyw_product.long_url) expect(page).to have_selector("a[href='#{@pwyw_product.long_url}'] > img[src='#{@pwyw_product.thumbnail.url}']") expect(page).to have_text("US$20") end check_out(@pwyw_product) end it "updates the rental" do visit @rental_product.long_url add_to_cart(@rental_product) within_cart_item(@rental_product.name) do expect(page).to have_link(@rental_product.name, href: @rental_product.long_url) expect(page).to have_selector("a[href='#{@rental_product.long_url}'] > img") expect(page).to have_text("US$5") select_disclosure "Edit" do choose "Rent" click_on "Save changes" end end within_cart_item(@rental_product.name) do expect(page).to have_link(@rental_product.name, href: @rental_product.long_url) expect(page).to have_text("US$3") end check_out(@rental_product) end describe "cart persistence" do let(:wait) { Selenium::WebDriver::Wait.new } context "when adding a product with a discount code" do let(:offer_code) { create(:percentage_offer_code, code: "get-it-for-free", amount_percentage: 100, products: [@product], user: @product.user) } it "calculates the discount and adds it to the cart" do buyer = create(:user) cart = create(:cart, user: buyer) login_as buyer visit "#{@product.long_url}/#{offer_code.code}" add_to_cart(@product, offer_code:) # Wait for the discount to be successfully verified - the card form will be removed when the product is free expect(page).to have_text("Discounts get-it-for-free US$-10", normalize_ws: true) expect(page).not_to have_selector(:fieldset, "Card information") expect(cart.reload.discount_codes).to eq([{ "code" => "get-it-for-free", "fromUrl" => true }]) end end it "persists the cart for a logged-in user and creates a different cart for the guest user on logout" do buyer = create(:user) login_as buyer visit @product.long_url add_to_cart(@product) wait.until { buyer.reload.alive_cart.present? } user_cart = Cart.alive.sole expect(user_cart.user).to eq(buyer) expect(user_cart.alive_cart_products.sole.product_id).to eq(@product.id) check_out(@product, logged_in_user: buyer, email: buyer.email) expect(user_cart.reload).to be_deleted expect(user_cart.email).to eq(buyer.email) expect(user_cart.order_id).to eq(Order.last.id) new_buyer_cart = buyer.reload.alive_cart expect(new_buyer_cart.browser_guid).to eq(user_cart.browser_guid) expect(new_buyer_cart.alive_cart_products.count).to eq(0) click_on "Back to Library" toggle_disclosure buyer.username click_on "Logout" visit @membership_product.long_url add_to_cart(@membership_product, recurrence: "Yearly", option: @membership_product.variants.first.name) wait.until { Cart.alive.count == 2 } guest_cart = Cart.last expect(guest_cart).to be_alive expect(guest_cart.user).to be_nil expect(guest_cart.alive_cart_products.sole.product_id).to eq(@membership_product.id) check_out(@membership_product) expect(guest_cart.reload).to be_deleted expect(guest_cart.email).to eq("test@gumroad.com") expect(guest_cart.order_id).to eq(Order.last.id) new_guest_cart = Cart.last expect(new_guest_cart).to be_alive expect(new_guest_cart.user).to be_nil expect(new_guest_cart.alive_cart_products.count).to eq(0) expect(new_buyer_cart.reload).to be_alive expect(new_buyer_cart.alive_cart_products.count).to eq(0) end it "creates and updates a cart during checkout for a logged-in user" do buyer = create(:user) login_as buyer visit @membership_product.long_url add_to_cart(@membership_product, recurrence: "Yearly", option: @membership_product.variant_categories.first.variants.first.name) wait.until { buyer.reload.alive_cart.present? && buyer.alive_cart.cart_products.exists? } cart = buyer.alive_cart cart_product = cart.cart_products.sole expect(cart_product).to have_attributes( product: @membership_product, recurrence: BasePrice::Recurrence::YEARLY, option: @membership_product.variant_categories.first.variants.first ) within_cart_item(@membership_product.name) do select_disclosure "Edit" do select "Monthly", from: "Recurrence" choose @membership_product.variants.second.name click_on "Save changes" end end wait.until { cart_product.reload.deleted? } new_cart_product = cart.cart_products.alive.sole expect(new_cart_product.reload).to have_attributes( recurrence: BasePrice::Recurrence::MONTHLY, option: @membership_product.variants.second ) visit @product.long_url add_to_cart(@product) wait.until { cart.cart_products.alive.count == 2 } expect(cart.cart_products.alive.first.product).to eq @membership_product expect(cart.cart_products.alive.second.product).to eq @product check_out(@product, logged_in_user: buyer) expect(cart.reload).to be_deleted # A new empty cart is created after checkout wait.until { buyer.reload.alive_cart.present? } expect(buyer.alive_cart.cart_products).to be_empty end it "creates a new cart with the failed item when an item fails after checkout" do buyer = create(:user) login_as buyer visit @membership_product.long_url add_to_cart(@membership_product, recurrence: "Yearly", option: @membership_product.variants.first.name) visit @product.long_url add_to_cart(@product) check_out(@product, logged_in_user: buyer, error: "The price just changed! Refresh the page for the updated price.") do @product.update!(price_cents: 100_00) end expect(page).to have_link("View content") wait.until { buyer.carts.count == 2 } expect(buyer.alive_cart.cart_products.sole.product).to eq @product refresh within_cart_item(@product.name) do expect(page).to have_text("US$100") end end it "merges the guest cart with the user's cart on login" do buyer = create(:user) buyer_cart = create(:cart, user: buyer, browser_guid: "old-browser-guid", email: "john@example.com") create(:cart_product, cart: buyer_cart, product: @product) visit @membership_product.long_url add_to_cart(@membership_product, recurrence: "Yearly", option: @membership_product.variants.first.name) wait.until { Cart.alive.count == 2 } guest_cart = Cart.alive.last expect(guest_cart.user).to be_nil expect(guest_cart.alive_cart_products.count).to eq(1) visit login_path fill_in "Email", with: buyer.email fill_in "Password", with: buyer.password click_on "Login" wait_for_ajax expect(page).to_not have_current_path(login_path) expect(buyer_cart.reload).to be_alive expect(guest_cart.reload).to be_deleted expect(buyer_cart.alive_cart_products.pluck(:product_id, :option_id)).to eq([[@product.id, nil], [@membership_product.id, @membership_product.variants.first.id]]) expect(buyer_cart.browser_guid).to_not eq("old-browser-guid") expect(buyer_cart.browser_guid).to eq(guest_cart.browser_guid) end describe "when adding products to the cart" do let(:buyer) { create(:buyer_user) } let(:seller) { create(:named_seller, name: "John Doe") } let(:product1) { create(:product, user: seller) } let(:product2) { create(:product, user: seller, name: "Another product") } describe "when cart has the maximum allowed products" do before do login_as buyer visit product1.long_url click_on text: "I want this!" wait.until { buyer.reload.alive_cart.present? } create_list(:cart_product, 49, cart: buyer.alive_cart) end it "shows an error message on adding a product to the cart" do visit product2.long_url click_on text: "I want this!" expect_alert_message "You cannot add more than 50 products to the cart." expect(page).to_not have_cart_item("Another product") expect(buyer.alive_cart.reload.alive_cart_products.find_by(product_id: product2.id)).to be_nil end end end context "when the checkout page URL contains `cart_id` query param" do context "when user is logged in" do it "shows user's cart without any modifications" do buyer = create(:user) user_cart = create(:cart, user: buyer) create(:cart_product, cart: user_cart, product: create(:product, name: "Product 1")) another_cart = create(:cart, :guest) create(:cart_product, cart: another_cart, product: create(:product, name: "Product 2")) login_as buyer visit checkout_index_path(cart_id: another_cart.external_id) expect(page).to have_current_path(checkout_index_path) expect(page).to have_text("Product 1") expect(page).to_not have_text("Product 2") expect(Cart.alive.count).to eq(2) expect(user_cart.reload.alive_cart_products.sole.product.name).to eq("Product 1") expect(another_cart.reload.alive_cart_products.sole.product.name).to eq("Product 2") end end context "when user is not logged in" do context "when the cart matching the `cart_id` query param belongs to a user" do it "redirects to the login page and merges the current guest cart with the logged in user's cart" do user_cart = create(:cart) create(:cart_product, cart: user_cart, product: create(:product, name: "Product 1")) product2 = create(:product, name: "Product 2") visit product2.long_url add_to_cart(product2) wait.until { Cart.alive.count == 2 } guest_cart = Cart.alive.last visit checkout_index_path(cart_id: user_cart.external_id) expect(page).to have_current_path(login_path(email: user_cart.user.email, next: checkout_index_path(referrer: UrlService.discover_domain_with_protocol))) fill_in "Password", with: user_cart.user.password click_on "Login" wait_for_ajax expect(page).to have_current_path(checkout_index_path) expect(Cart.alive.count).to eq(1) expect(guest_cart.reload).to be_deleted expect(user_cart.reload).to be_alive expect(user_cart.alive_cart_products.map(&:product).map(&:name)).to match_array(["Product 1", "Product 2"]) expect(user_cart.browser_guid).to eq(guest_cart.browser_guid) expect(page).to have_text("Product 1") expect(page).to have_text("Product 2") end end context "when the cart matching the `cart_id` query param has `browser_guid` different from the current `_gumroad_guid` cookie value" do it "merges the current guest cart with the cart matching the `cart_id` query param" do cart = create(:cart, :guest, browser_guid: SecureRandom.uuid) create(:cart_product, cart:, product: create(:product, name: "Product 1")) current_guest_cart = create(:cart, :guest) create(:cart_product, cart: current_guest_cart, product: create(:product, name: "Product 2")) visit root_path current_browser_guid = Capybara.current_session.driver.browser.manage.all_cookies.find { _1[:name] == "_gumroad_guid" }&.[](:value) current_guest_cart.update!(browser_guid: current_browser_guid) visit checkout_index_path(cart_id: cart.external_id) expect(page).to have_current_path(checkout_index_path) expect(page).to have_text("Product 1") expect(page).to have_text("Product 2") expect(Cart.alive.count).to eq(1) expect(current_guest_cart.reload).to be_deleted expect(cart.reload.alive_cart_products.map(&:product).map(&:name)).to match_array(["Product 1", "Product 2"]) expect(cart.reload.browser_guid).to eq(current_browser_guid) end end end end end context "when there are no configuration inputs" do it "hides the edit popover" do @product.update!(quantity_enabled: false) visit @product.long_url add_to_cart(@product) expect(page).to_not have_disclosure("Edit") 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/checkout/upsells_spec.rb
spec/requests/checkout/upsells_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" require "shared_examples/creator_dashboard_page" describe("Checkout upsells page", type: :system, js: true) do let(:seller) { create(:named_seller, :eligible_for_service_products) } let(:product1) { create(:product_with_digital_versions, user: seller, price_cents: 1000, name: "Product 1") } let(:product2) { create(:product_with_digital_versions, user: seller, price_cents: 500, name: "Product 2") } let!(:upsell1) { create(:upsell, product: product1, variant: product1.alive_variants.second, name: "Upsell 1", seller:, cross_sell: true, offer_code: create(:offer_code, user: seller, products: [product1]), updated_at: 2.days.ago) } let!(:upsell2) { create(:upsell, product: product2, name: "Upsell 2", seller:, updated_at: 1.day.ago) } let!(:upsell2_variant) { create(:upsell_variant, upsell: upsell2, selected_variant: product2.alive_variants.first, offered_variant: product2.alive_variants.second) } let!(:universal_upsell) { create(:upsell, product: product1, name: "Universal Upsell", seller:, cross_sell: true, universal: true) } before do product1.alive_variants.second.update!(price_difference_cents: 500) product2.alive_variants.second.update!(price_difference_cents: 500) build_list :product, 2, user: seller do |product, i| product.name = "Product #{i + 3}" create_list(:upsell_purchase, 2, upsell: upsell1, selected_product: product) upsell1.selected_products << product end create_list(:upsell_purchase, 5, upsell: upsell2, selected_product: product2, upsell_variant: upsell2_variant) end include_context "with switching account to user as admin for seller" it_behaves_like "creator dashboard page", "Checkout" do let (:path) { checkout_upsells_path } end describe "upsells table" do it "displays all upsells correctly" do visit checkout_upsells_path upsell1_row = find(:table_row, { "Upsell" => "Upsell 1", "Revenue" => "$40", "Uses" => "4" }) within upsell1_row do expect(page).to have_text("Product 1 - Untitled 2") end upsell1_row.click within_modal "Upsell 1" do within_section "Details" do expect(page).to have_text("Offer text Take advantage of this excellent offer", normalize_ws: true) expect(page).to have_text("Uses 4", normalize_ws: true) expect(page).to have_text("Revenue $40", normalize_ws: true) expect(page).to have_text("Discount $1", normalize_ws: true) end within_section "Selected products" do expect(page).to have_text("Product 3 2 uses from this product", normalize_ws: true) expect(page).to have_text("Product 4 2 uses from this product", normalize_ws: true) end within_section "Offered product" do expect(page).to have_text("Product 1 - Untitled 2") end expect(page).to_not have_section("Selected product", exact: true) expect(page).to_not have_section("Offers") expect(page).to have_button("Edit") expect(page).to have_button("Duplicate") expect(page).to have_button("Delete") end upsell2_row = find(:table_row, { "Upsell" => "Upsell 2", "Revenue" => "$25", "Uses" => "5" }) within upsell2_row do expect(page).to have_text("Product 2") end upsell2_row.click within_modal "Upsell 2" do within_section "Details" do expect(page).to have_text("Offer text Take advantage of this excellent offer", normalize_ws: true) expect(page).to have_text("Uses 5", normalize_ws: true) expect(page).to have_text("Revenue $25", normalize_ws: true) expect(page).to_not have_text("Discount") end within_section "Selected product" do expect(page).to have_text("Product 2") end within_section "Offers" do expect(page).to have_text("Untitled 1 → Untitled 2 5 uses", normalize_ws: true) end expect(page).to_not have_section("Selected products") expect(page).to_not have_section("Offered product") expect(page).to have_button("Edit") expect(page).to have_button("Duplicate") expect(page).to have_button("Delete") end universal_upsell_row = find(:table_row, { "Upsell" => "Universal Upsell" }) universal_upsell_row.click within_modal "Universal Upsell" do within_section "Selected products" do expect(page).to have_content("All products") end end end context "when the creator has no upsells" do it "displays a placeholder message" do login_as create(:user) visit checkout_upsells_path within_section "Offering an upsell at checkout" do expect(page).to have_text("Upsells allow you to suggest additional products to your customer at checkout. You can nudge them to purchase either an upgraded version or an extra product add-on.") click_on "New upsell" end expect(page).to have_section("Create an upsell") end end describe "sorting and pagination" do before do stub_const("Checkout::UpsellsController::PER_PAGE", 1) universal_upsell.destroy! end it "sorts and paginates the upsells" do visit checkout_upsells_path expect(page).to have_table "Upsells", with_rows: [{ "Upsell" => "Upsell 2" }] expect(page).to have_button("1", aria: { current: "page" }) click_on "Next" expect(page).to have_table "Upsells", with_rows: [{ "Upsell" => "Upsell 1" }] expect(page).to have_button("2", aria: { current: "page" }) click_on "Previous" expect(page).to have_table "Upsells", with_rows: [{ "Upsell" => "Upsell 2" }] expect(page).to have_button("1", aria: { current: "page" }) find(:columnheader, "Upsell").click expect(page).to have_button("1", aria: { current: "page" }) expect(page).to have_table "Upsells", with_rows: [{ "Upsell" => "Upsell 1" }] click_on "2" expect(page).to have_button("2", aria: { current: "page" }) expect(page).to have_table "Upsells", with_rows: [{ "Upsell" => "Upsell 2" }] find(:columnheader, "Revenue").click expect(page).to have_button("1", aria: { current: "page" }) expect(page).to have_table "Upsells", with_rows: [{ "Upsell" => "Upsell 2" }] click_on "Next" expect(page).to have_button("2", aria: { current: "page" }) expect(page).to have_table "Upsells", with_rows: [{ "Upsell" => "Upsell 1" }] find(:columnheader, "Uses").click expect(page).to have_button("1", aria: { current: "page" }) expect(page).to have_table "Upsells", with_rows: [{ "Upsell" => "Upsell 1" }] click_on "Next" expect(page).to have_button("2", aria: { current: "page" }) expect(page).to have_table "Upsells", with_rows: [{ "Upsell" => "Upsell 2" }] end end end def within_preview_modal(title:, &block) in_preview do within "[role=dialog]" do expect(page).to have_selector("h2", text: title) block.call end end end describe "upsell creation" do it "allows creating an upsell" do visit checkout_upsells_path click_on "New upsell" choose "Replace the version selected with another version of the same product" fill_in "Name", with: "Complete course upsell" fill_in "Offer text", with: "My cool upsell" fill_in "Offer description", with: "This is a really cool upsell" choose "Paused" within_preview_modal(title: "My cool upsell") do expect(page).to have_text("This is a really cool upsell") end fill_in "Offer text", with: "Enhance your learning experience" fill_in "Offer description", with: "You'll enjoy a range of exclusive features, including..." within_preview_modal(title: "Enhance your learning experience") do expect(page).to have_text("You'll enjoy a range of exclusive features, including...") end select_combo_box_option search: "Product 1", from: "Apply to this product" select_combo_box_option search: "Untitled 1", from: "Version to offer for Untitled 2" within_preview_modal(title: "Enhance your learning experience") do expect(page).to have_radio_button("Untitled 1", text: "$10") end within find("[aria-label='Upsell versions']") do click_on "Clear value" end select_combo_box_option search: "Untitled 2", from: "Version to offer for Untitled 1" within_preview_modal(title: "Enhance your learning experience") do expect(page).to have_radio_button("Untitled 2", text: "$15") end click_on "Save" expect(page).to have_alert(text: "Successfully created upsell!") find(:table_row, { "Upsell" => "Complete course upsell" }).click within_modal "Complete course upsell" do within_section "Details" do expect(page).to have_text("Offer text Enhance your learning experience", normalize_ws: true) expect(page).to have_text("Uses 0", normalize_ws: true) expect(page).to have_text("Revenue $0", normalize_ws: true) expect(page).to have_text("Status Paused", normalize_ws: true) end within_section "Selected product" do expect(page).to have_text("Product 1") end within_section "Offers" do expect(page).to have_text("Untitled 1 → Untitled 2") expect(page).to have_text("0 uses") end expect(page).to_not have_section("Selected products") expect(page).to_not have_section("Offered product") end upsell = seller.upsells.last expect(upsell.name).to eq("Complete course upsell") expect(upsell.text).to eq("Enhance your learning experience") expect(upsell.description).to eq("You'll enjoy a range of exclusive features, including...") expect(upsell.cross_sell).to eq(false) expect(upsell.product).to eq(product1) expect(upsell.upsell_variants.first.selected_variant).to eq(product1.alive_variants.first) expect(upsell.upsell_variants.first.offered_variant).to eq(product1.alive_variants.second) end context "when a product is archived" do before { product1.update!(archived: true) } it "doens't include the product in the product list" do visit checkout_upsells_path click_on "New upsell" find(:label, "Apply to these products").click expect(page).to have_combo_box "Apply to these products", options: (2..7).map { |i| "Product #{i}" } send_keys(:escape) find(:label, "Product to offer").click expect(page).to have_combo_box "Product to offer", options: (2..7).map { |i| "Product #{i}" } end end context "when the creator has a call product" do before { create(:call_product, user: seller, name: "Product Call") } it "can have a upsell but cannot be offered as a upsell" do visit checkout_upsells_path click_on "New upsell" find(:label, "Apply to these products").click expect(page).to have_combo_box "Apply to these products", with_options: ["Product Call"] send_keys(:escape) find(:label, "Product to offer").click expect(page).not_to have_combo_box "Product to offer", with_options: ["Product Call"] end end it "allows creating a cross-sell upsell" do visit checkout_upsells_path click_on "New upsell" choose "Replace the selected products with another product" fill_in "Name", with: "Complete course upsell" fill_in "Offer text", with: "My cool upsell" fill_in "Offer description", with: "This is a really cool upsell" within_preview_modal(title: "My cool upsell") do expect(page).to have_text("This is a really cool upsell") end fill_in "Offer text", with: "Enhance your learning experience" fill_in "Offer description", with: "You'll enjoy a range of exclusive features, including..." within_preview_modal(title: "Enhance your learning experience") do expect(page).to have_text("You'll enjoy a range of exclusive features, including...") end select_combo_box_option search: "Product 1", from: "Apply to these products" select_combo_box_option search: "Product 3", from: "Product to offer" within_preview_modal(title: "Enhance your learning experience") do within_section "Product 3", section_element: :article do expect(page).to have_link("Seller") expect(page).to have_selector("[itemprop='price']", text: "$1") end end find(:label, "Product to offer").click select_combo_box_option search: "Product 2", from: "Product to offer" select_combo_box_option search: "Untitled 2", from: "Version to offer" within_preview_modal(title: "Enhance your learning experience") do within_section "Product 2 - Untitled 2", section_element: :article do expect(page).to have_link("Seller") expect(page).to have_selector("[itemprop='price']", text: "$10") end end find(:label, "Version to offer").click select_combo_box_option search: "Untitled 1", from: "Version to offer" within_preview_modal(title: "Enhance your learning experience") do within_section "Product 2 - Untitled 1", section_element: :article do expect(page).to have_selector("[itemprop='price']", text: "$5") end end check "Add discount to the offered product" fill_in "Percentage", with: "20" within_preview_modal(title: "Enhance your learning experience") do within_section "Product 2 - Untitled 1", section_element: :article do expect(page).to have_selector("[itemprop='price']", text: "$5 $4") end end click_on "Save" expect(page).to have_alert(text: "Successfully created upsell!") find(:table_row, { "Upsell" => "Complete course upsell" }).click within_modal "Complete course upsell" do within_section "Details" do expect(page).to have_text("Offer text Enhance your learning experience", normalize_ws: true) expect(page).to have_text("Discount 20%", normalize_ws: true) expect(page).to have_text("Uses 0", normalize_ws: true) expect(page).to have_text("Revenue $0", normalize_ws: true) end within_section "Selected products" do expect(page).to have_text("Product 1") expect(page).to have_text("0 uses from this product") end within_section "Offered product" do expect(page).to have_text("Product 2 - Untitled 1") end expect(page).to_not have_section("Selected product", exact: true) expect(page).to_not have_section("Offers") end upsell = seller.upsells.last expect(upsell.name).to eq("Complete course upsell") expect(upsell.text).to eq("Enhance your learning experience") expect(upsell.description).to eq("You'll enjoy a range of exclusive features, including...") expect(upsell.cross_sell).to eq(true) expect(upsell.replace_selected_products).to eq(true) expect(upsell.universal).to eq(false) expect(upsell.product).to eq(product2) expect(upsell.variant).to eq(product2.alive_variants.first) expect(upsell.selected_products).to eq([product1]) expect(upsell.offer_code.amount_percentage).to eq(20) expect(upsell.offer_code.products).to eq([product2]) end it "allows creating a universal cross-sell upsell" do visit checkout_upsells_path click_on "New upsell" fill_in "Name", with: "Complete course upsell" fill_in "Offer text", with: "My cool upsell" fill_in "Offer description", with: "This is a really cool upsell" within_preview_modal(title: "My cool upsell") do expect(page).to have_text("This is a really cool upsell") end fill_in "Offer text", with: "Enhance your learning experience" fill_in "Offer description", with: "You'll enjoy a range of exclusive features, including..." check "All products" select_combo_box_option search: "Product 1", from: "Product to offer" select_combo_box_option search: "Untitled 2", from: "Version to offer" click_on "Save" expect(page).to have_alert(text: "Successfully created upsell!") find(:table_row, { "Upsell" => "Complete course upsell" }).click upsell = seller.upsells.last expect(upsell.name).to eq("Complete course upsell") expect(upsell.text).to eq("Enhance your learning experience") expect(upsell.description).to eq("You'll enjoy a range of exclusive features, including...") expect(upsell.cross_sell).to eq(true) expect(upsell.replace_selected_products).to eq(false) expect(upsell.universal).to eq(true) expect(upsell.product).to eq(product1) expect(upsell.variant).to eq(product1.alive_variants.second) expect(upsell.selected_products).to eq([]) expect(upsell.offer_code).to eq(nil) end it "validates the upsell form" do visit checkout_upsells_path click_on "New upsell" click_on "Save" expect(page).to have_alert(text: "Please complete all required fields.") expect(find_field("Name")["aria-invalid"]).to eq("true") expect(find_field("Offer text")["aria-invalid"]).to eq("true") expect(find_field("Apply to these products")["aria-invalid"]).to eq("true") expect(find_field("Product to offer")["aria-invalid"]).to eq("true") select_combo_box_option search: "Product 1", from: "Product to offer" wait_for_ajax click_on "Save" expect(find_field("Version to offer")["aria-invalid"]).to eq("true") choose "Replace the version selected with another version of the same product" click_on "Save" expect(page).to have_alert(text: "Please complete all required fields.") expect(find_field("Apply to this product")["aria-invalid"]).to eq("true") end end describe "upsell editing" do it "allows updating an upsell to a cross-sell" do visit checkout_upsells_path find(:table_row, { "Upsell" => "Upsell 2" }).click click_on "Edit" choose "Add another product to the cart" fill_in "Name", with: "Complete course upsell", fill_options: { clear: :backspace } fill_in "Offer text", with: "Enhance your learning experience", fill_options: { clear: :backspace } fill_in "Offer description", with: "You'll enjoy a range of exclusive features, including...", fill_options: { clear: :backspace } select_combo_box_option search: "Product 1", from: "Apply to these products" select_combo_box_option search: "Product 2", from: "Product to offer" select_combo_box_option search: "Untitled 1", from: "Version to offer" check "Add discount to the offered product" choose "Percentage" fill_in "Percentage", with: "20" click_on "Save" expect(page).to have_alert(text: "Successfully updated upsell!") find(:table_row, { "Upsell" => "Complete course upsell" }).click within_modal "Complete course upsell" do within_section "Details" do expect(page).to have_text("Offer text Enhance your learning experience", normalize_ws: true) expect(page).to have_text("Discount 20%", normalize_ws: true) expect(page).to have_text("Uses 5", normalize_ws: true) expect(page).to have_text("Revenue $25", normalize_ws: true) end within_section "Selected products" do expect(page).to have_text("Product 1") expect(page).to have_text("0 uses from this product") end within_section "Offered product" do expect(page).to have_text("Product 2 - Untitled 1") end expect(page).to_not have_section("Selected product", exact: true) expect(page).to_not have_section("Offers") end upsell2.reload expect(upsell2.name).to eq("Complete course upsell") expect(upsell2.text).to eq("Enhance your learning experience") expect(upsell2.description).to eq("You'll enjoy a range of exclusive features, including...") expect(upsell2.cross_sell).to eq(true) expect(upsell2.replace_selected_products).to eq(false) expect(upsell2.universal).to eq(false) expect(upsell2.product).to eq(product2) expect(upsell2.variant).to eq(product2.alive_variants.first) expect(upsell2.selected_products).to eq([product1]) expect(upsell2.offer_code.amount_percentage).to eq(20) expect(upsell2.offer_code.products).to eq([product2]) end it "allows updating a cross-sell to an upsell" do visit checkout_upsells_path find(:table_row, { "Upsell" => "Upsell 1" }).click click_on "Edit" fill_in "Name", with: "Complete course upsell" fill_in "Offer text", with: "Enhance your learning experience" fill_in "Offer description", with: "You'll enjoy a range of exclusive features, including..." choose "Replace the version selected with another version of the same product" select_combo_box_option search: "Product 1", from: "Apply to this product" select_combo_box_option search: "Untitled 2", from: "Version to offer for Untitled 1" click_on "Save" expect(page).to have_alert(text: "Successfully updated upsell!") find(:table_row, { "Upsell" => "Complete course upsell" }).click within_modal "Complete course upsell" do within_section "Details" do expect(page).to have_text("Offer text Enhance your learning experience", normalize_ws: true) expect(page).to have_text("Uses 4", normalize_ws: true) expect(page).to have_text("Revenue $40", normalize_ws: true) end within_section "Selected product" do expect(page).to have_text("Product 1") end within_section "Offers" do expect(page).to have_text("Untitled 1 → Untitled 2") expect(page).to have_text("0 uses") end expect(page).to_not have_section("Selected products") expect(page).to_not have_section("Offered product") end upsell1.reload expect(upsell1.name).to eq("Complete course upsell") expect(upsell1.text).to eq("Enhance your learning experience") expect(upsell1.description).to eq("You'll enjoy a range of exclusive features, including...") expect(upsell1.cross_sell).to eq(false) expect(upsell1.product).to eq(product1) expect(upsell1.upsell_variants.first.selected_variant).to eq(product1.alive_variants.first) expect(upsell1.upsell_variants.first.offered_variant).to eq(product1.alive_variants.second) end context "when has archived products" do let(:selected_product) { upsell1.selected_products.first } let(:product) { upsell1.product } before do product.update!(archived: true) selected_product.update!(archived: true) end it "preserves the archived products on save" do visit checkout_upsells_path find(:table_row, { "Upsell" => "Upsell 1" }).click click_on "Edit" find(:label, "Apply to these products").click expect(page).to have_combo_box "Apply to these products", options: (2..7).map { |i| "Product #{i}" } send_keys(:escape) expect(page).to have_text(selected_product.name) click_on "Save" expect(upsell1.reload.product).to eq(product) expect(upsell1.selected_products).to include(selected_product) end end end it "allows deleting the selected upsell" do visit checkout_upsells_path find(:table_row, { "Upsell" => "Upsell 2" }).click click_on "Delete" expect(page).to have_alert(text: "Successfully deleted upsell!") expect(page).to_not have_selector(:table_row, { "Upsell" => "Upsell 2" }) visit checkout_upsells_path expect(page).to_not have_selector(:table_row, { "Upsell" => "Upsell 2" }) expect(upsell2.reload.deleted_at).to be_present expect(upsell2_variant.reload.deleted_at).to be_present find(:table_row, { "Upsell" => "Upsell 1" }).click click_on "Delete" expect(page).to have_alert(text: "Successfully deleted upsell!") expect(page).to_not have_selector(:table_row, { "Upsell" => "Upsell 1" }) visit checkout_upsells_path expect(page).to_not have_selector(:table_row, { "Upsell" => "Upsell 1" }) expect(upsell1.reload.deleted_at).to be_present expect(upsell1.offer_code.reload.deleted_at).to be_present end it "allows pausing the selected upsell" do visit checkout_upsells_path find(:table_row, { "Upsell" => "Upsell 2" }).click within_modal "Upsell 2" do within_section "Details" do expect(page).to have_text("Status Live", normalize_ws: true) end click_on "Pause upsell" end expect(page).to have_alert(text: "Upsell paused and will not appear at checkout.") find(:table_row, { "Upsell" => "Upsell 2", "Status" => "Paused" }).click within_modal "Upsell 2" do within_section "Details" do expect(page).to have_text("Status Paused", normalize_ws: true) end end expect(upsell2.reload.paused).to eq(true) end it "allows resuming the selected upsell" do upsell2.update!(paused: true) visit checkout_upsells_path find(:table_row, { "Upsell" => "Upsell 2", "Status" => "Paused" }).click within_modal "Upsell 2" do within_section "Details" do expect(page).to have_text("Status Paused", normalize_ws: true) end click_on "Resume upsell" end expect(page).to have_alert(text: "Upsell resumed and will appear at checkout.") find(:table_row, { "Upsell" => "Upsell 2", "Status" => "Live" }).click within_modal "Upsell 2" do within_section "Details" do expect(page).to have_text("Status Live", normalize_ws: true) end end expect(upsell2.reload.paused).to eq(false) end it "allows duplicating the selected upsell" do visit checkout_upsells_path find(:table_row, { "Upsell" => "Upsell 1" }).click click_on "Duplicate" expect(find_field("Name").value).to eq("Upsell 1 (copy)") fill_in "Name", with: "Complete course upsell" fill_in "Offer text", with: "Enhance your learning experience" fill_in "Offer description", with: "You'll enjoy a range of exclusive features, including..." choose "Replace the version selected with another version of the same product" select_combo_box_option search: "Product 1", from: "Apply to this product" select_combo_box_option search: "Untitled 2", from: "Version to offer for Untitled 1" click_on "Save" expect(page).to have_alert(text: "Successfully created upsell!") find(:table_row, { "Upsell" => "Complete course upsell" }).click within_modal "Complete course upsell" do within_section "Details" do expect(page).to have_text("Offer text Enhance your learning experience", normalize_ws: true) expect(page).to have_text("Uses 0", normalize_ws: true) expect(page).to have_text("Revenue $0", normalize_ws: true) end within_section "Selected product" do expect(page).to have_text("Product 1") end within_section "Offers" do expect(page).to have_text("Untitled 1 → Untitled 2") expect(page).to have_text("0 uses") end expect(page).to_not have_section("Selected products") expect(page).to_not have_section("Offered product") end upsell = seller.upsells.last expect(upsell.name).to eq("Complete course upsell") expect(upsell.text).to eq("Enhance your learning experience") expect(upsell.description).to eq("You'll enjoy a range of exclusive features, including...") expect(upsell.cross_sell).to eq(false) expect(upsell.replace_selected_products).to eq(false) expect(upsell.product).to eq(product1) expect(upsell.upsell_variants.first.selected_variant).to eq(product1.alive_variants.first) expect(upsell.upsell_variants.first.offered_variant).to eq(product1.alive_variants.second) end it "allows duplicating the selected cross-sell" do visit checkout_upsells_path find(:table_row, { "Upsell" => "Upsell 2" }).click click_on "Duplicate" expect(find_field("Name").value).to eq("Upsell 2 (copy)") fill_in "Name", with: "Complete course upsell", fill_options: { clear: :backspace } fill_in "Offer text", with: "Enhance your learning experience", fill_options: { clear: :backspace } fill_in "Offer description", with: "You'll enjoy a range of exclusive features, including...", fill_options: { clear: :backspace } choose "Add another product to the cart" select_combo_box_option search: "Product 1", from: "Apply to these products", match: :first select_combo_box_option search: "Product 2", from: "Product to offer" select_combo_box_option search: "Untitled 1", from: "Version to offer" check "Add discount to the offered product" fill_in "Percentage", with: "20" click_on "Save" expect(page).to have_alert(text: "Successfully created upsell!") find(:table_row, { "Upsell" => "Complete course upsell" }).click within_modal "Complete course upsell" do within_section "Details" do expect(page).to have_text("Offer text Enhance your learning experience", normalize_ws: true) expect(page).to have_text("Discount 20%", normalize_ws: true) expect(page).to have_text("Uses 0", normalize_ws: true) expect(page).to have_text("Revenue $0", normalize_ws: true) end within_section "Selected products" do expect(page).to have_text("Product 1") expect(page).to have_text("0 uses from this product") end within_section "Offered product" do expect(page).to have_text("Product 2 - Untitled 1") end expect(page).to_not have_section("Selected product", exact: true) expect(page).to_not have_section("Offers") end upsell = seller.upsells.last expect(upsell.name).to eq("Complete course upsell") expect(upsell.text).to eq("Enhance your learning experience") expect(upsell.description).to eq("You'll enjoy a range of exclusive features, including...") expect(upsell.cross_sell).to eq(true) expect(upsell.replace_selected_products).to eq(false) expect(upsell.universal).to eq(false) expect(upsell.product).to eq(product2) expect(upsell.variant).to eq(product2.alive_variants.first) expect(upsell.selected_products).to eq([product1]) expect(upsell.offer_code.amount_percentage).to eq(20) expect(upsell.offer_code.products).to eq([product2]) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/checkout/offer_codes_spec.rb
spec/requests/checkout/offer_codes_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Checkout offer codes", :js, type: :system do before do @product = create(:product, price_cents: 1000) @product2 = create(:product, price_cents: 1000) end it "only shows the discount code field for users that have it enabled" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) visit "/l/#{@product2.unique_permalink}" add_to_cart(@product2) expect(page).to_not have_field("Discount code") create(:percentage_offer_code, products: [@product], amount_percentage: 15) visit "/l/#{@product.unique_permalink}" add_to_cart(@product) expect(page).to_not have_field("Discount code") @product.user.update!(display_offer_code_field: true) visit "/l/#{@product.unique_permalink}" add_to_cart(@product) expect(page).to have_field("Discount code") end it "does not show $0 discount codes that were added from the URL" do zero_percent_code = create(:percentage_offer_code, products: [@product], amount_percentage: 0, code: "0p") zero_cent_code = create(:percentage_offer_code, products: [@product], amount_percentage: 0, code: "0c") visit "/l/#{@product.unique_permalink}?offer_code=0p" add_to_cart(@product, offer_code: zero_percent_code) visit "/checkout?code=0c" expect(page).to_not have_text zero_percent_code.code expect(page).to_not have_text zero_cent_code.code actual_code = create(:percentage_offer_code, products: [@product], amount_percentage: 15) visit "/checkout?code=#{actual_code.code}" expect(page).to have_text(actual_code.code) end context "discount has already been applied to an item in the cart" do let(:seller) { create(:user, display_offer_code_field: true) } let!(:offer_code) { create(:percentage_offer_code, user: seller, universal: true, products: [], code: "everything") } let!(:product1) { create(:product, user: seller, name: "Product 1", price_cents: 1000) } let!(:product2) { create(:product, user: seller, name: "Product 2", price_cents: 2000) } it "applies the discount to items added to the cart" do visit product1.long_url add_to_cart(product1) fill_in "Discount code", with: "everything" click_on "Apply" expect(page).to have_text("Discounts everything US$-5", normalize_ws: true) visit product2.long_url add_to_cart(product2) expect(page).to have_text("Discounts everything US$-15", normalize_ws: true) check_out(product2) purchase1 = Purchase.last expect(purchase1.offer_code).to eq(offer_code) expect(purchase1.price_cents).to eq(500) expect(purchase1.link).to eq(product1) purchase2 = Purchase.second_to_last expect(purchase2.offer_code).to eq(offer_code) expect(purchase2.price_cents).to eq(1000) expect(purchase2.link).to eq(product2) end end describe "when product is removed from cart" do let(:seller) { create(:user, display_offer_code_field: true) } let!(:product1) { create(:product, user: seller, name: "Product 1", price_cents: 1000) } let!(:product2) { create(:product, user: seller, name: "Product 2", price_cents: 2000) } let!(:product3) { create(:product, user: seller, name: "Product 3", price_cents: 3000) } let(:product1_and_2_offer_code) { create(:percentage_offer_code, user: seller, products: [product1, product2], code: "product1_and_2_offer_code") } context "discount applies to all products" do let!(:offer_code) { create(:percentage_offer_code, user: seller, universal: true, products: [], code: "everything") } it "does not remove the discount" do visit product1.long_url add_to_cart(product1) fill_in "Discount code", with: "everything" click_on "Apply" expect(page).to have_text("Discounts everything US$-5", normalize_ws: true) visit product2.long_url add_to_cart(product2) expect(page).to have_text("Discounts everything US$-15", normalize_ws: true) visit product3.long_url add_to_cart(product3) expect(page).to have_text("Discounts everything US$-30", normalize_ws: true) within_cart_item "Product 3" do click_on "Remove" end wait_for_ajax expect(page).to have_text("Discounts everything US$-15", normalize_ws: true) check_out(product1) purchase1 = Purchase.last expect(purchase1.offer_code).to eq(offer_code) expect(purchase1.price_cents).to eq(500) expect(purchase1.link).to eq(product1) purchase2 = Purchase.second_to_last expect(purchase2.offer_code).to eq(offer_code) expect(purchase2.price_cents).to eq(1000) expect(purchase2.link).to eq(product2) end end context "discount applies to other products" do before do product1_and_2_offer_code end it "does not remove the discount" do visit product1.long_url add_to_cart(product1) fill_in "Discount code", with: "product1_and_2_offer_code" click_on "Apply" expect(page).to have_text("Discounts product1_and_2_offer_code US$-5", normalize_ws: true) visit product2.long_url add_to_cart(product2) expect(page).to have_text("Discounts product1_and_2_offer_code US$-15", normalize_ws: true) visit product3.long_url add_to_cart(product3) expect(page).to have_text("Discounts product1_and_2_offer_code US$-15", normalize_ws: true) within_cart_item "Product 2" do click_on "Remove" end wait_for_ajax within_cart_item "Product 3" do click_on "Remove" end wait_for_ajax expect(page).to have_text("Discounts product1_and_2_offer_code US$-5", normalize_ws: true) check_out(product1) purchase1 = Purchase.last expect(purchase1.offer_code).to eq(product1_and_2_offer_code) expect(purchase1.price_cents).to eq(500) expect(purchase1.link).to eq(product1) end end context "discount does not apply to other products" do before do product1_and_2_offer_code end it "removes the discount" do visit product1.long_url add_to_cart(product1) fill_in "Discount code", with: "product1_and_2_offer_code" click_on "Apply" expect(page).to have_text("Discounts product1_and_2_offer_code US$-5", normalize_ws: true) visit product2.long_url add_to_cart(product2) expect(page).to have_text("Discounts product1_and_2_offer_code US$-15", normalize_ws: true) visit product3.long_url add_to_cart(product3) expect(page).to have_text("Discounts product1_and_2_offer_code US$-15", normalize_ws: true) within_cart_item "Product 1" do click_on "Remove" end wait_for_ajax within_cart_item "Product 2" do click_on "Remove" end wait_for_ajax expect(page).not_to have_text("Discounts product1_and_2_offer_code", normalize_ws: true) expect(page).to_not have_field("Discount code") check_out(product3) purchase3 = Purchase.last expect(purchase3.offer_code).to be_nil expect(purchase3.price_cents).to eq(3000) expect(purchase3.link).to eq(product3) end end end describe "100% discount with tipping" do let(:seller) { create(:user, display_offer_code_field: true, tipping_enabled: true) } let!(:product) { create(:product, user: seller, name: "Free with code", price_cents: 1000) } let!(:offer_code) { create(:percentage_offer_code, user: seller, products: [product], amount_percentage: 100, code: "FREE100") } it "does not show tip selector and allows checkout without tip when price is $0" do visit product.long_url add_to_cart(product) fill_in "Discount code", with: "FREE100" click_on "Apply" expect(page).to have_selector("[aria-label='Discount code']", text: "FREE100") expect(page).not_to have_text("Add a tip") check_out(product, is_free: true) purchase = Purchase.last expect(purchase.offer_code).to eq(offer_code) expect(purchase.price_cents).to eq(0) expect(purchase.tip).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/checkout/currencies_spec.rb
spec/requests/checkout/currencies_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Checkout currency conversions", :js, type: :system do before do $currency_namespace = Redis::Namespace.new(:currencies, redis: $redis) $currency_namespace.set("GBP", 5.1651) @product = create(:product, price_cents: 2300, price_currency_type: "gbp") end it "correctly converts to USD at checkout" do visit "/l/#{@product.unique_permalink}" add_to_cart(@product) within "[role=listitem]" do expect(page).to have_text("US$4.45") end check_out(@product) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/checkout/discounts_spec.rb
spec/requests/checkout/discounts_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" require "shared_examples/creator_dashboard_page" describe("Checkout discounts page", type: :system, js: true) do include CurrencyHelper let(:seller) { create(:named_seller) } let(:product1) { create(:product, name: "Product 1", user: seller, price_cents: 1000, price_currency_type: Currency::EUR) } let(:product2) { create(:product, name: "Product 2", user: seller, price_cents: 500) } let(:membership) { create(:membership_product_with_preset_tiered_pricing, name: "Membership", user: seller) } let!(:offer_code1) { create(:percentage_offer_code, name: "Discount 1", code: "code1", products: [product1, product2, membership], 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: 5, 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) } before do 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 include_context "with switching account to user as admin for seller" it_behaves_like "creator dashboard page", "Checkout" do let(:path) { checkout_discounts_path } end describe "discounts table" do before do offer_code1.products += build_list(:product, 2, user: seller, price_cents: 1000) do |product, i| product.update!(name: "Product #{i + 3}") end end it "displays all offer codes correctly" do visit checkout_discounts_path within find(:table_row, { "Discount" => "Discount 1", "Revenue" => "$123.30", "Uses" => "10/12", "Term" => "Jan 1, #{Time.current.year - 1} - Feb 1, #{Time.current.year - 1}", "Status" => "Expired" }) do expect(page).to have_text("50% off of Product 1, Product 2, and 3 others") expect(page).to have_selector("[aria-label='Offer code']", text: "CODE1") end within find(:table_row, { "Discount" => "Discount 2", "Revenue" => "$25", "Uses" => "5/20", "Term" => "Jan 1, #{Time.current.year + 1} - No end date", "Status" => "Scheduled" }) do expect(page).to have_text("$2 off of Product 2") expect(page).to have_selector("[aria-label='Offer code']", text: "CODE2") end within find(:table_row, { "Discount" => "Discount 3", "Revenue" => "$15", "Uses" => "2/∞", "Term" => "No end date", "Status" => "Live" }) do expect(page).to have_text("50% off of all products") expect(page).to have_selector("[aria-label='Offer code']", text: "CODE3") end end it "displays offer code drawers" do visit checkout_discounts_path find(:table_row, { "Discount" => "Discount 1" }).click within_modal "Discount 1" do within_section "Details" do expect(page).to have_text("Code CODE1", normalize_ws: true) expect(page).to have_text("Discount 50%", normalize_ws: true) expect(page).to have_text("Uses 10/12", normalize_ws: true) expect(page).to have_text("Revenue $123.30", normalize_ws: true) expect(page).to have_text("Start date Jan 1, #{Time.current.year - 1}, 12 AM", normalize_ws: true) expect(page).to have_text("End date Feb 1, #{Time.current.year - 1}, 12 AM", normalize_ws: true) expect(page).to have_text("Minimum quantity 5", normalize_ws: true) expect(page).to have_text("Discount duration for memberships Once (first billing period only)", normalize_ws: true) expect(page).to have_text("Minimum amount $10", normalize_ws: true) end within_section "Products" do expect(page).to have_text("Product 1 10 uses", normalize_ws: true) expect(page).to have_text("Product 2 0 uses", normalize_ws: true) expect(page).to have_text("Product 3 0 uses", normalize_ws: true) expect(page).to have_text("Product 4 0 uses", normalize_ws: true) expect(page).to have_button("Copy link", count: 5) end expect(page).to have_button("Duplicate") expect(page).to have_button("Edit") expect(page).to have_button("Delete") end find(:table_row, { "Discount" => "Discount 2" }).click within_modal "Discount 2" do within_section "Details" do expect(page).to have_text("Code CODE2", normalize_ws: true) expect(page).to have_text("Discount $2", normalize_ws: true) expect(page).to have_text("Uses 5/20", normalize_ws: true) expect(page).to have_text("Revenue $25", normalize_ws: true) expect(page).to have_text("Start date Jan 1, #{Time.current.year + 1}, 12 AM", normalize_ws: true) expect(page).to_not have_text("End date") expect(page).to_not have_text("Minimum quantity") expect(page).to_not have_text("Discount duration for memberships") expect(page).to_not have_text("Minimum amount") end within_section "Products" do expect(page).to have_text("Product 2 5 uses", normalize_ws: true) expect(page).to have_button("Copy link") end expect(page).to have_button("Duplicate") expect(page).to have_button("Edit") expect(page).to have_button("Delete") end find(:table_row, { "Discount" => "Discount 3" }).click within_modal "Discount 3" do within_section "Details" do expect(page).to have_text("Code CODE3", normalize_ws: true) expect(page).to have_text("Discount 50%", normalize_ws: true) expect(page).to have_text("Uses 2/∞", normalize_ws: true) expect(page).to have_text("Revenue $15", normalize_ws: true) expect(page).to have_text("Discount duration for memberships Forever", normalize_ws: true) expect(page).to_not have_text("Start date") expect(page).to_not have_text("End date") expect(page).to_not have_text("Minimum quantity") expect(page).to_not have_text("Minimum amount") end expect(page).to_not have_section("Products") expect(page).to have_button("Duplicate") expect(page).to have_button("Edit") expect(page).to have_button("Delete") end end context "when the creator has no discounts" do it "displays a placeholder message" do login_as create(:user) visit checkout_discounts_path expect(page).to have_text("No discounts yet") expect(page).to have_text("Use discounts to create sweet deals for your customers") end end end describe "creating offer codes" do describe "percentage offer code" do it "creates the offer code" do visit checkout_discounts_path click_on "New discount" fill_in "Name", with: "Black Friday" code = find_field("Discount code").value click_on "Generate new discount" new_code = find_field("Discount code").value expect(new_code).to_not eq(code) check "All products" fill_in "Percentage", with: "10" check "Limit quantity" fill_in "Quantity", with: "10" check "Limit validity period" fill_in_datetime "Valid from", with: "2022-11-02T23:00" check "Set a minimum quantity" fill_in "Minimum quantity per product", with: "1" select "Once (first billing period only)", from: "Discount duration for memberships" check "Set a minimum qualifying amount" fill_in "Minimum amount", with: "10" click_on "Add discount" expect(page).to have_alert(text: "Successfully created discount!") within find(:table_row, { "Discount" => "Black Friday", "Revenue" => "$0", "Uses" => "0/10" }) do expect(page).to have_text("10% off of all products") expect(page).to have_selector("[aria-label='Offer code']", text: new_code.upcase) end visit checkout_discounts_path within find(:table_row, { "Discount" => "Black Friday", "Revenue" => "$0", "Uses" => "0/10" }) do expect(page).to have_text("10% off of all products") expect(page).to have_selector("[aria-label='Offer code']", text: new_code.upcase) end offer_code = OfferCode.last expect(offer_code.name).to eq("Black Friday") expect(offer_code.code).to eq(new_code) expect(offer_code.currency_type).to eq(nil) expect(offer_code.amount_percentage).to eq(10) expect(offer_code.amount_cents).to eq(nil) expect(offer_code.max_purchase_count).to eq(10) expect(offer_code.universal).to eq(true) expect(offer_code.valid_at).to eq(ActiveSupport::TimeZone[seller.timezone].local(2022, 11, 2, 23)) expect(offer_code.expires_at).to eq(nil) expect(offer_code.minimum_quantity).to eq(1) expect(offer_code.duration_in_billing_cycles).to eq(1) expect(offer_code.minimum_amount_cents).to eq(1000) end context "when the selected products have different currency types" do it "doesn't allow switching to fixed amount" do create(:product, name: "Product 3", user: seller, price_currency_type: "gbp") visit checkout_discounts_path click_on "New discount" find(:label, "Products").click select_combo_box_option "Product 1", from: "Products" select_combo_box_option "Product 3", from: "Products" fixed_amount_field = find_field("Fixed amount", disabled: true, match: :first) fixed_amount_field.hover expect(fixed_amount_field).to have_tooltip(text: "To select a fixed amount, make sure the selected products are priced in the same currency.") end end context "when a product is archived" do before { product1.update!(archived: true) } it "doens't include the product in the product list" do visit checkout_discounts_path click_on "New discount" find(:label, "Products").click expect(page).to have_combo_box "Products", options: ["Product 2", "Membership"] end end end describe "absolute offer code" do it "creates the offer code" do visit checkout_discounts_path click_on "New discount" fill_in "Name", with: "Black Friday" code = "code" fill_in "Discount code", with: code check "All products" choose "Fixed amount" fill_in "Fixed amount", with: "10" check "Limit validity period" fill_in_datetime "Valid from", with: "2022-11-02T23:00" uncheck "No end date" fill_in_datetime "Valid until", with: "2022-12-02T23:00" click_on "Add discount" expect(page).to have_alert(text: "Successfully created discount!") within find(:table_row, { "Discount" => "Black Friday", "Revenue" => "$0", "Uses" => "0/∞" }) do expect(page).to have_text("€10 off of all products") expect(page).to have_selector("[aria-label='Offer code']", text: code.upcase) end visit checkout_discounts_path within find(:table_row, { "Discount" => "Black Friday", "Revenue" => "$0", "Uses" => "0/∞" }) do expect(page).to have_text("€10 off of all products") expect(page).to have_selector("[aria-label='Offer code']", text: code.upcase) end offer_code = OfferCode.last expect(offer_code.name).to eq("Black Friday") expect(offer_code.code).to eq(code) expect(offer_code.currency_type).to eq("eur") expect(offer_code.amount_cents).to eq(1000) expect(offer_code.amount_percentage).to eq(nil) expect(offer_code.max_purchase_count).to eq(nil) expect(offer_code.universal).to eq(true) expect(offer_code.valid_at).to eq(ActiveSupport::TimeZone[seller.timezone].local(2022, 11, 2, 23)) expect(offer_code.expires_at).to eq(ActiveSupport::TimeZone[seller.timezone].local(2022, 12, 2, 23)) expect(offer_code.minimum_quantity).to eq(nil) expect(offer_code.duration_in_billing_cycles).to eq(nil) expect(offer_code.minimum_amount_cents).to eq(nil) end context "when the offer code has multiple products" do it "creates the offer code" do visit checkout_discounts_path click_on "New discount" fill_in "Name", with: "Black Friday" code = "code" fill_in "Discount code", with: code fill_in "Percentage", with: "10" select_combo_box_option search: "Product 1", from: "Products" select_combo_box_option search: "Product 2", from: "Products" click_on "Add discount" within find(:table_row, { "Discount" => "Black Friday", "Revenue" => "$0", "Uses" => "0/∞" }) do expect(page).to have_text("10% off of Product 1, Product 2") expect(page).to have_selector("[aria-label='Offer code']", text: code.upcase) end expect(page).to have_modal "Black Friday" visit checkout_discounts_path within find(:table_row, { "Discount" => "Black Friday", "Revenue" => "$0", "Uses" => "0/∞" }) do expect(page).to have_text("10% off of Product 1, Product 2") expect(page).to have_selector("[aria-label='Offer code']", text: code.upcase) end offer_code = OfferCode.last expect(offer_code.name).to eq("Black Friday") expect(offer_code.code).to eq(code) expect(offer_code.currency_type).to eq(nil) expect(offer_code.amount_percentage).to eq(10) expect(offer_code.amount_cents).to eq(nil) expect(offer_code.max_purchase_count).to eq(nil) expect(offer_code.universal).to eq(false) expect(offer_code.products).to eq([product1, product2]) expect(offer_code.valid_at).to eq(nil) expect(offer_code.expires_at).to eq(nil) expect(offer_code.minimum_quantity).to eq(nil) expect(offer_code.duration_in_billing_cycles).to eq(nil) expect(offer_code.minimum_amount_cents).to eq(nil) end it "only allows the selection of products with the same currency" do create(:product, name: "Product 3", user: seller, price_currency_type: "gbp") visit checkout_discounts_path click_on "New discount" choose "Fixed amount" find(:label, "Products").click expect(page).to have_combo_box "Products", options: ["Product 1", "Product 2", "Membership", "Product 3"] select_combo_box_option "Product 1", from: "Products" find(:label, "Products").click expect(page).to have_combo_box "Products", options: ["Product 2", "Membership", "Product 3"] click_on "Product 1" select_combo_box_option "Product 3", from: "Products" find(:label, "Products").click expect(page).to have_combo_box "Products", options: ["Product 1", "Membership"] end end context "when the offer code is universal" do it "allows the selection of a currency type" do create(:product, name: "Product 3", user: seller, price_currency_type: "gbp") visit checkout_discounts_path click_on "New discount" fill_in "Name", with: "Discount" check "All products" choose "Fixed amount" select "£", from: "Currency", visible: false fill_in "Fixed amount", with: "1" click_on "Add discount" expect(page).to have_alert(text: "Successfully created discount!") within_modal "Discount" do click_on "Edit" end expect(page).to have_select("Currency", selected: "£", visible: false) expect(OfferCode.last.currency_type).to eq("gbp") end end context "when the offer code's code is taken" do before do create(:offer_code, user: seller, code: "code") end it "displays an error message" do visit checkout_discounts_path click_on "New discount" fill_in "Name", with: "Black Friday" check "All products" fill_in "Percentage", with: "100" fill_in "Discount code", with: "code" click_on "Add discount" expect(page).to have_alert(text: "Discount code must be unique.") end end context "when required fields aren't filled" do it "displays error statuses" do visit checkout_discounts_path click_on "New discount" fill_in "Discount code", with: "" fill_in "Percentage", with: "" click_on "Add discount" expect(find_field("Name")["aria-invalid"]).to eq("true") expect(find_field("Discount code")["aria-invalid"]).to eq("true") expect(find_field("Percentage", type: "text")["aria-invalid"]).to eq("true") end end context "when the offer code would discount the product below its currency's minimum but above 0" do it "displays an error message" do visit checkout_discounts_path click_on "New discount" fill_in "Name", with: "Black Friday" choose "Fixed amount" fill_in "Fixed amount", with: "9.50" select_combo_box_option search: "Product 1", from: "Products" click_on "Add discount" expect(page).to have_alert(text: "The price after discount for all of your products must be either €0 or at least €0.79.") end end context "when the offer code's expiration date is before its validity date" do it "displays an error status" do visit checkout_discounts_path click_on "New discount" check "Limit validity period" fill_in_datetime "Valid from", with: "2022-12-02T23:00" uncheck "No end date" fill_in_datetime "Valid until", with: "2022-11-02T23:00" click_on "Add discount" expect(find_field("Valid until")["aria-invalid"]).to eq("true") end end end context "when the offer code applies to a membership" do it "displays the duration select" do visit checkout_discounts_path click_on "New discount" check "All products" expect(page).to have_select("Discount duration for memberships", options: ["Once (first billing period only)", "Forever"], selected: "Forever") uncheck "All products" expect(page).to_not have_select("Discount duration for memberships") find(:label, "Products").click select_combo_box_option "Membership", from: "Products" expect(page).to have_select("Discount duration for memberships", options: ["Once (first billing period only)", "Forever"], selected: "Forever") end end end describe "editing offer codes" do it "updates the offer code" do # Allows us to test editing an offer code that already has `valid_at` # set with fewer date picker interactions offer_code2.update!(valid_at: Time.current) visit checkout_discounts_path table_row = find(:table_row, { "Discount" => "Discount 2" }) within table_row do click_on "Edit" end expect(page).to have_section("Edit discount") click_on "Cancel" table_row.click within_modal "Discount 2" do click_on "Edit" end expect(page).to have_field("Name", with: "Discount 2") expect(page).to have_field("Discount code", with: "code2") expect(page).to have_checked_field("Fixed amount") expect(page).to have_field("Fixed amount", with: "2") expect(page).to have_unchecked_field("All products") find("label", text: "Products").click expect(page).to have_combo_box("Products", options: ["Membership"]) expect(page).to have_checked_field("Limit quantity") expect(page).to have_field("Quantity", with: "20") expect(page).to have_field("Valid from", with: offer_code2.valid_at.in_time_zone(seller.timezone).iso8601[0..15]) expect(page).to have_checked_field("No end date") expect(page).to_not have_select("Discount duration for memberships") fill_in "Name", with: "Black Friday" check "All products" choose "Percentage" fill_in "Percentage", with: "10" check "Limit quantity" fill_in "Quantity", with: "10" check "Set a minimum qualifying amount" fill_in "Minimum amount", with: "5" fill_in_datetime "Valid from", with: "2022-11-02T23:00" uncheck "No end date" fill_in_datetime "Valid until", with: "2022-12-02T23:00" click_on "Save changes" expect(page).to have_alert(text: "Successfully updated discount!") within find(:table_row, { "Discount" => "Black Friday", "Revenue" => "$25", "Uses" => "5/10" }) do expect(page).to have_text("10% off of all products") expect(page).to have_selector("[aria-label='Offer code']", text: "CODE2") end visit checkout_discounts_path within find(:table_row, { "Discount" => "Black Friday", "Revenue" => "$25", "Uses" => "5/10" }) do expect(page).to have_text("10% off of all products") expect(page).to have_selector("[aria-label='Offer code']", text: "CODE2") end offer_code2.reload expect(offer_code2.name).to eq("Black Friday") expect(offer_code2.code).to eq("code2") expect(offer_code2.currency_type).to eq(nil) expect(offer_code2.amount_percentage).to eq(10) expect(offer_code2.amount_cents).to eq(nil) expect(offer_code2.max_purchase_count).to eq(10) expect(offer_code2.universal).to eq(true) expect(offer_code2.valid_at).to eq(ActiveSupport::TimeZone[seller.timezone].local(2022, 11, 2, 23)) expect(offer_code2.expires_at).to eq(ActiveSupport::TimeZone[seller.timezone].local(2022, 12, 2, 23)) expect(offer_code2.duration_in_billing_cycles).to eq(nil) expect(offer_code2.minimum_amount_cents).to eq(500) end context "when the offer code has multiple products" do let!(:product3) { create(:product, name: "Product 3", user: seller, price_cents: 2000) } it "updates the offer code" do visit checkout_discounts_path find(:table_row, { "Discount" => "Discount 1" }).click within_modal "Discount 1" do click_on "Edit" end fill_in "Name", with: "Black Friday" choose "Percentage" fill_in "Percentage", with: "10" click_on "Product 2" select_combo_box_option search: "Product 3", from: "Products" uncheck "Limit quantity" uncheck "Limit validity period" uncheck "Set a minimum qualifying amount" expect(page).to have_checked_field("Set a minimum quantity") expect(page).to have_field("Minimum quantity per product", with: "5") uncheck "Set a minimum quantity" expect(page).to have_select("Discount duration for memberships", options: ["Once (first billing period only)", "Forever"], selected: "Once (first billing period only)") select "Forever", from: "Discount duration for memberships" click_on "Save changes" within find(:table_row, { "Discount" => "Black Friday", "Revenue" => "$123.30", "Uses" => "10/∞" }) do expect(page).to have_text("10% off of Product 1, Membership, and 1 other") expect(page).to have_selector("[aria-label='Offer code']", text: "CODE1") end expect(page).to have_modal "Black Friday" visit checkout_discounts_path within find(:table_row, { "Discount" => "Black Friday", "Revenue" => "$123.30", "Uses" => "10/∞" }) do expect(page).to have_text("10% off of Product 1, Membership, and 1 other") expect(page).to have_selector("[aria-label='Offer code']", text: "CODE1") end offer_code1.reload expect(offer_code1.name).to eq("Black Friday") expect(offer_code1.code).to eq("code1") expect(offer_code1.currency_type).to eq(nil) expect(offer_code1.amount_percentage).to eq(10) expect(offer_code1.amount_cents).to eq(nil) expect(offer_code1.max_purchase_count).to eq(nil) expect(offer_code1.universal).to eq(false) expect(offer_code1.products).to eq([product1, membership, product3]) expect(offer_code1.valid_at).to eq(nil) expect(offer_code1.expires_at).to eq(nil) expect(offer_code1.minimum_quantity).to eq(nil) expect(offer_code1.duration_in_billing_cycles).to eq(nil) expect(offer_code1.minimum_amount_cents).to eq(nil) end end context "when required fields aren't filled" do it "displays error statuses" do visit checkout_discounts_path find(:table_row, { "Discount" => "Discount 1" }).click within_modal "Discount 1" do click_on "Edit" end fill_in "Name", with: "" within find(:fieldset, "Products") do click_on "Clear value" end fill_in "Percentage", with: "" fill_in "Quantity", with: "" fill_in "Minimum quantity per product", with: "" fill_in "Minimum amount", with: "" click_on "Save changes" expect(find_field("Name")["aria-invalid"]).to eq("true") expect(find_field("Percentage", type: "text")["aria-invalid"]).to eq("true") expect(find_field("Products")["aria-invalid"]).to eq("true") expect(find_field("All products")["aria-invalid"]).to eq("true") expect(find_field("Quantity")["aria-invalid"]).to eq("true") expect(find_field("Minimum quantity per product")["aria-invalid"]).to eq("true") expect(find_field("Minimum amount")["aria-invalid"]).to eq("true") end end context "when the offer code would discount the product below its currency's minimum but above 0" do it "displays an error message" do visit checkout_discounts_path find(:table_row, { "Discount" => "Discount 1" }).click within_modal "Discount 1" do click_on "Edit" end fill_in "Name", with: "Black Friday" choose "Percentage" fill_in "Percentage", with: "95" click_on "Save changes" expect(page).to have_alert(text: "The price after discount for all of your products must be either €0 or at least €0.79.") end end context "when a selected product is archived" do before do product1.update!(archived: true) end it "preserves the archived product on save" do visit checkout_discounts_path find(:table_row, { "Discount" => "Discount 1" }).click within_modal "Discount 1" do click_on "Edit" end find(:label, "Products").click expect(page).to have_combo_box "Products", options: ["Product 1", "Product 2", "Membership"] click_on "Save changes" expect(offer_code1.reload.products).to eq([product1, product2, membership]) end end end it "deletes the offer code" do visit checkout_discounts_path within find(:table_row, { "Discount" => "Discount 1" }) do select_disclosure "Open discount action menu" do click_on "Delete" end end expect(page).to have_alert(text: "Successfully deleted discount!") expect(page).to_not have_selector(:table_row, { "Discount" => "Discount 1" }) find(:table_row, { "Discount" => "Discount 2" }).click within_modal "Discount 2" do click_on "Delete" end expect(page).to have_alert(text: "Successfully deleted discount!") expect(page).to_not have_selector(:table_row, { "Discount" => "Discount 2" }) visit checkout_discounts_path expect(page).to_not have_selector(:table_row, { "Discount" => "Discount 1" }) expect(page).to_not have_selector(:table_row, { "Discount" => "Discount 2" }) expect(offer_code1.reload.deleted_at).to be_present expect(offer_code2.reload.deleted_at).to be_present end it "duplicates the offer code" do visit checkout_discounts_path table_row = find(:table_row, { "Discount" => "Discount 1" }) within table_row do select_disclosure "Open discount action menu" do click_on "Duplicate" end end expect(page).to have_section("Create discount") click_on "Cancel" table_row.click within_modal "Discount 1" do click_on "Duplicate" end code = find_field("Discount code").value expect(page).to have_section("Create discount") expect(page).to have_field("Name", with: "Discount 1") expect(page).to have_checked_field("Percentage") expect(page).to have_field("Percentage", with: "50") expect(page).to have_unchecked_field("All products") find("label", text: "Products").click expect(page).to have_combo_box("Products", options: ["Product 1", "Product 2"]) find("body").native.send_key("escape") # to dismiss the combo box so the limit quantity checkbox is visible expect(page).to have_checked_field("Limit quantity") expect(page).to have_field("Quantity", with: "12") expect(page).to have_field("Valid from", with: "#{Time.current.year - 1}-01-01T00:00") expect(page).to have_unchecked_field("No end date") expect(page).to have_field("Valid until", with: "#{Time.current.year - 1}-02-01T00:00") expect(page).to have_checked_field("Set a minimum quantity") expect(page).to have_field("Minimum quantity per product", with: "5") expect(page).to have_checked_field("Set a minimum qualifying amount") expect(page).to have_field("Minimum amount", with: "10") check "Limit quantity" fill_in "Quantity", with: "5" fill_in "Name", with: "Discount 1 Duplicate" click_on "Add discount" expect(page).to have_alert(text: "Successfully created discount!") expect(page).to have_selector(:table_row, { "Discount" => "Discount 1 Duplicate" }) offer_code = OfferCode.last expect(offer_code.name).to eq("Discount 1 Duplicate") expect(offer_code.code).to eq(code) expect(offer_code.currency_type).to eq(nil) expect(offer_code.amount_percentage).to eq(50) expect(offer_code.amount_cents).to eq(nil) expect(offer_code.max_purchase_count).to eq(5) expect(offer_code.universal).to eq(false) expect(offer_code.products).to eq([product1, product2, membership]) expect(offer_code.valid_at).to eq(offer_code1.valid_at) expect(offer_code.expires_at).to eq(offer_code1.expires_at) end describe "pagination" do before do stub_const("Checkout::DiscountsController::PER_PAGE", 1) end it "paginates the offer codes" do visit checkout_discounts_path expect(page).to have_button("Previous", disabled: true) expect(page).to have_button("Next") expect(page).to have_selector(:table_row, { "Discount" => "Discount 1" }) click_on "2" expect(page).to have_button("Previous") expect(page).to have_button("Next") expect(page).to have_current_path(checkout_discounts_path({ page: 2 })) expect(page).to have_selector(:table_row, { "Discount" => "Discount 2" }) click_on "3" expect(page).to have_button("Previous") expect(page).to have_button("Next", disabled: true) expect(page).to have_current_path(checkout_discounts_path({ page: 3 })) expect(page).to have_selector(:table_row, { "Discount" => "Discount 3" }) end end describe "sorting" do before do build_list(:offer_code, 3, user: seller, universal: true) do |offer_code, i| offer_code.update!(name: "Discount #{i + 3}", code: "discount#{i + 3}", valid_at: i.days.ago, updated_at: i.days.ago) end stub_const("Checkout::DiscountsController::PER_PAGE", 2) end it "sorts the offer codes" do visit checkout_discounts_path find(:columnheader, "Discount").click
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/checkout/payment_spec.rb
spec/requests/checkout/payment_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Checkout payment", :js, type: :system do before do @product = create(:product, price_cents: 1000) Feature.deactivate(:disable_braintree_sales) end it "shows native, braintree, or no paypal button depending on availability" do create(:merchant_account_paypal, user: @product.user, charge_processor_merchant_id: "CJS32DZ7NDN5L", currency: "gbp") visit "/l/#{@product.unique_permalink}" add_to_cart(@product) select_tab "PayPal" expect(page).to have_selector("iframe[title=PayPal]") product2 = create(:product, price_cents: 1000) visit "/l/#{product2.unique_permalink}" add_to_cart(product2) select_tab "PayPal" expect(page).to_not have_selector("iframe[title=PayPal]") expect(page).to have_button "Pay" product3 = create(:product, price_cents: 1000) product3.user.update!(disable_paypal_sales: true) visit "/l/#{product3.unique_permalink}" add_to_cart(product3) expect(page).to_not have_tab_button "PayPal" end context "email typo suggestions" do before { Feature.activate(:require_email_typo_acknowledgment) } it "disables the payment button until typo suggestion is resolved" do visit @product.long_url add_to_cart(@product) expect(page).to have_button "Pay", disabled: false fill_in "Email address", with: "hi@gnail.com" unfocus expect(page).to have_text "Did you mean hi@gmail.com?" expect(page).to have_button "Pay", disabled: true # Rejecting the typo suggestion does NOT update the field value. within_fieldset "Email address" do click_on "No" end expect(page).to have_field("Email address", with: "hi@gnail.com") expect(page).to have_button "Pay", disabled: false fill_in "Email address", with: "hi@hotnail.com" unfocus expect(page).to have_text "Did you mean hi@hotmail.com?" expect(page).to have_button "Pay", disabled: true # Accepting the typo suggestion updates the field value. within_fieldset "Email address" do click_on "Yes" end expect(page).to have_field("Email address", with: "hi@hotmail.com") expect(page).to have_button "Pay", disabled: false # Re-entering a typo that has been acknowledged should not show # suggestions again. fill_in "Email address", with: "hi@gnail.com" unfocus expect(page).to_not have_text "Did you mean" expect(page).to have_button "Pay", disabled: false end context "feature flag is off" do before { Feature.deactivate(:require_email_typo_acknowledgment) } it "does not block the payment button" do visit @product.long_url add_to_cart(@product) expect(page).to have_button "Pay", disabled: false fill_in "Email address", with: "hi@gnail.com" unfocus expect(page).to have_text "Did you mean hi@gmail.com?" expect(page).to have_button "Pay", disabled: 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/products/collabs_mobile_spec.rb
spec/requests/products/collabs_mobile_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Collabs - Mobile", type: :system, js: true, mobile_view: true do let(:seller) { create(:named_seller) } before do login_as(seller) end it "shows Sales and Revenue labels in the collab products table footer" do create(:product, :is_collab, user: seller) visit(products_collabs_path) footer_rows = page.all("tfoot tr") within(footer_rows.first) do expect(page).to have_text("Totals") expect(page).to have_text("Sales 0", normalize_ws: true) expect(page).to have_text("Revenue $0", normalize_ws: true) end end it "shows Members and Revenue labels in the collab memberships table footer" do create(:subscription_product, :is_collab, user: seller) visit(products_collabs_path) footer_rows = page.all("tfoot tr") within(footer_rows.first) do expect(page).to have_text("Totals") expect(page).to have_text("Members 0", normalize_ws: true) expect(page).to have_text("Revenue $0", 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/products/mobile_tracking_spec.rb
spec/requests/products/mobile_tracking_spec.rb
# frozen_string_literal: true describe "Mobile tracking", type: :system, js: true do let(:product) { create(:product) } before do allow_any_instance_of(UsersHelper).to receive(:is_third_party_analytics_enabled?).and_return(true) end it "adds global functions the apps can call to track product events" do visit link_mobile_tracking_path(product.unique_permalink) expect(page.evaluate_script("typeof window.tracking.ctaClick")).to eq("function") expect(page.evaluate_script("typeof window.tracking.productPurchase")).to eq("function") end context "when the product has product third-party analytics" do before do create(:third_party_analytic, user: product.user, link: product, location: "product") end it "loads the third-party analytics iframe" do visit link_mobile_tracking_path(product.unique_permalink) expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{product.unique_permalink}']", visible: false) end end context "when the product has receipt third-party analytics" do before do create(:third_party_analytic, user: product.user, link: product, location: "receipt") end it "loads the third-party analytics iframe after purchase" do visit link_mobile_tracking_path(product.unique_permalink) expect(page).not_to have_selector("iframe", visible: false) page.execute_script("window.tracking.productPurchase({permalink: 'test', currency_type: 'usd'})") expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='test']", visible: false) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/dropbox_spec.rb
spec/requests/products/dropbox_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Dropbox uploads", type: :system, js: true do include ProductEditPageHelpers let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } include_context "with switching account to user as admin for seller" before do visit edit_link_path(product.unique_permalink) + "/content" end it "embeds dropbox files successfully" do select_disclosure "Upload files" do pick_dropbox_file("/db_upload_testing/Download-Card.pdf") end select_disclosure "Upload files" do pick_dropbox_file("/db_upload_testing/SmallTestFile") end %w(Download-Card SmallTestFile).each do |file_name| expect(page).to have_embed(name: file_name) wait_for_file_embed_to_finish_uploading(name: file_name) end sleep 0.5 # wait for the editor to update the content save_change expect(product.reload.alive_product_files.count).to eq 2 expect(product.alive_product_files.first.display_name).to eq("Download-Card") expect(product.alive_product_files.last.display_name).to eq("SmallTestFile") expected_content = product.alive_product_files.map do |file| { "type" => "fileEmbed", "attrs" => { "id" => file.external_id, "uid" => anything, "collapsed" => false } } end expected_content << { "type" => "paragraph" } expect(product.alive_rich_contents.sole.description).to match_array(expected_content) end it "allows to change dropbox file's name and description while the file is uploading" do select_disclosure "Upload files" do pick_dropbox_file("/db_upload_testing/Download-Card.pdf") end # Make sure the file row remains in "uploading" state while we edit the name and description allow_any_instance_of(DropboxFilesController).to receive(:index) toggle_disclosure "Upload files" within find_embed(name: "Download-Card") do click_on "Edit" fill_in "Name", with: "Greeting-Card" fill_in "Description", with: "This is a fancy greeting card!" end allow_any_instance_of(DropboxFilesController).to receive(:index).and_call_original wait_for_file_embed_to_finish_uploading(name: "Greeting-Card") sleep 0.5 # wait for the editor to update the content save_change product.reload uploaded_file = product.alive_product_files.sole expect(uploaded_file.display_name).to eq "Greeting-Card" expect(uploaded_file.description).to eq "This is a fancy greeting card!" expect(product.alive_rich_contents.sole.description).to match_array([ { "type" => "fileEmbed", "attrs" => { "id" => uploaded_file.external_id, "uid" => anything, "collapsed" => false } }, { "type" => "paragraph" } ]) end it "allows users to cancel dropbox uploads" do select_disclosure "Upload files" do pick_dropbox_file("/db_upload_testing/Download-Card.pdf", true) end select_disclosure "Upload files" do pick_dropbox_file("/db_upload_testing/GumroadCreatorFAQ.pdf") end expect(page).to have_embed(name: "Download-Card") expect(page).to have_embed(name: "GumroadCreatorFAQ") wait_for_file_embed_to_finish_uploading(name: "GumroadCreatorFAQ") toggle_disclosure "Upload files" within find_embed(name: "Download-Card") do click_on "Cancel" end sleep 0.5 # wait for the editor to update the content save_change expect(page).to have_embed(name: "GumroadCreatorFAQ") expect(page).not_to have_embed(name: "Download-Card") expect(product.user.dropbox_files.count).to eq 2 successful_dropbox_file = product.user.dropbox_files.reload.where(state: "successfully_uploaded").first expect(successful_dropbox_file.product_file).to eq product.alive_product_files.last expect(successful_dropbox_file.link).to eq product expect(successful_dropbox_file.json_data["file_name"]).to eq "GumroadCreatorFAQ.pdf" expect(successful_dropbox_file.s3_url).not_to be_nil cancelled_db_file = product.user.dropbox_files.reload.where.not(state: "successfully_uploaded").first expect(cancelled_db_file.product_file).to be_nil expect(cancelled_db_file.json_data["file_name"]).to eq "Download-Card.pdf" expect(product.alive_product_files.count).to eq 1 expect(product.alive_rich_contents.sole.description).to match_array([ { "type" => "fileEmbed", "attrs" => { "id" => successful_dropbox_file.product_file.external_id, "uid" => anything, "collapsed" => false } }, { "type" => "paragraph" } ]) end it "allows users to remove dropbox uploads" do select_disclosure "Upload files" do pick_dropbox_file("/db_upload_testing/Download-Card.pdf") end select_disclosure "Upload files" do pick_dropbox_file("/db_upload_testing/GumroadCreatorFAQ.pdf") end expect(page).to have_embed(name: "Download-Card") wait_for_file_embed_to_finish_uploading(name: "Download-Card") expect(page).to have_embed(name: "GumroadCreatorFAQ") wait_for_file_embed_to_finish_uploading(name: "GumroadCreatorFAQ") toggle_disclosure "Upload files" within find_embed(name: "Download-Card") do page.click select_disclosure "Actions" do click_on "Delete" end end sleep 0.5 # wait for the editor to update the content save_change expect(page).to have_embed(name: "GumroadCreatorFAQ") expect(page).not_to have_embed(name: "Download-Card") expect(product.user.dropbox_files.count).to eq 2 successful_dropbox_file = product.user.dropbox_files.last expect(successful_dropbox_file.product_file).to eq product.alive_product_files.last expect(successful_dropbox_file.link).to eq product expect(successful_dropbox_file.json_data["file_name"]).to eq "GumroadCreatorFAQ.pdf" removed_db_file = product.user.dropbox_files.first expect(removed_db_file.product_file).to be_nil expect(removed_db_file.json_data["file_name"]).to eq "Download-Card.pdf" expect(product.alive_product_files.count).to eq 1 expect(product.alive_rich_contents.sole.description).to match_array([ { "type" => "fileEmbed", "attrs" => { "id" => successful_dropbox_file.product_file.external_id, "uid" => anything, "collapsed" => false } }, { "type" => "paragraph" } ]) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/creation_spec.rb
spec/requests/products/creation_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Product creation", type: :system, js: true do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } let(:user_with_admin_role) { create(:user, name: "Admin") } include_context "with switching account to user as admin for seller" describe "native types" do it "selects 'digital' by default" do visit new_product_path fill_in("Name", with: "Default digital native type") fill_in("Price", with: 1) click_on("Next: Customize") expect(page).to have_title("Default digital native type") expect(page).to have_text("Add details") expect(seller.products.last.native_type).to eq(Link::NATIVE_TYPE_DIGITAL) end it "creates a digital product" do visit new_product_path fill_in("Name", with: "Digital product native type") choose("Digital product") fill_in("Price", with: 1) click_on("Next: Customize") expect(page).to have_title("Digital product native type") expect(page).to have_text("Add details") product = seller.links.last expect(product.native_type).to eq("digital") expect(product.is_physical).to be(false) expect(product.is_recurring_billing).to be(false) expect(product.is_in_preorder_state).to be(false) expect(product.subscription_duration).to be_nil expect(product.custom_attributes).to eq([]) expect(product.should_include_last_post).to be_falsey end it "creates a course product" do visit new_product_path fill_in("Name", with: "Course product native type") choose("Course or tutorial") fill_in("Price", with: 1) click_on("Next: Customize") expect(page).to have_title("Course product native type") expect(page).to have_text("Add details") product = seller.links.last expect(product.native_type).to eq("course") expect(product.is_physical).to be(false) expect(product.is_recurring_billing).to be(false) expect(product.is_in_preorder_state).to be(false) expect(product.subscription_duration).to be_nil expect(product.custom_attributes).to eq([]) expect(product.should_include_last_post).to be_falsey end it "creates a ebook product" do visit new_product_path fill_in("Name", with: "Ebook product native type") choose("E-book") fill_in("Price", with: 1) click_on("Next: Customize") expect(page).to have_title("Ebook product native type") expect(page).to have_selector("input[value='Pages']") product = seller.links.last expect(product.native_type).to eq("ebook") expect(product.is_physical).to be(false) expect(product.is_recurring_billing).to be(false) expect(product.is_in_preorder_state).to be(false) expect(product.subscription_duration).to be_nil expect(product.custom_attributes).to eq([{ "name" => "Pages", "value" => "" }]) expect(product.should_include_last_post).to be_falsey end it "creates a membership product" do visit new_product_path fill_in("Name", with: "membership product native type") choose("Membership") expect(page).to have_content("a month") select("every 6 months", from: "Default subscription duration", visible: false) fill_in("Price", with: 1) click_on("Next: Customize") expect(page).to have_title("membership product native type") expect(page).to have_text("Add details") expect(page).to have_checked_field("New members will be emailed this product's last published post") expect(page).to have_checked_field("New members will get access to all posts you have published") product = seller.links.last expect(product.native_type).to eq("membership") expect(product.is_physical).to be(false) expect(product.is_recurring_billing).to be(true) expect(product.is_in_preorder_state).to be(false) expect(product.subscription_duration).to eq("biannually") expect(product.custom_attributes).to eq([]) expect(product.should_include_last_post).to be_truthy end context "physical products are disabled" do it "does not allow the creation of a physical product" do visit new_product_path expect(page).to_not have_radio_button("Physical good") end end context "physical products are enabled" do before { seller.update!(can_create_physical_products: true) } it "creates an physical product" do visit new_product_path fill_in("Name", with: "physical product native type") choose("Physical good") fill_in("Price", with: 1) click_on("Next: Customize") expect(page).to have_title("physical product native type") product = seller.links.last expect(product.native_type).to eq("physical") expect(product.is_physical).to be(true) expect(product.is_recurring_billing).to be(false) expect(product.is_in_preorder_state).to be(false) expect(product.subscription_duration).to be_nil expect(product.should_include_last_post).to be_falsey end end context "commissions are disabled" do it "does not allow the creation of a commission product" do visit new_product_path expect(page).to_not have_radio_button("Commission") end end context "commissions are enabled" do before { Feature.activate(:commissions) } context "seller is not eligible for service products" do it "does not allow the creation of a service product" do visit new_product_path commission_button = find(:radio_button, "Commission", disabled: true) commission_button.hover expect(commission_button).to have_tooltip(text: "Service products are disabled until your account is 30 days old.") end end context "seller is eligible for service products" do let(:seller) { create(:user, :eligible_for_service_products) } it "creates a commission product" do visit new_product_path choose "Commission" fill_in "Name", with: "My commission" fill_in "Price", with: "2" click_on "Next: Customize" expect(page).to have_title("My commission") product = seller.products.last expect(product.native_type).to eq("commission") expect(product.is_physical).to be(false) expect(product.is_recurring_billing).to be(false) expect(product.is_in_preorder_state).to be(false) expect(product.subscription_duration).to be_nil expect(product.custom_attributes).to eq([]) expect(product.should_include_last_post).to be_falsey end end end end context "user can create multiple products in one session" do it "creates multiple products" do visit new_product_path fill_in("Name", with: "My First product") choose("Digital product") fill_in("Price", with: 1) click_on("Next: Customize") expect(page).to have_title("My First product") expect(page).to have_text("Add details") product = seller.links.last expect(product.name).to eq("My First product") page.go_back fill_in("Name", with: "My Second product") choose("Digital product") fill_in("Price", with: 1) click_on("Next: Customize") expect(page).to have_title("My Second product") expect(page).to have_text("Add details") product = seller.links.last expect(product.name).to eq("My Second product") # Verify both products appear on the products list visit products_path expect(page).to have_content("My First product") expect(page).to have_content("My Second product") end end context "seller is not eligible for service products" do it "does not allow the creation of a coffee product" do visit new_product_path coffee_button = find(:radio_button, "Coffee", disabled: true) coffee_button.hover expect(coffee_button).to have_tooltip(text: "Service products are disabled until your account is 30 days old.") end it "does not allow the creation of a service product" do visit new_product_path call_button = find(:radio_button, "Call", disabled: true) call_button.hover expect(call_button).to have_tooltip(text: "Service products are disabled until your account is 30 days old.") end end context "seller is eligible for service products" do let(:seller) { create(:user, :eligible_for_service_products) } before do Feature.activate(:product_edit_react) end it "creates a coffee product" do visit new_product_path choose "Coffee" fill_in "Name", with: "My coffee" fill_in "Suggested amount", with: "1" click_on "Next: Customize" expect(page).to have_title("My coffee") product = seller.products.last expect(product.native_type).to eq("coffee") expect(product.is_physical).to be(false) expect(product.is_recurring_billing).to be(false) expect(product.is_in_preorder_state).to be(false) expect(product.subscription_duration).to be_nil expect(product.custom_attributes).to eq([]) expect(product.should_include_last_post).to be_falsey end it "creates a call product" do visit new_product_path choose "Call" fill_in "Name", with: "My call" fill_in "Price", with: "1" click_on "Next: Customize" expect(page).to have_title("My call") product = seller.products.last expect(product.native_type).to eq("call") expect(product.is_physical).to be(false) expect(product.is_recurring_billing).to be(false) expect(product.is_in_preorder_state).to be(false) expect(product.subscription_duration).to be_nil expect(product.custom_attributes).to eq([]) expect(product.should_include_last_post).to be_falsey end end describe "currencies" do it "creates a membership priced in a single-unit currency" do visit new_product_path fill_in("Name", with: "membership in yen") choose("Membership") select("¥ (Yen)", from: "Currency", visible: false) fill_in("Price", with: 5000) click_on("Next: Customize") expect(page).to have_title("membership in yen") product = seller.links.last tier_price = product.default_tier.prices.alive.first expect(product.price_currency_type).to eq("jpy") expect(tier_price.currency).to eq("jpy") expect(tier_price.price_cents).to eq(5000) end it "creates a digital product priced in a single-unit currency" do visit new_product_path fill_in("Name", with: "Digital product in yen") choose("Digital product") select("¥ (Yen)", from: "Currency", visible: false) fill_in("Price", with: 5000) click_on("Next: Customize") expect(page).to have_title("Digital product in yen") product = seller.links.last price = product.prices.alive.first expect(product.price_currency_type).to eq("jpy") expect(product.price_cents).to eq(5000) expect(price.currency).to eq("jpy") expect(price.price_cents).to eq(5000) end end describe "form validations" do it "focuses on name field on submit if name is not filled" do visit new_product_path fill_in("Price", with: 1) click_on("Next: Customize") name_field = find_field("Name") expect(page.active_element).to eq(name_field) expect(name_field.ancestor("fieldset.danger")).to be_truthy end it "focuses on price field on submit if price is not filled" do visit new_product_path fill_in("Name", with: "Digital product") choose("Digital product") click_on("Next: Customize") price_field = find_field("Price") expect(page.active_element).to eq(price_field) expect(price_field.ancestor("fieldset.danger")).to be_truthy end end describe "bundles" do it "allows the creation of a bundle" do visit new_product_path choose "Bundle" fill_in("Name", with: "Bundle") fill_in("Price", with: 1) click_on("Next: Customize") expect(page).to have_title("Bundle") product = Link.last expect(product.is_bundle).to eq(true) expect(product.native_type).to eq("bundle") end end it "does not automatically enable the community chat on creating a product" do Feature.activate_user(:communities, seller) visit new_product_path choose "Digital product" fill_in "Name", with: "My product" fill_in "Price", with: 1 click_on "Next: Customize" wait_for_ajax expect(page).not_to have_checked_field("Invite your customers to your Gumroad community chat") product = seller.products.last expect(product.community_chat_enabled?).to be(false) expect(product.active_community).to be_nil end describe "AI Product Generation" do before do Feature.activate_user(:ai_product_generation, seller) allow_any_instance_of(User).to receive(:eligible_for_ai_product_generation?).and_return(true) end it "creates a product using AI prompt and customizes it" do vcr_turned_on do VCR.use_cassette("Product creation using AI") do visit new_product_path expect(page).to have_status(text: "New. You can create your product using AI now") click_on "Create a product with AI" fill_in "Create a product with AI", with: "Create a Ruby on Rails coding tutorial ebook with 4 chapters for $29.99" click_on "Generate" wait_for_ajax expect(page).to have_alert(text: "All set! Review the form below and hit 'Next: customize' to continue.") expect(page).to have_field("Name", with: "Ruby on Rails Coding Tutorial") expect(page).to have_radio_button("E-book", checked: true) expect(page).to have_field("Price", with: "29.99") click_on "Next: Customize" wait_for_ajax expect(page).to have_title("Ruby on Rails Coding Tutorial") expect(page).to have_status(text: "Your AI product is ready! Take a moment to check out the product and content tabs. Tweak things and make it your own—this is your time to shine!") within find("[aria-label='Description']") do expect(page).to have_text("Welcome to the Ruby on Rails Coding Tutorial ebook! This comprehensive guide is designed for both beginners and experienced developers who want to master the Ruby on Rails framework.") end product = seller.products.last within_section "Cover", section_element: :section do expect(page).to have_image(src: product.display_asset_previews.sole.url) end within_section "Thumbnail", section_element: :section do expect(page).to have_image("Thumbnail image", src: product.thumbnail.url) end within_fieldset "Additional details" do inputs = all("input[type='text']") expect(inputs[0].value).to eq("Pages") expect(inputs[1].value).to eq("4") end within_section "Pricing", section_element: :section do expect(page).to have_field("Amount", with: "29.99") end select_tab "Content" expect(page).to have_text("Chapter 1: Introduction to Ruby on Rails") expect(page).to have_text("Chapter 2: Setting Up Your Development Environment") expect(page).to have_text("Chapter 3: Building Your First Rails Application") expect(page).to have_text("Chapter 4: Advanced Features and Best Practices") within find("[aria-label='Content editor']") do expect(page).to have_text("What is Ruby on Rails?") expect(page).to have_text("Key Features of Ruby on Rails") expect(page).to have_text("In this chapter, we will delve deeper into the history of Ruby on Rails and its community.") 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/products/index_mobile_spec.rb
spec/requests/products/index_mobile_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Products Page Scenario - Mobile", type: :system, js: true, mobile_view: true do let(:seller) { create(:named_seller) } before do login_as(seller) end it "shows Sales and Revenue labels in the products table footer" do create(:product, user: seller) visit(products_path) footer_rows = page.all("tfoot tr") within(footer_rows.first) do expect(page).to have_text("Totals") expect(page).to have_text("Sales 0", normalize_ws: true) expect(page).to have_text("Revenue $0", normalize_ws: true) end end it "shows Members and Revenue labels in the memberships table footer" do create(:subscription_product, user: seller) visit(products_path) footer_rows = page.all("tfoot tr") within(footer_rows.first) do expect(page).to have_text("Totals") expect(page).to have_text("Members 0", normalize_ws: true) expect(page).to have_text("Revenue $0", 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/products/affiliated_products_spec.rb
spec/requests/products/affiliated_products_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" require "shared_examples/products_navigation" describe "Affiliated Products", type: :system, js: true do let(:affiliate_user) { create(:affiliate_user) } include_context "with switching account to user as admin for seller" do let(:seller) { affiliate_user } end it_behaves_like "tab navigation on products page" do let(:url) { products_affiliated_index_path } end shared_examples "accesses global affiliates page" do it "provides details about the program" do visit products_affiliated_index_path expect(page).to have_tab_button("Affiliated", open: true) click_on "Gumroad affiliate" expect(page).to have_content "Gumroad Affiliates" expect(page).to have_content "Affiliate link" expect(page).to have_content "Affiliate link generator" expect(page).to have_content "How to know if a product is eligible" end end context "when the user has affiliated products" do let(:creator) { create(:named_user) } let(:creator_products) { create_list(:product, 10, user: creator, price_cents: 1000) } let(:affiliate_one_products) { creator_products.shuffle.first(3) } let(:affiliate_two_products) { (creator_products - affiliate_one_products).shuffle.first(2) } let(:affiliate_three_products) { (creator_products - affiliate_one_products - affiliate_two_products) } # ensure global affiliate products appear first for testing purposes by explicitly setting affiliate creation dates let(:direct_affiliate) { create(:direct_affiliate, affiliate_user:, seller: creator, affiliate_basis_points: 2500, created_at: 3.days.ago) } let(:global_affiliate) { affiliate_user.global_affiliate } before do affiliate_one_products.each do |product| create(:product_affiliate, affiliate: direct_affiliate, product:, affiliate_basis_points: 25_00) end affiliate_two_products.each do |product| create(:product_affiliate, affiliate: direct_affiliate, product:, affiliate_basis_points: 5_00) end create(:product_affiliate, affiliate: direct_affiliate, product: affiliate_three_products.first, affiliate_basis_points: 20_00) purchases = [] purchases << create(:purchase_in_progress, seller: creator, link: affiliate_one_products.first, affiliate: global_affiliate) purchases << create(:purchase_in_progress, seller: creator, link: affiliate_one_products.first, affiliate: direct_affiliate) 2.times do purchases << create(:purchase_in_progress, seller: creator, link: affiliate_two_products.first, affiliate: direct_affiliate) end 4.times do purchases << create(:purchase_in_progress, seller: creator, link: affiliate_three_products.first, affiliate: direct_affiliate) end purchases.each do |purchase| purchase.process! purchase.update_balance_and_mark_successful! end end it "displays stats about affiliated products and sales and correct table rows data" do visit products_affiliated_index_path within "[aria-label='Stats']" do within_section "Revenue" do expect(page).to have_content "9.86" end within_section "Sales" do expect(page).to have_content 8 end within_section "Products" do expect(page).to have_content 6 end within_section "Affiliated creators" do expect(page).to have_content 1 end end within "table" do expect(page).to have_selector(:table_row, { "Product" => affiliate_one_products.first.name, "Sales" => "1", "Type" => "Gumroad", "Commission" => "10%", "Revenue" => "$0.79" }) expect(page).to have_selector(:table_row, { "Product" => affiliate_one_products.first.name, "Sales" => "1", "Type" => "Direct", "Commission" => "25%", "Revenue" => "$1.97" }) expect(page).to have_selector(:table_row, { "Product" => affiliate_one_products.second.name, "Sales" => "0", "Type" => "Direct", "Commission" => "25%", "Revenue" => "$0" }) expect(page).to have_selector(:table_row, { "Product" => affiliate_one_products.third.name, "Sales" => "0", "Type" => "Direct", "Commission" => "25%", "Revenue" => "$0" }) expect(page).to have_selector(:table_row, { "Product" => affiliate_two_products.first.name, "Sales" => "2", "Type" => "Direct", "Commission" => "5%", "Revenue" => "$0.78" }) expect(page).to have_selector(:table_row, { "Product" => affiliate_two_products.second.name, "Sales" => "0", "Type" => "Direct", "Commission" => "5%", "Revenue" => "$0" }) expect(page).to have_selector(:table_row, { "Product" => affiliate_three_products.first.name, "Sales" => "4", "Type" => "Direct", "Commission" => "20%", "Revenue" => "$6.32" }) end end context "pagination" do before { stub_const("AffiliatedProductsPresenter::PER_PAGE", 5) } it "returns paginated affiliated products" do affiliate_three_products[1..].each do |product| create(:product_affiliate, affiliate: direct_affiliate, product:, affiliate_basis_points: 2000) end visit products_affiliated_index_path expect(page).to have_selector("table > tbody > tr", count: 5) click_on "2" expect(page).to have_selector("table > tbody > tr", count: 5) click_on "3" expect(page).to have_selector("table > tbody > tr", count: 1) expect(page).not_to have_selector("button", text: "4") end it "sets the page to 1 on sort" do visit products_affiliated_index_path within find("[aria-label='Pagination']") do expect(find_button("1")["aria-current"]).to eq("page") click_on "2" wait_for_ajax expect(find_button("1")["aria-current"]).to be_nil expect(find_button("2")["aria-current"]).to eq("page") end find(:columnheader, "Revenue").click wait_for_ajax within find("[aria-label='Pagination']") do expect(find_button("1")["aria-current"]).to eq("page") expect(find_button("2")["aria-current"]).to be_nil end end end it "supports searching affiliated products" do visit products_affiliated_index_path new_product = create(:product, user: creator, name: "A very unique product name") create(:product_affiliate, affiliate: direct_affiliate, product: new_product, affiliate_basis_points: 25_00) select_disclosure "Search" do fill_in "Search", with: new_product.name end expect(page).to have_selector("table > tbody > tr", count: 1) within "table" do expect(page).to have_selector(:table_row, { "Product" => new_product.name, "Sales" => "0", "Type" => "Direct", "Commission" => "25%", "Revenue" => "$0" }) end fill_in "Search", with: "" expect(page).to have_selector("table > tbody > tr", count: 8) end it "sorts affiliated products by column" do visit products_affiliated_index_path expect(page).to have_nth_table_row_record(1, affiliate_three_products.first.name) expect(page).to have_nth_table_row_record(2, affiliate_two_products.first.name) expect(page).to have_nth_table_row_record(3, affiliate_one_products.first.name) find(:columnheader, "Product").click expect(page).to have_nth_table_row_record(1, affiliate_one_products.first.name) expect(page).to have_nth_table_row_record(2, affiliate_two_products.first.name) expect(page).to have_nth_table_row_record(3, affiliate_three_products.first.name) find(:columnheader, "Sales").click expect(page).to have_nth_table_row_record(1, affiliate_three_products.first.name) expect(page).to have_nth_table_row_record(2, affiliate_two_products.first.name) expect(page).to have_nth_table_row_record(3, affiliate_one_products.first.name) find(:columnheader, "Sales").click expect(page).to have_nth_table_row_record(1, affiliate_one_products.first.name) expect(page).to have_nth_table_row_record(2, affiliate_two_products.first.name) expect(page).to have_nth_table_row_record(3, affiliate_three_products.first.name) find(:columnheader, "Commission").click expect(page).to have_nth_table_row_record(1, affiliate_one_products.first.name) expect(page).to have_nth_table_row_record(2, affiliate_two_products.first.name) expect(page).to have_nth_table_row_record(3, affiliate_three_products.first.name) find(:columnheader, "Commission").click expect(page).to have_nth_table_row_record(1, affiliate_three_products.first.name) expect(page).to have_nth_table_row_record(2, affiliate_two_products.first.name) expect(page).to have_nth_table_row_record(3, affiliate_one_products.first.name) find(:columnheader, "Revenue").click expect(page).to have_nth_table_row_record(1, affiliate_one_products.first.name) expect(page).to have_nth_table_row_record(2, affiliate_two_products.first.name) expect(page).to have_nth_table_row_record(3, affiliate_three_products.first.name) find(:columnheader, "Revenue").click expect(page).to have_nth_table_row_record(1, affiliate_three_products.first.name) expect(page).to have_nth_table_row_record(2, affiliate_two_products.first.name) expect(page).to have_nth_table_row_record(3, affiliate_one_products.first.name) end it "copies the affiliated product link" do visit products_affiliated_index_path within first("table > tbody > tr") do click_on "Copy link" end expect(page).to have_text("Copied!") end it "allows opening the product on clicking product's title" do visit products_affiliated_index_path find(:columnheader, "Revenue").click find(:columnheader, "Revenue").click product = affiliate_three_products.first within find(:table_row, { "Product" => product.name }, match: :first) do expect(page).to have_link(product.name, href: direct_affiliate.referral_url_for_product(product)) end end it "allows opening product on clicking product's title based on the destination URL setting" do # When Destination URL is set direct_affiliate.update!(destination_url: "https://gumroad.com", apply_to_all_products: true) product = affiliate_three_products.first # Set unique product name to avoid flakiness product.update!(name: "Beautiful banner") visit products_affiliated_index_path find(:columnheader, "Revenue").click find(:columnheader, "Revenue").click within find(:table_row, { "Product" => "Beautiful banner" }) do new_window = window_opened_by { click_link product.name } within_window new_window do expect(page).to have_current_path("https://gumroad.com?affiliate_id=#{direct_affiliate.external_id_numeric}") end end # When Destination URL is not set direct_affiliate.update!(destination_url: nil) refresh within find(:table_row, { "Product" => "Beautiful banner" }) do new_window = window_opened_by { click_link product.name } within_window new_window do expect(page).to have_current_path(product.long_url) end end end it "displays products with global affiliate sales by the user" do visit products_affiliated_index_path within find(:table_row, { "Product" => affiliate_one_products.first.name, "Type" => "Gumroad" }) do expect(page).to have_selector(:table_cell, "Sales", text: "1") end end it_behaves_like "accesses global affiliates page" end context "viewing global affiliates" do let!(:affiliate) { affiliate_user.global_affiliate } it "displays the user's global affiliate link" do visit products_affiliated_index_path(affiliates: true) expect(page).to have_content "Gumroad Affiliates" expect(page).to have_content "#{UrlService.discover_domain_with_protocol}/discover?a=#{affiliate.external_id_numeric}" end it "displays the amount earned as an affiliate" do create_list(:purchase, 2, affiliate:, price_cents: 10_00) # 10% commission * 1 purchases @ $10 - 10% of gumroad fee = $1.58 in affiliate commission visit products_affiliated_index_path(affiliates: true) expect(page).to have_content "To date, you have made $1.58 from Gumroad referrals." end context "generating links" do it "appends the affiliate query param to a valid Gumroad URL" do visit products_affiliated_index_path(affiliates: true) [ { original: "https://#{DISCOVER_DOMAIN}", expected: "https://#{DISCOVER_DOMAIN}/?a=#{affiliate.external_id_numeric}" }, { original: "https://#{DOMAIN}/l/x", expected: "https://#{DOMAIN}/l/x?a=#{affiliate.external_id_numeric}" }, { original: "https://edgar.#{ROOT_DOMAIN}", expected: "https://edgar.#{ROOT_DOMAIN}/?a=#{affiliate.external_id_numeric}" }, { original: "https://#{ROOT_DOMAIN}?foo=bar", expected: "https://#{ROOT_DOMAIN}/?foo=bar&a=#{affiliate.external_id_numeric}" }, { original: "https://#{ROOT_DOMAIN}?a=#{affiliate.external_id_numeric}", expected: "https://#{ROOT_DOMAIN}/?a=#{affiliate.external_id_numeric}" }, { original: "https://#{SHORT_DOMAIN}/x", expected: "https://#{SHORT_DOMAIN}/x?a=#{affiliate.external_id_numeric}" }, ].each do |urls| fill_in "Paste a destination page URL", with: urls[:original] click_on "Generate link" expect(page).to have_content urls[:expected] end end it "returns an error for an invalid or non-Gumroad URL" do visit products_affiliated_index_path(affiliates: true) [ROOT_DOMAIN, "https://example.com"].each do |url| fill_in "Paste a destination page URL", with: url click_on "Generate link" expect_alert_message("Invalid URL. Make sure your URL is a Gumroad URL and starts with \"http\" or \"https\".") end end end describe "checking product eligibility", :realistic_error_responses do context "searching by product URL" do it "displays product eligibility for a valid, eligible Gumroad URL" do product = create(:product, :recommendable) product_with_custom_permalink = create(:product, :recommendable, name: "Custom Permalink", custom_permalink: "foo") visit products_affiliated_index_path(affiliates: true) [ product.long_url, "#{PROTOCOL}://#{ROOT_DOMAIN}/l/#{product.unique_permalink}", "#{PROTOCOL}://#{SHORT_DOMAIN}/#{product.unique_permalink}", "#{PROTOCOL}://#{DOMAIN}/l/#{product.unique_permalink}", ].each do |valid_url| fill_in "Paste a product URL", with: "#{valid_url}\n" expect(page).not_to have_selector("[role=alert]") expect(page).to have_link product.name, href: "#{product.long_url}?a=#{affiliate.external_id_numeric}" end fill_in "Paste a product URL", with: "#{product_with_custom_permalink.long_url}\n" expect(page).not_to have_selector("[role=alert]") expect(page).to have_link product_with_custom_permalink.name, href: "#{product_with_custom_permalink.long_url}?a=#{affiliate.external_id_numeric}" end it "displays a warning for an invalid URL" do product = create(:product, :recommendable) visit products_affiliated_index_path(affiliates: true) [ { url: "", message: "URL must be provided" }, { url: "#{PROTOCOL}://#{ROOT_DOMAIN}/l/foo", message: "Please provide a valid Gumroad product URL" }, { url: "#{PROTOCOL}://example.com/l/#{product.unique_permalink}", message: "Please provide a valid Gumroad product URL" }, ].each do |invalid_option| fill_in "Paste a product URL", with: "#{invalid_option[:url]}\n" wait_for_ajax expect_alert_message(invalid_option[:message]) end end it "displays a warning for an ineligible product" do product = create(:product) visit products_affiliated_index_path(affiliates: true) fill_in "Paste a product URL", with: "#{product.long_url}\n" wait_for_ajax expect_alert_message("This product is not eligible for the Gumroad Affiliate Program.") 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/products/collabs_spec.rb
spec/requests/products/collabs_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" require "shared_examples/products_navigation" require "shared_examples/with_sorting_and_pagination" describe "Collabs", type: :system, js: true do let(:user) { create(:user) } include_context "with switching account to user as admin for seller" do let(:seller) { user } end it_behaves_like "tab navigation on products page" do let(:url) { products_collabs_path } end context "when the user has collabs" do # User is a collaborator for two other sellers let(:seller_1) { create(:user) } let(:seller_1_collaborator) { create(:collaborator, seller: seller_1, affiliate_user: user) } let(:seller_2) { create(:user) } let(:seller_2_collaborator) { create(:collaborator, seller: seller_2, affiliate_user: user) } # Products # 1. Owned by user let!(:collab_1) { create(:product, :is_collab, user:, price_cents: 10_00, collaborator_cut: 30_00, created_at: 1.month.ago) } let!(:membership_collab_1) { create(:membership_product_with_preset_tiered_pricing, :is_collab, name: "My membership", user:, collaborator_cut: 50_00, created_at: 2.months.ago) } # 2. Owned by others let!(:collab_2) { create(:product, :is_collab, user: seller_1, price_cents: 20_00, collaborator_cut: 25_00, collaborator: seller_1_collaborator, created_at: 3.months.ago) } let!(:collab_3) { create(:product, :is_collab, user: seller_2, collaborator_cut: 50_00, collaborator: seller_2_collaborator, created_at: 4.months.ago) } # no purchases let!(:membership_collab_2) { create(:membership_product_with_preset_tiered_pricing, :is_collab, user: seller_2, collaborator_cut: 25_00, collaborator: seller_2_collaborator, created_at: 5.months.ago) } # Purchases let!(:collab_1_purchase_1) { create(:purchase_in_progress, seller: user, link: collab_1, affiliate: collab_1.collaborator) } let!(:collab_1_purchase_2) { create(:purchase_in_progress, seller: user, link: collab_1, affiliate: collab_1.collaborator) } let!(:collab_1_purchase_3) { create(:purchase_in_progress, seller: user, link: collab_1, affiliate: collab_1.collaborator) } let!(:collab_2_purchase_1) { create(:purchase_in_progress, seller: seller_1, link: collab_2, affiliate: collab_2.collaborator) } let!(:collab_2_purchase_2) { create(:purchase_in_progress, seller: seller_1, link: collab_2, affiliate: collab_2.collaborator) } let!(:membership_collab_1_purchase_1) do tier = membership_collab_1.tiers.first create(:membership_purchase, purchase_state: "in_progress", seller: user, link: membership_collab_1, price_cents: tier.prices.first.price_cents, # $3 affiliate: membership_collab_1.collaborator, tier:) end let!(:membership_collab_1_purchase_2) do tier = membership_collab_1.tiers.last create(:membership_purchase, purchase_state: "in_progress", seller: user, link: membership_collab_1, price_cents: tier.prices.first.price_cents, # $5 affiliate: membership_collab_1.collaborator, tier:) end let!(:membership_collab_2_purchase_1) do tier = membership_collab_2.tiers.last create(:membership_purchase, purchase_state: "in_progress", seller: seller_2, link: membership_collab_2, price_cents: tier.prices.first.price_cents, # $5 affiliate: membership_collab_2.collaborator, tier:) end before do [ collab_1_purchase_1, collab_1_purchase_2, collab_1_purchase_3, collab_2_purchase_1, collab_2_purchase_2, membership_collab_1_purchase_1, membership_collab_1_purchase_2, membership_collab_2_purchase_1, ].each do |p| p.process! p.update_balance_and_mark_successful! end index_model_records(Purchase) index_model_records(Link) index_model_records(Balance) end it "renders the correct stats and collab products", :sidekiq_inline, :elasticsearch_wait_for_refresh do visit(products_collabs_path) within "[aria-label='Stats']" do within_section "Total revenue" do # collab 1: $21 = 3 * (10_00 * (1 - 0.3)) # collab 2: $10 = 2 * $5 # membership collab 1: $4 = 1 * $1.50 + 1 * $2.50 # membership collab 2: $1.25 = 1 * $5 * 0.25 # TOTAL: $21 + $10 + $4 + $1.25 = $36.25 expect(page).to have_content "$36.25" end within_section "Customers" do expect(page).to have_content 5 end within_section "Active members" do expect(page).to have_content 3 end within_section "Collaborations" do expect(page).to have_content 5 end end expect(page).to have_table("Memberships", with_rows: [ { "Name" => membership_collab_1.name, "Price" => "$3+ a month", "Cut" => "50%", "Members" => "2", "Revenue" => "$4" }, { "Name" => membership_collab_2.name, "Price" => "$3+ a month", "Cut" => "25%", "Members" => "1", "Revenue" => "$1.25" }, ]) expect(page).to have_table("Products", with_rows: [ { "Name" => collab_1.name, "Price" => "$10", "Cut" => "70%", "Sales" => "3", "Revenue" => "$21" }, { "Name" => collab_2.name, "Price" => "$20", "Cut" => "25%", "Sales" => "2", "Revenue" => "$10" }, { "Name" => collab_3.name, "Price" => "$1", "Cut" => "50%", "Sales" => "0", "Revenue" => "$0" }, ]) within_table "Memberships" do within(:table_row, { "Name" => membership_collab_1.name }) do expect(page).to have_content "$4 /mo" end within(:table_row, { "Name" => membership_collab_2.name }) do expect(page).to have_content "$1.25 /mo" end end end # TODO (shan) Re-enable once server-side sorting properly works for all columns (may need additional tweaks) xdescribe "product sorting" do include_context "with products and memberships" it_behaves_like "a table with sorting", "Products" do before do visit(products_collabs_path) end let!(:default_order) { [collab_1, collab_2, collab_3] } let!(:columns) do { "Name" => [collab_1, collab_2, collab_3], "Price" => [collab_1, collab_2, collab_3], "Cut" => [collab_1, collab_2, collab_3], "Sales" => [collab_1, collab_2, collab_3], "Revenue" => [collab_1, collab_2, collab_3], } end end end xdescribe "membership sorting" do include_context "with products and memberships" it_behaves_like "a table with sorting", "Memberships" do before do visit(products_collabs_path) end let!(:default_order) { [collab_membership_1, collab_membership_2] } let!(:columns) do { "Name" => [collab_membership_1, collab_membership_2], "Price" => [collab_membership_1, collab_membership_2], "Cut" => [collab_membership_1, collab_membership_2], "Members" => [collab_membership_1, collab_membership_2], "Revenue" => [collab_membership_1, collab_membership_2], } end end end end context "when the user does not have collabs" do it "displays a placeholder message" do visit(products_collabs_path) expect(page).to have_text("Create your first collab!") expect(page).to have_link("Add a collab") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/index_spec.rb
spec/requests/products/index_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" require "shared_examples/products_navigation" require "shared_examples/with_sorting_and_pagination" describe "Products Page Scenario", type: :system, js: true do include ProductEditPageHelpers def find_product_row(product, hover: false) row = find(:table_row, { "Name" => product.name }) row.hover if hover row end let(:seller) { create(:named_seller) } include_context "with switching account to user as admin for seller" describe "navigation" do it_behaves_like "tab navigation on products page" do let(:url) { products_path } end it "navigates to filtered customers page when sales count is clicked" do product = create(:product, user: seller) visit(products_path) within find_product_row product do find(:table_cell, "Sales").find("a").click end expect(page).to have_section("Sales") select_disclosure "Filter" do expect(page).to have_button(product.name) end end context "product edit page" do it "navigates from title and description" do product = create(:product, user: seller) visit(products_path) within find_product_row(product) do click_on product.name end expect(page).to have_current_path(edit_link_path(product)) end end end describe "deletion" do it "deletes a membership" do membership = create(:subscription_product, user: seller) visit(products_path) within find_product_row membership do select_disclosure "Open product action menu" do click_on "Delete" end click_on "Cancel" end expect(page).not_to have_alert(text: "Product deleted!") within find_product_row membership do select_disclosure "Open product action menu" do click_on "Delete" end click_on "Confirm" end expect(page).to have_alert(text: "Product deleted!") end it "deletes a product" do product = create(:product, user: seller) visit(products_path) within find_product_row product do select_disclosure "Open product action menu" do click_on "Delete" end click_on "Cancel" end expect(page).not_to have_alert(text: "Product deleted!") within find_product_row product do select_disclosure "Open product action menu" do click_on "Delete" end click_on "Confirm" end expect(page).to have_alert(text: "Product deleted!") end it "disables the delete menuitem if the user isn't authorized" do expect_any_instance_of(LinkPolicy).to receive(:destroy?).and_return(false) product = create(:product, user: seller) visit products_path within find_product_row(product) do select_disclosure "Open product action menu" do expect(page).to have_menuitem("Delete", disabled: true) end end end end describe "duplication" do it "duplicates a membership" do membership = create(:subscription_product, user: seller) visit(products_path) within find_product_row membership do select_disclosure "Open product action menu" do click_on "Duplicate" end end wait_for_ajax # This is less flaky compared to using Sidekiq inline DuplicateProductWorker.new.perform(membership.id) expect(page).to have_content("#{membership.name} (copy)") end it "duplicates a product" do product = create(:product, user: seller) visit(products_path) within find_product_row product do select_disclosure "Open product action menu" do click_on "Duplicate" end end wait_for_ajax # This is less flaky compared to using Sidekiq inline DuplicateProductWorker.new.perform(product.id) expect(page).to have_content("#{product.name} (copy)") end it "shows loading state when creator requests to duplicate a product" do product = create(:product, user: seller) visit(products_path) within find_product_row product do select_disclosure "Open product action menu" do click_on "Duplicate" end expect(page).to have_menuitem("Duplicating...", disabled: true) end expect(page).to have_alert(text: "Duplicating the product. You will be notified once it's ready.") end it "shows loading state on page load when product is duplicating" do product = create(:product, user: seller, is_duplicating: true) visit(products_path) within find_product_row product do select_disclosure "Open product action menu" do click_on "Duplicate" end expect(page).to have_menuitem("Duplicating...", disabled: true) end end it "shows error flash message on request to duplicate a product that is still processing" do product = create(:product, user: seller, is_duplicating: true) visit(products_path) within find_product_row product do select_disclosure "Open product action menu" do click_on "Duplicate" end expect(page).to have_menuitem("Duplicating...", disabled: true) end expect(page).to have_alert(text: "Duplication in progress...") end it "shows error flash message when product duplication fails" do product = create(:product, user: seller) expect(seller.links.alive.count).to eq 1 allow_any_instance_of(ProductDuplicatorService).to receive(:duplicate_third_party_analytics).and_raise(RuntimeError) visit(products_path) expect do within find_product_row(product) do select_disclosure "Open product action menu" do click_on "Duplicate" end end expect(page).to have_alert(text: "Duplicating the product. You will be notified once it's ready.") end.to(change { Link.count }.by(0)) end it "succeeds if the product has buy and rental prices" do product = create(:product, user: seller, purchase_type: "buy_and_rent", price_cents: 500, rental_price_cents: 300) create(:price, link: product, price_cents: 300, is_rental: true) visit products_path within find_product_row(product) do select_disclosure "Open product action menu" do click_on "Duplicate" end end wait_for_ajax expect(DuplicateProductWorker).to have_enqueued_sidekiq_job(product.id) # Doing this manually instead of sidekiq inline to have better control over assertions/non flaky waits DuplicateProductWorker.new.perform(product.id) wait_for_ajax expect(page).to have_alert(text: "#{product.name} is duplicated") expect(page).to have_content("#{product.name} (copy)") duplicate_product = Link.last expect(duplicate_product.rental_price_cents).to eq 300 expect(duplicate_product.buy_price_cents).to eq 500 end it "duplicates the product-level rich content along with the file embeds" do product = create(:product, user: seller) product_file1 = create(:product_file, link: product) product_file2 = create(:readable_document, link: product) content = [ { "type" => "fileEmbed", "attrs" => { "id" => product_file1.external_id, "uid" => "product-file-1-uid" } }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Lorem ipsum" }] }, { "type" => "fileEmbed", "attrs" => { "id" => product_file2.external_id, "uid" => "product-file-2-uid" } }, ] create(:rich_content, entity: product, description: content) visit products_path within find_product_row(product) do select_disclosure "Open product action menu" do click_on "Duplicate" end end wait_for_ajax expect(DuplicateProductWorker).to have_enqueued_sidekiq_job(product.id) DuplicateProductWorker.new.perform(product.id) expect(page).to have_alert(text: "#{product.name} is duplicated") click_on "#{product.name} (copy)" select_tab "Content" expect(page).to have_text("Lorem ipsum") expect(page).to have_embed(name: product_file1.name_displayable) expect(page).to have_embed(name: product_file2.name_displayable) end it "duplicates the variant-level rich content along with the file embeds" do product = create(:product, user: seller) product_file1 = create(:product_file, link: product) product_file2 = create(:readable_document, link: product) category = create(:variant_category, link: product, title: "Versions") version1 = create(:variant, variant_category: category, name: "Version 1") version1.product_files << product_file1 version2 = create(:variant, variant_category: category, name: "Version 2") version2.product_files << product_file2 create(:rich_content, entity: version1, description: [ { "type" => "paragraph", "content" => [{ "text" => "This is Version 1 content", "type" => "text" }] }, { "type" => "fileEmbed", "attrs" => { "id" => product_file1.external_id, "uid" => "product-file-1-uid" } } ]) create(:rich_content, entity: version2, description: [ { "type" => "paragraph", "content" => [{ "text" => "This is Version 2 content", "type" => "text" }] }, { "type" => "fileEmbed", "attrs" => { "id" => product_file2.external_id, "uid" => "product-file-2-uid" } } ]) visit products_path within find_product_row(product) do select_disclosure "Open product action menu" do click_on "Duplicate" end end wait_for_ajax expect(DuplicateProductWorker).to have_enqueued_sidekiq_job(product.id) DuplicateProductWorker.new.perform(product.id) expect(page).to have_alert(text: "#{product.name} is duplicated") click_on "#{product.name} (copy)" select_tab "Content" expect(page).to have_combo_box("Select a version", text: "Editing: Version 1") expect(page).to have_text("This is Version 1 content") expect(page).to have_embed(name: product_file1.name_displayable) expect(page).to_not have_embed(name: product_file2.name_displayable) select_combo_box_option("Version 2", from: "Select a version") expect(page).to have_text("This is Version 2 content") expect(page).to_not have_embed(name: product_file1.name_displayable) expect(page).to have_embed(name: product_file2.name_displayable) end it "disables the duplicate menuitem if the user isn't authorized" do expect_any_instance_of(ProductDuplicates::LinkPolicy).to receive(:create?).and_return(false) product = create(:product, user: seller) visit products_path within find_product_row(product) do select_disclosure "Open product action menu" do expect(page).to have_menuitem("Duplicate", disabled: true) end end end end describe "actions popover" do it "is hidden if the use isn't authorized to delete or duplicate" do expect_any_instance_of(LinkPolicy).to receive(:destroy?).and_return(false) expect_any_instance_of(ProductDuplicates::LinkPolicy).to receive(:create?).and_return(false) product = create(:product, user: seller) visit products_path within find_product_row(product) do expect(page).to_not have_disclosure "Open product action menu" end end end describe "pagination" do before do stub_const("LinksController::PER_PAGE", 1) end it "paginates memberships" do membership1 = create(:membership_product, created_at: 3.days.ago, name: "Name 1", user: seller) membership2 = create(:membership_product, created_at: 2.days.ago, name: "Name 2", user: seller) membership3 = create(:membership_product, created_at: 1.day.ago, name: "Name 3", user: seller) visit products_path # Page 1 expect(page).to have_nth_table_row_record(1, membership3.name, exact_text: false) expect(page).not_to have_nth_table_row_record(1, membership2.name, exact_text: false) expect(page).not_to have_nth_table_row_record(1, membership1.name, exact_text: false) expect(page).to have_button("Previous", disabled: true) expect(page).to have_button("Next") expect(find_button("1")["aria-current"]).to eq("page") expect(find_button("2")["aria-current"]).to be_nil expect(find_button("3")["aria-current"]).to be_nil # Page 2 click_on "Next" wait_for_ajax expect(page).not_to have_nth_table_row_record(1, membership3.name, exact_text: false) expect(page).to have_nth_table_row_record(1, membership2.name, exact_text: false) expect(page).not_to have_nth_table_row_record(1, membership1.name, exact_text: false) expect(page).to have_button("Previous") expect(page).to have_button("Next") expect(find_button("1")["aria-current"]).to be_nil expect(find_button("2")["aria-current"]).to eq("page") expect(find_button("3")["aria-current"]).to be_nil # Page 3 click_on "3" wait_for_ajax expect(page).not_to have_nth_table_row_record(1, membership3.name, exact_text: false) expect(page).not_to have_nth_table_row_record(1, membership2.name, exact_text: false) expect(page).to have_nth_table_row_record(1, membership1.name, exact_text: false) expect(page).to have_button("Previous") expect(page).to have_button("Next", disabled: true) expect(find_button("1")["aria-current"]).to be_nil expect(find_button("2")["aria-current"]).to be_nil expect(find_button("3")["aria-current"]).to eq("page") end it "paginates products" do products = {} 15.times do |i| products[i] = create(:product, created_at: i.days.ago, name: "Name #{i}", user: seller) end visit products_path # Page 1 expect(page).to have_selector(:table_row, { "Name" => products[0].name }) expect(page).not_to have_selector(:table_row, { "Name" => products[1].name }) expect(page).not_to have_selector(:table_row, { "Name" => products[2].name }) expect(page).to have_button("1", exact: true) expect(page).to have_button("9", exact: true) expect(page).not_to have_button("10", exact: true) expect(page).to have_button("15", exact: true) # Page 2 click_on "Next" wait_for_ajax expect(page).to have_selector(:table_row, { "Name" => products[1].name }) # Page 15 click_on "15" wait_for_ajax expect(page).to have_selector(:table_row, { "Name" => products[14].name }) expect(page).to have_button("7", exact: true) expect(page).to have_button("15", exact: true) expect(page).not_to have_button("6", exact: true) expect(page).to have_button("1", exact: true) # Page 14 click_on "Previous" wait_for_ajax expect(page).to have_selector(:table_row, { "Name" => products[13].name }) # Page 7 click_on "7" wait_for_ajax expect(page).to have_selector(:table_row, { "Name" => products[6].name }) expect(page).to have_button("3", exact: true) expect(page).to have_button("10", exact: true) expect(page).not_to have_button("2", exact: true) expect(page).not_to have_button("11", exact: true) expect(page).to have_button("1", exact: true) expect(page).to have_button("15", exact: true) end end describe "product sorting" do include_context "with products and memberships" it_behaves_like "a table with sorting", "Products" do before do visit(products_path) end let!(:default_order) { [product1, product3, product4, product2] } let!(:columns) do { "Name" => [product1, product2, product3, product4], "Sales" => [product1, product2, product3, product4], } end let!(:boolean_columns) { { "Status" => [product3, product4, product1, product2] } } end end describe "membership sorting" do include_context "with products and memberships" it_behaves_like "a table with sorting", "Memberships" do before do visit(products_path) end let!(:default_order) { [membership2, membership3, membership4, membership1] } let!(:columns) do { "Name" => [membership1, membership2, membership3, membership4], "Members" => [membership4, membership1, membership3, membership2], } end let!(:boolean_columns) { { "Status" => [membership3, membership4, membership2, membership1] } } end end describe "searching" do before do per_page = 2 per_page.times do create(:product, user: seller, name: "Pig") end stub_const("LinksController::PER_PAGE", per_page) end it "shows the search results" do product = create(:product, user: seller, name: "Chicken", unique_permalink: "chicken") visit(products_path) expect(page).to have_field("Search products", visible: false) table = find(:table, "Products").find("tbody") expect(table).to have_selector(:table_row, count: 2) expect(page).to have_selector("[aria-label='Pagination']") select_disclosure "Toggle Search" do expect(page).to have_field("Search products") end fill_in "Search products", with: "Chicken" find_product_row product expect(table).to have_selector(:table_row, count: 1) expect(page).not_to have_selector("[aria-label='Pagination']") end it "duplicates a product" do product = create(:product, user: seller, name: "Test product") stub_const("LinksController::PER_PAGE", 1) visit(products_path) select_disclosure "Toggle Search" do fill_in "Search products", with: "product" end expect(page).to have_link(product.long_url, href: product.long_url) within find_product_row product do select_disclosure "Open product action menu" do click_on "Duplicate" end end expect(page).to have_alert(text: "Duplicating the product. You will be notified once it's ready.") end it "duplicates a membership" do membership = create(:subscription_product, user: seller, name: "Test membership") stub_const("LinksController::PER_PAGE", 1) visit(products_path) select_disclosure "Toggle Search" do fill_in "Search products", with: "membership" end expect(page).to have_link(membership.long_url, href: membership.long_url) within find_product_row membership do select_disclosure "Open product action menu" do click_on "Duplicate" end end expect(page).to have_alert(text: "Duplicating the product. You will be notified once it's ready.") end it "deletes a product" do product = create(:product, user: seller, name: "Test product") stub_const("LinksController::PER_PAGE", 1) visit(products_path) select_disclosure "Toggle Search" do fill_in "Search products", with: "product" end expect(page).to have_link(product.long_url, href: product.long_url) within find_product_row product do select_disclosure "Open product action menu" do click_on "Delete" end click_on "Confirm" end expect(page).to have_alert(text: "Product deleted!") end it "deletes a membership" do membership = create(:subscription_product, user: seller, name: "Test membership") stub_const("LinksController::PER_PAGE", 1) visit(products_path) select_disclosure "Toggle Search" do fill_in "Search products", with: "membership" end expect(page).to have_link(membership.long_url, href: membership.long_url) within find_product_row membership do select_disclosure "Open product action menu" do click_on "Delete" end click_on "Confirm" end expect(page).to have_alert(text: "Product deleted!") end end describe "dashboard stats" do before do @digital_product = create(:product, user: seller, price_cents: 10_00, name: "Product 1") create(:purchase, link: @digital_product) create(:purchase, link: @digital_product) create(:refunded_purchase, link: @digital_product) create(:purchase, link: @digital_product, purchase_state: "in_progress") @membership = create(:membership_product_with_preset_tiered_pricing, user: seller, name: "My membership") create(:membership_purchase, link: @membership, price_cents: 10_00, variant_attributes: [@membership.default_tier]) create(:membership_purchase, link: @membership, price_cents: 10_00, variant_attributes: [@membership.default_tier]) create(:membership_purchase, link: @membership, price_cents: 10_00, variant_attributes: [@membership.default_tier], purchase_state: "in_progress") cancelled_membership = create(:membership_purchase, link: @membership, price_cents: 10_00, variant_attributes: [@membership.default_tier]) cancelled_membership.subscription.update!(cancelled_at: 1.day.ago) index_model_records(Purchase) index_model_records(Link) end context "when data is not cached" do it "renders the correct stats" do expect do visit(products_path) end.to change { CacheProductDataWorker.jobs.size }.by(2) expect(page).to have_table("Memberships", with_rows: [ { "Name" => @membership.name, "Members" => "3", "Revenue" => "$30" } ]) expect(page).to have_table("Products", with_rows: [ { "Name" => @digital_product.name, "Sales" => "2", "Revenue" => "$20" } ]) end end context "when data is cached" do before do @digital_product.product_cached_values.create! @membership.product_cached_values.create! end it "renders the correct stats" do expect do visit(products_path) end.to_not change { CacheProductDataWorker.jobs.size } expect(page).to have_table("Memberships", with_rows: [ { "Name" => @membership.name, "Members" => "3", "Revenue" => "$30" } ]) expect(page).to have_table("Products", with_rows: [ { "Name" => @digital_product.name, "Sales" => "2", "Revenue" => "$20" } ]) end end end describe "Archiving" do it "archives a membership" do membership = create(:subscription_product, user: seller) visit(products_path) expect(page).not_to have_tab_button("Archived") within find_product_row membership do select_disclosure "Open product action menu" do click_on "Archive" end end expect(page).to have_tab_button("Archived") expect(page).not_to have_content(membership.name) find(:tab_button, "Archived").click expect(page).to have_content(membership.name) end it "archives and unpublishes a published product" do product = create(:product, user: seller) expect(product.purchase_disabled_at).to be_nil visit(products_path) expect(page).not_to have_tab_button("Archived") within find_product_row product do select_disclosure "Open product action menu" do click_on "Archive" end end expect(page).to have_alert(text: "Product was archived and unpublished successfully") expect(page).to have_tab_button("Archived") expect(page).not_to have_content(product.name) product.reload expect(product.archived?).to be(true) expect(product.purchase_disabled_at).to be_present find(:tab_button, "Archived").click within find_product_row product do expect(page).to have_content(product.name) expect(page).to have_text("Unpublished") end end it "archives an unpublished product" do product = create(:product, :unpublished, user: seller) visit(products_path) within find_product_row product do select_disclosure "Open product action menu" do click_on "Archive" end end expect(page).to have_alert(text: "Product was archived successfully") expect(product.reload.archived?).to be(true) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/third_party_analytics_spec.rb
spec/requests/products/third_party_analytics_spec.rb
# frozen_string_literal: true require("spec_helper") describe("Third party analytics", type: :system, js: true) do before do @user = create(:user) @product = create(:product, user: @user) @product2 = create(:product, user: @user) @product_without_3pa = create(:product) end context "on product page" do context "when the product has no third-party analytics" do it "doesn't load the third-party analytics iframe" do visit @product_without_3pa.long_url expect(page).to_not have_selector("iframe[aria-label='Third-party analytics']", visible: false) end end context "when the product has product third-party analytics" do before do create(:third_party_analytic, user: @user, link: @product, location: "product") end it "loads the third-party analytics iframe" do visit @product.long_url expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{@product.unique_permalink}']", visible: false) end end context "when the product has global third-party analytics" do before do create(:third_party_analytic, user: @user, link: @product, location: "all") end it "loads the third-party analytics iframe" do visit @product.long_url expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{@product.unique_permalink}']", visible: false) end end context "when the user has product third-party analytics" do before do create(:third_party_analytic, user: @user, link: nil, location: "product") end it "loads the third-party analytics iframe" do visit @product.long_url expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{@product.unique_permalink}']", visible: false) end end context "when the user has global third-party analytics" do before do create(:third_party_analytic, user: @user, link: nil, location: "all") end it "loads the third-party analytics iframe" do visit @product.long_url expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{@product.unique_permalink}']", visible: false) end end end context "after checkout" do context "when the product has no third-party analytics" do it "doesn't load the third-party analytics iframe" do visit @product_without_3pa.long_url add_to_cart(@product_without_3pa) check_out(@product_without_3pa) expect(page).to_not have_selector("iframe[aria-label='Third-party analytics']", visible: false) end end context "when the product has receipt third-party analytics" do before do create(:third_party_analytic, user: @user, link: @product, location: "receipt") end it "loads the third-party analytics iframe" do visit @product.long_url add_to_cart(@product) check_out(@product) expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{@product.unique_permalink}']", visible: false) end end context "when the product has global third-party analytics" do before do create(:third_party_analytic, user: @user, link: @product, location: "all") end it "loads the third-party analytics iframe" do visit @product.long_url add_to_cart(@product) check_out(@product) expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{@product.unique_permalink}']", visible: false) end end context "when the user has receipt third-party analytics" do before do create(:third_party_analytic, user: @user, link: nil, location: "receipt") end it "loads the third-party analytics iframe" do visit @product.long_url add_to_cart(@product) check_out(@product) expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{@product.unique_permalink}']", visible: false) end end context "when the user has global third-party analytics" do before do create(:third_party_analytic, user: @user, link: nil, location: "all") end it "loads the third-party analytics iframe" do visit @product.long_url add_to_cart(@product) check_out(@product) expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{@product.unique_permalink}']", visible: false) end end context "when an authenticated user purchases multiple products" do before do @product3 = create(:product, user: @user) create(:third_party_analytic, user: @user, link: @product) create(:third_party_analytic, user: @user, link: @product2) create(:third_party_analytic, user: @user, link: @product3, location: "product") @buyer = create(:user) login_as @buyer end it "loads all applicable third-party analytics iframes" do visit @product.long_url add_to_cart(@product) visit @product2.long_url add_to_cart(@product2) visit @product3.long_url add_to_cart(@product3) check_out(@product3, logged_in_user: @buyer) expect(page).to have_alert(text: "Your purchase was successful! We sent a receipt to #{@buyer.email}.") expect(page.current_path).to eq("/library") expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{@product.unique_permalink}'][src*='/#{@product.unique_permalink}?location=receipt&purchase_id=#{URI.encode_www_form_component(@product.sales.sole.external_id)}']", visible: false) expect(page).to have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{@product2.unique_permalink}'][src*='#{@product2.unique_permalink}?location=receipt&purchase_id=#{URI.encode_www_form_component(@product2.sales.sole.external_id)}']", visible: false) expect(page).to_not have_selector("iframe[aria-label='Third-party analytics'][data-permalink='#{@product3.unique_permalink}']", visible: false) end end end describe "Google Analytics cross-domain tracking" do it "preserves the `_gl` search parameter on the checkout page" do visit "#{@product.long_url}?_gl=thing" add_to_cart(@product) wait_for_ajax query = Rack::Utils.parse_query(URI.parse(page.current_url).query) # Ensure that the other query parameters have been cleared out expect(query["quantity"]).to be_nil expect(query["_gl"]).to eq("thing") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/archived_products_spec.rb
spec/requests/products/archived_products_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" require "shared_examples/products_navigation" require "shared_examples/with_sorting_and_pagination" describe "Archived Products", type: :system, js: true do let(:seller) { create(:named_seller) } include_context "with switching account to user as admin for seller" it_behaves_like "tab navigation on products page" do let(:url) { products_archived_index_path } end describe "pagination" do before do stub_const("Products::ArchivedController::PER_PAGE", 1) end it "paginates archived memberships" do membership1 = create(:membership_product, created_at: 3.days.ago, name: "Name 1", user: seller, archived: true) membership2 = create(:membership_product, created_at: 2.days.ago, name: "Name 2", user: seller, archived: true) membership3 = create(:membership_product, created_at: 1.day.ago, name: "Name 3", user: seller, archived: true) visit products_archived_index_path # Page 1 expect(page).to have_nth_table_row_record(1, membership3.name, exact_text: false) expect(page).not_to have_nth_table_row_record(1, membership2.name, exact_text: false) expect(page).not_to have_nth_table_row_record(1, membership1.name, exact_text: false) expect(page).to have_button("Previous", disabled: true) expect(page).to have_button("Next") expect(find_button("1")["aria-current"]).to eq("page") expect(find_button("2")["aria-current"]).to be_nil expect(find_button("3")["aria-current"]).to be_nil # Page 2 click_on "2" wait_for_ajax expect(page).not_to have_nth_table_row_record(1, membership3.name, exact_text: false) expect(page).to have_nth_table_row_record(1, membership2.name, exact_text: false) expect(page).not_to have_nth_table_row_record(1, membership1.name, exact_text: false) expect(page).to have_button("Previous") expect(page).to have_button("Next") expect(find_button("1")["aria-current"]).to be_nil expect(find_button("2")["aria-current"]).to eq("page") expect(find_button("3")["aria-current"]).to be_nil # Page 3 click_on "3" wait_for_ajax expect(page).not_to have_nth_table_row_record(1, membership3.name, exact_text: false) expect(page).not_to have_nth_table_row_record(1, membership2.name, exact_text: false) expect(page).to have_nth_table_row_record(1, membership1.name, exact_text: false) expect(page).to have_button("Previous") expect(page).to have_button("Next", disabled: true) expect(find_button("1")["aria-current"]).to be_nil expect(find_button("2")["aria-current"]).to be_nil expect(find_button("3")["aria-current"]).to eq("page") end it "paginates archived products" do products = {} 15.times do |i| products[i] = create(:product, created_at: i.days.ago, name: "Name #{i}", user: seller, archived: true) end visit products_archived_index_path # Page 1 expect(page).to have_selector(:table_row, { "Name" => products[0].name }) expect(page).not_to have_selector(:table_row, { "Name" => products[1].name }) expect(page).not_to have_selector(:table_row, { "Name" => products[2].name }) expect(page).to have_button("1", exact: true) expect(page).to have_button("9", exact: true) expect(page).not_to have_button("10", exact: true) expect(page).to have_button("15", exact: true) # Page 2 click_on "Next" wait_for_ajax expect(page).to have_selector(:table_row, { "Name" => products[1].name }) # Page 15 click_on "15" wait_for_ajax expect(page).to have_selector(:table_row, { "Name" => products[14].name }) expect(page).to have_button("7", exact: true) expect(page).to have_button("15", exact: true) expect(page).not_to have_button("6", exact: true) expect(page).to have_button("1", exact: true) # Page 14 click_on "Previous" wait_for_ajax expect(page).to have_selector(:table_row, { "Name" => products[13].name }) # Page 7 click_on "7" wait_for_ajax expect(page).to have_selector(:table_row, { "Name" => products[6].name }) expect(page).to have_button("3", exact: true) expect(page).to have_button("10", exact: true) expect(page).not_to have_button("2", exact: true) expect(page).not_to have_button("11", exact: true) expect(page).to have_button("1", exact: true) expect(page).to have_button("15", exact: true) expect(page).to have_button("15", exact: true) end end describe "archived product sorting" do include_context "with products and memberships", true it_behaves_like "a table with sorting", "Products" do before do visit(products_archived_index_path) end let!(:default_order) { [product1, product3, product4, product2] } let!(:columns) do { "Name" => [product1, product2, product3, product4], "Sales" => [product1, product2, product3, product4], } end let!(:boolean_columns) { { "Status" => [product3, product4, product1, product2] } } end end describe "archived membership sorting" do include_context "with products and memberships", true it_behaves_like "a table with sorting", "Memberships" do before do visit(products_archived_index_path) end let!(:default_order) { [membership2, membership3, membership4, membership1] } let!(:columns) do { "Name" => [membership1, membership2, membership3, membership4], "Members" => [membership4, membership1, membership3, membership2], } end let!(:boolean_columns) { { "Status" => [membership3, membership4, membership2, membership1] } } end end describe "Unarchiving" do let!(:archived_membership) { create(:membership_product, user: seller, name: "archived_membership", archived: true) } let!(:archived_product) { create(:product, user: seller, name: "archived_product", archived: true) } it "unarchives a membership" do visit(products_archived_index_path) within find(:table_row, { "Name" => archived_membership.name }) do select_disclosure "Open product action menu" do click_on "Unarchive" end end wait_for_ajax expect(page).to have_alert(text: "Product was unarchived successfully") expect(page).not_to have_content(archived_membership.name) expect(archived_membership.reload.archived).to eq(false) end it "unarchives a product" do visit(products_archived_index_path) within find(:table_row, { "Name" => archived_product.name }) do select_disclosure "Open product action menu" do click_on "Unarchive" end end wait_for_ajax expect(page).to have_alert(text: "Product was unarchived successfully") expect(page).not_to have_content(archived_product.name) expect(archived_product.reload.archived).to eq(false) end context "with one product left on the page" do before do archived_membership.update!(archived: false) end it "redirects to the products page after unarchiving" do visit(products_archived_index_path) within find(:table_row, { "Name" => archived_product.name }) do select_disclosure "Open product action menu" do click_on "Unarchive" end end wait_for_ajax expect(page).to have_current_path(products_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/products/edit/multiple_preview_spec.rb
spec/requests/products/edit/multiple_preview_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" def upload_image click_on "Upload images or videos" page.attach_file(Rails.root.join("spec", "support", "fixtures", "smaller.png")) do select_tab "Computer files" end end describe("Product edit multiple-preview Scenario", type: :system, js: true) do let(:seller) { create(:named_seller) } let(:product) { create(:product, user: seller) } include_context "with switching account to user as admin for seller" it "uploads a preview image" do visit(edit_link_path(product)) upload_image within "[role=tablist][aria-label='Product covers']" do img = first("img") expect(img.native.css_value("max-width")).to eq("100%") find(:tab_button).hover expect(page).to have_selector("[aria-label='Remove cover']") end end it "uploads an image via URL" do visit(edit_link_path(product)) click_on "Upload images or videos" select_tab "External link" fill_in placeholder: "https://", with: "https://picsum.photos/200/300" click_on "Upload" within "[role=tablist][aria-label='Product covers']" do img = first("img") expect(img.native.css_value("max-width")).to eq("100%") find(:tab_button).hover expect(page).to have_selector("[aria-label='Remove cover']") end end it "uploads an image as a second preview" do create(:asset_preview, link: product) visit(edit_link_path(product)) expect(page).to have_selector("img") expect do select_disclosure "Add cover" do upload_image expect(page).to have_selector("[role='progressbar']") end wait_for_ajax end.to change { product.reload.asset_previews.alive.count }.by(1) end it "fails with informative error for too many previews" do Link::MAX_PREVIEW_COUNT.times { create(:asset_preview, link: product) } visit(edit_link_path(product)) expect do button = find(:disclosure_button, "Add cover", disabled: true) button.hover expect(button).to have_tooltip(text: "Maximum number of previews uploaded") end.to_not change { AssetPreview.count } end it "fails gracefully for Internet error" do visit(edit_link_path(product)) expect_any_instance_of(AssetPreview).to receive(:url_or_file).and_raise(URI::InvalidURIError) expect do upload_image expect(page).to have_content("Could not process your preview, please try again.") expect(page).to_not have_selector("[role='progressbar'][aria-label='Uploading...']") end.to_not change { AssetPreview.count } end it "deletes previews" do create(:asset_preview, link: product) create(:asset_preview, link: product) visit(edit_link_path(product)) expect(find(:section, "Cover", section_element: :section)).to have_selector("img") expect(product.asset_previews.alive.count).to eq(2) within "[role=tablist][aria-label='Product covers']" do previews = all("img") expect(first("img")[:src]).to eq(previews.first["src"]) all(:tab_button).first.hover find("[aria-label='Remove cover']").click wait_for_ajax expect(product.asset_previews.alive.count).to eq(1) expect(first("img")[:src]).to eq(previews.last["src"]) find(:tab_button).hover find("[aria-label='Remove cover']").click end expect(page).to_not have_selector("[role=tablist][aria-label='Product covers']") expect(page).to have_button("Upload images or videos") expect(product.asset_previews.alive.count).to eq(0) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/edit/rich_text_editor_spec.rb
spec/requests/products/edit/rich_text_editor_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Product Edit Rich Text Editor", type: :system, js: true) do include ProductEditPageHelpers let(:seller) { create(:named_seller, :eligible_for_service_products) } before do @product = create(:product_with_pdf_file, user: seller, size: 1024) @product.shipping_destinations << ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0) end include_context "with switching account to user as admin for seller" it "instantly preview changes to product description" do visit("/products/#{@product.unique_permalink}/edit") in_preview do expect(page).to have_text @product.description end set_rich_text_editor_input find("[aria-label='Description']"), to_text: "New description line" in_preview do expect(page).to have_text "New description line" end end it "trims leading/trailing spaces for description" do visit("/products/#{@product.unique_permalink}/edit") set_rich_text_editor_input find("[aria-label='Description']"), to_text: " New description line. " in_preview do expect(page).to_not have_text " New description line. " expect(page).to have_text "New description line." end end it "removes data URLs from description on content update or save" do description = "<p>Text1</p><p>Text2<figure><img class='img-data-uri' src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD'/></figure></p>" visit("/products/#{@product.unique_permalink}/edit") page.execute_script("$(\"[aria-label='Description']\").html(\"#{description}\");") sleep 1 in_preview do expect(page).to have_content "Text1" expect(page).to have_content "Text2" expect(page).to_not have_selector("figure img") end save_change expect(@product.reload.description).to_not include("data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD") end it "shows loading spinner over an image while it is being uploaded" do visit edit_link_path(@product) rich_text_editor_input = find("[aria-label='Description']") attach_file file_fixture("smilie.png") do click_on "Insert image" end expect(rich_text_editor_input).to have_selector("img[src^='blob:']") expect(rich_text_editor_input).to have_selector("figure [role='progressbar']") expect(rich_text_editor_input).to have_selector("img[src^='#{AWS_S3_ENDPOINT}/#{S3_BUCKET}']") expect(rich_text_editor_input).to_not have_selector("figure [role='progressbar']") end it "shows a warning when switching to other tabs while images or files are still uploading" do Feature.activate_user(:audio_previews, @product.user) visit edit_link_path(@product) rich_text_editor_input = find("[aria-label='Description']") # When images are uploading attach_file file_fixture("smilie.png") do click_on "Insert image" end expect(rich_text_editor_input).to have_selector("img[src^='blob:']") # TODO(ershad): Enable this once we have a way to slow down the upload process # select_tab "Content" # expect(page).to have_alert(text: "Some images are still uploading, please wait...") expect(page).to have_current_path(edit_link_path(@product)) expect(page).to have_tab_button("Product", open: true) expect(rich_text_editor_input).to have_selector("img[src^='#{AWS_S3_ENDPOINT}/#{S3_BUCKET}']") select_tab "Content" expect(page).to_not have_alert(text: "Some images are still uploading, please wait...") expect(page).to have_current_path(edit_link_path(@product) + "/content") expect(page).to have_tab_button("Content", open: true) # When files are uploading select_tab "Product" attach_file file_fixture("test.mp3") do click_on "Insert audio" end select_tab "Content" expect(page).to have_alert(text: "Some files are still uploading, please wait...") wait_for_file_embed_to_finish_uploading(name: "test") select_tab "Content" expect(page).to_not have_alert(text: "Some files are still uploading, please wait...") expect(page).to have_current_path(edit_link_path(@product) + "/content") expect(page).to have_tab_button("Content", open: true) end it "ignores overlay links" do url = "#{@product.long_url}?wanted=true" visit edit_link_path(@product) select_disclosure "Insert" do click_on "Button" end within_modal do fill_in "Enter text", with: "Buy button" fill_in "Enter URL", with: url send_keys :enter end click_on "Insert link" within_modal do fill_in "Enter URL", with: url fill_in "Enter text", with: "Buy link" click_on "Add link" end in_preview do expect(page).to have_link "Buy button" expect(page).to have_link "Buy link" end end it "supports adding external links" do visit("/products/#{@product.unique_permalink}/edit") rich_text_editor_input = find("[aria-label='Description']") click_on "Insert link" within_modal do fill_in "Enter URL", with: "https://example.com/link1" click_on "Add link" end click_on "Insert link" within_modal do fill_in "Enter URL", with: "https://example.com/link2" send_keys :enter end expect(rich_text_editor_input).to have_link("https://example.com/link1", href: "https://example.com/link1") expect(rich_text_editor_input).to have_link("https://example.com/link2", href: "https://example.com/link2") sleep 1 save_change expect(@product.reload.description).to have_link("https://example.com/link1", href: "https://example.com/link1") expect(@product.description).to have_link("https://example.com/link2", href: "https://example.com/link2") end it "supports adding an external link with label" do visit("/products/#{@product.unique_permalink}/edit") external_link = "https://gumroad.com/" rich_text_editor_input = find("[aria-label='Description']") click_on "Insert link" within_modal do fill_in "Enter text", with: "Gumroad" fill_in "Enter URL", with: external_link click_on "Add link" end expect(rich_text_editor_input).to have_link("Gumroad", href: external_link) sleep 1 save_change expect(@product.reload.description).to include("<a href=\"#{external_link}\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">Gumroad</a>") rich_text_editor_select_all(rich_text_editor_input) click_on "Bold" click_on "Italic" new_link = "https://notgumroad.com/" within rich_text_editor_input do click_on "Gumroad" within_disclosure "Gumroad" do fill_in "Enter text", with: "Not Gumroad" click_on "Save" end click_on "Not Gumroad" within_disclosure "Not Gumroad" do fill_in "Enter URL", with: new_link click_on "Save" end expect(page).to have_link("Not Gumroad", href: new_link) expect(page).to_not have_link("Not Gumroad", href: external_link) end expect(page).to have_selector("strong", text: "Not Gumroad") expect(page).to have_selector("em", text: "Not Gumroad") save_change expect(@product.reload.description).to include new_link expect(@product.description).to_not include external_link visit @product.long_url expect(page).to have_link("Not Gumroad", href: new_link) expect(page).to_not have_disclosure("Not Gumroad") expect(page).to have_selector("strong", text: "Not Gumroad") expect(page).to have_selector("em", text: "Not Gumroad") visit edit_link_path(@product) within find("[aria-label='Description']") do click_on "Not Gumroad" within_disclosure "Not Gumroad" do click_on "Remove link" end expect(page).to_not have_link("Not Gumroad", href: new_link) end end it "converts legacy links to the links with edit support on clicking a legacy link" do rich_content = create( :product_rich_content, entity: @product, description: [ { "type" => "paragraph", "content" => [ { "type" => "text", "text" => "Visit " }, { "type" => "text", "text" => "Google", "marks" => [{ "type" => "link", "attrs" => { "href" => "https://google.com" } }] }, { "type" => "text", "text" => " to explore the web" } ] }, { "type" => "paragraph", "content" => [ { "type" => "text", "text" => "And also visit " }, { "type" => "text", "text" => "Gumroad", "marks" => [{ "type" => "link", "attrs" => { "href" => "https://gumroad.com" } }] }, { "type" => "text", "text" => " to buy products from indie creators" } ] } ] ) Feature.activate(:product_edit_react) visit("#{edit_link_path(@product)}/content") within find("[aria-label='Content editor']") do expect(page).to have_link("Gumroad", href: "https://gumroad.com") expect(page).to have_link("Google", href: "https://google.com") expect(page).to have_text("Visit Google to explore the web", normalize_ws: true) expect(page).to have_text("And also visit Gumroad to buy products from indie creators", normalize_ws: true) end click_on "Google" sleep 0.5 # Wait for the editor to update the content save_change wait_for_ajax expect(rich_content.reload.description).to eq([ { "type" => "paragraph", "content" => [ { "type" => "text", "text" => "Visit " }, { "type" => "tiptap-link", "attrs" => { "href" => "https://google.com" }, "content" => [{ "text" => "Google", "type" => "text" }] }, { "type" => "text", "text" => " to explore the web" } ] }, { "type" => "paragraph", "content" => [ { "type" => "text", "text" => "And also visit " }, { "type" => "tiptap-link", "attrs" => { "href" => "https://gumroad.com" }, "content" => [{ "text" => "Gumroad", "type" => "text" }] }, { "type" => "text", "text" => " to buy products from indie creators" } ] } ]) refresh within find("[aria-label='Content editor']") do expect(page).to have_link("Gumroad", href: "https://gumroad.com") expect(page).to have_link("Google", href: "https://google.com") expect(page).to have_text("Visit Google to explore the web", normalize_ws: true) expect(page).to have_text("And also visit Gumroad to buy products from indie creators", normalize_ws: true) end click_on "Gumroad" within_disclosure "Gumroad" do expect(page).to have_field("Enter text", with: "Gumroad") expect(page).to have_field("Enter URL", with: "https://gumroad.com") end end it "does not open a new tab when an external link is clicked" do @product.update!(description: '<a href="https://gumroad.com" target="_blank">Gumroad</a>') visit("/products/#{@product.unique_permalink}/edit") within("[aria-label='Description']") do # Need to double click in order to ensure we have the editor input focused first find("a").double_click end expect(page.driver.browser.window_handles.size).to eq(1) end it "validates links, fixing links with invalid protocols and adding https where necessary" do visit("/products/#{@product.unique_permalink}/edit") rich_text_editor_input = find("[aria-label='Description']") click_on "Insert link" within_modal do fill_in "Enter text", with: "An invalid link 1" fill_in "Enter URL", with: "" click_on "Add link" end expect(page).to have_alert(text: "Please enter a valid URL.") expect(page).to_not have_alert(text: "Please enter a valid URL.") fill_in "Enter text", with: "An invalid link 2" fill_in "Enter URL", with: "/broken:link" click_on "Add link" expect(page).to have_alert(text: "Please enter a valid URL.") expect(page).to_not have_alert(text: "Please enter a valid URL.") fill_in "Enter text", with: "Valid link 1" fill_in "Enter URL", with: " gumroad.com " click_on "Add link" expect(page).to_not have_alert(text: "Please enter a valid URL.") rich_text_editor_input.native.send_keys(:control, "e") # Move cursor to end of line rich_text_editor_input.native.send_keys(:enter) click_on "Insert link" within_modal do fill_in "Enter text", with: "Valid link 2" fill_in "Enter URL", with: " https//example.com/1?q=hello" click_on "Add link" end expect(page).to_not have_alert(text: "Please enter a valid URL.") rich_text_editor_input.native.send_keys(:control, "e") # Move cursor to end of line rich_text_editor_input.native.send_keys(:enter) click_on "Insert link" within_modal do fill_in "Enter text", with: "Valid link 3" fill_in "Enter URL", with: "http:example.com/2?q=hello" click_on "Add link" end expect(page).to_not have_alert(text: "Please enter a valid URL.") expect(rich_text_editor_input).to_not have_text("An invalid link 1") expect(rich_text_editor_input).to_not have_text("An invalid link 2") expect(rich_text_editor_input).to have_link("Valid link 1", href: "https://gumroad.com/") expect(rich_text_editor_input).to have_link("Valid link 2", href: "https://example.com/1?q=hello") expect(rich_text_editor_input).to have_link("Valid link 3", href: "https://example.com/2?q=hello") sleep 1 save_change expect(@product.reload.description).to_not include("An invalid link 1") expect(@product.reload.description).to_not include("An invalid link 2") expect(@product.reload.description).to include("https://gumroad.com/") expect(@product.reload.description).to include("https://example.com/1?q=hello") expect(@product.reload.description).to include("https://example.com/2?q=hello") end it "supports twitter embeds" do visit("/products/#{@product.unique_permalink}/edit") rich_text_editor_input = find("[aria-label='Description']") select_disclosure "Insert" do click_on "Twitter post" end within_modal do fill_in "URL", with: "https://twitter.com/gumroad/status/1380521414818557955" click_on "Insert" end wait_for_ajax sleep 1 expect(rich_text_editor_input.find("iframe")[:src]).to include "1380521414818557955" save_change expect(@product.reload.description).to include "iframe.ly/api/iframe?app=1&amp;url=#{CGI.escape("https://twitter.com/gumroad/status/1380521414818557955")}" end it "supports button embeds" do visit("/products/#{@product.unique_permalink}/edit") external_link = "https://gumroad.com/" rich_text_editor_input = find("[aria-label='Description']") select_disclosure "Insert" do click_on "Button" end within_modal do fill_in "Enter text", with: "Gumroad" fill_in "Enter URL", with: external_link click_on "Add button" end wait_for_ajax expect(rich_text_editor_input).to have_link("Gumroad", href: external_link) save_change expect(@product.reload.description).to include external_link rich_text_editor_select_all(rich_text_editor_input) click_on "Bold" click_on "Italic" rich_text_editor_input.click new_link = "https://notgumroad.com/" within rich_text_editor_input do select_disclosure "Gumroad" do fill_in "Enter URL", with: new_link click_on "Save" end select_disclosure "Gumroad" do fill_in "Enter text", with: "Not Gumroad" click_on "Save" end expect(page).to have_link("Not Gumroad", href: new_link) expect(page).not_to have_link("Gumroad", href: external_link) end expect(page).to have_selector("strong", text: "Not Gumroad") expect(page).to have_selector("em", text: "Not Gumroad") save_change expect(@product.reload.description).to include new_link expect(@product.description).not_to include external_link visit @product.long_url expect(page).to have_link("Not Gumroad", href: new_link) expect(page).to_not have_disclosure("Not Gumroad") expect(page).to have_selector("strong", text: "Not Gumroad") expect(page).to have_selector("em", text: "Not Gumroad") end it "stores editor history actions" do visit("/products/#{@product.unique_permalink}/edit") expect(page).to have_selector("[aria-label='Undo last change']") expect(page).to have_selector("[aria-label='Redo last undone change']") rich_text_editor_input = find("[aria-label='Description']") rich_text_editor_input.native.clear expect(rich_text_editor_input).to have_content("") expect(page).to have_selector("[aria-label='Undo last change']") expect(page).to have_selector("[aria-label='Redo last undone change']") click_on "Undo last change" expect(rich_text_editor_input).to have_content(@product.plaintext_description) expect(page).to have_selector("[aria-label='Undo last change']") expect(page).to have_selector("[aria-label='Redo last undone change']") click_on "Redo last undone change" expect(rich_text_editor_input).to have_content("") expect(page).to have_selector("[aria-label='Undo last change']") expect(page).to have_selector("[aria-label='Redo last undone change']") end it "fixes blocks containing blocks so TipTap doesn't discard them" do @product.update(description: "<h4><p>test</p><p><figure><img src=\"http://fake/\"><p class=\"figcaption\">Caption</p></figure></p><p>test 2</p></h4>") visit("/products/#{@product.unique_permalink}/edit") rich_text_editor_input = find("[aria-label='Description']") expect(rich_text_editor_input).to have_selector("p", text: "test") expect(rich_text_editor_input).to have_selector("img[src=\"http://fake/\"]") expect(rich_text_editor_input).to have_selector("p.figcaption", text: "Caption") expect(rich_text_editor_input).to have_selector("p", text: "test 2") rich_text_editor_input.send_keys("more text") sleep 1 save_change expect(@product.reload.description).to eq "<h4><br></h4><p>test</p><p><br></p><figure><img src=\"http://fake/\"><p class=\"figcaption\">Caption</p></figure><p><br></p><p>test 2more text</p>" end describe "Dynamic product content editor" do it "does not show Insert video popover and external link tab within Insert link popover" do visit edit_link_path(@product) + "/content" expect(page).not_to have_button("Insert video") select_disclosure "Upload files" do expect(page).not_to have_tab_button("Link to external page") end end it "supports embedding tweets" do tweet_url = "https://x.com/gumroad/status/1743053631640006693" product = create(:product, user: seller) visit edit_link_path(product) + "/content" rich_text_editor_input = find("[aria-label='Content editor']") select_disclosure "Insert" do click_on "Twitter post" end expect(page).to have_content("Insert Twitter post") fill_in "URL", with: tweet_url click_on "Insert" expect(page).to_not have_text("URL") sleep 0.5 # wait for the editor to update the content escaped_url = CGI.escape(tweet_url) iframely_base = "https://cdn.iframe.ly/api/iframe" expect(rich_text_editor_input.find("iframe")[:src]).to include(iframely_base) expect(rich_text_editor_input.find("iframe")[:src]).to include("url=#{escaped_url}") save_change description = product.reload.rich_contents.first.description.first expect(description["type"]).to eq("raw") expect(description["attrs"]["html"]).to include(iframely_base) expect(description["attrs"]["html"]).to include("url=#{escaped_url}") end end describe "public files in the product description" do before do Feature.activate_user(:audio_previews, @product.user) end it "uploads and embeds public audio files" do visit edit_link_path(@product) # Validate that non-audio files are not allowed attach_file file_fixture("test.pdf") do click_on "Insert audio" end expect(page).to have_alert(text: "Only audio files are allowed") expect(page).to_not have_embed(name: "test") # Validate that large files are not allowed attach_file file_fixture("big-music-file.mp3") do click_on "Insert audio" end expect(page).to have_alert(text: "File is too large (max allowed size is 5.0 MB)") expect(page).to_not have_embed(name: "big-music-file") # Upload a valid audio file attach_file file_fixture("test.mp3") do click_on "Insert audio" end expect(page).to have_button("Save changes", disabled: true) wait_for_file_embed_to_finish_uploading(name: "test") expect(page).to have_button("Save changes", disabled: false) within find_embed(name: "test") do expect(page).to have_text("MP3") expect(page).to have_button("Play") click_on "Edit" expect(page).to have_field("Name", with: "test") # Allow renaming the file fill_in "Enter file name", with: "My awesome track" expect(page).to have_text("My awesome track") click_on "Close drawer" # Allow playing the file click_on "Play" expect(page).to have_selector("[aria-label='Progress']", text: "00:00") expect(page).to have_selector("[aria-label='Progress']", text: "00:01") expect(page).to have_selector("[aria-label='Pause']") click_on "Pause" expect(page).to have_selector("[aria-label='Rewind15']") click_on "Close" expect(page).to_not have_selector("[aria-label='Rewind15']") end # Validate that only a certain number of files are allowed attach_file file_fixture("test.mp3") do click_on "Insert audio" end wait_for_file_embed_to_finish_uploading(name: "test") rename_file_embed(from: "test", to: "My MP3 track") attach_file file_fixture("test.wav") do click_on "Insert audio" end expect(page).not_to have_selector("[role='progressbar']") attach_file file_fixture("magic.mp3") do click_on "Insert audio" end expect(page).not_to have_selector("[role='progressbar']") attach_file file_fixture("sample.flac") do click_on "Insert audio" end expect(page).not_to have_selector("[role='progressbar']") attach_file file_fixture("test-with-tags.wav") do click_on "Insert audio" end expect(page).to have_alert(text: "You can only upload up to 5 audio previews in the description") # Ensure that embedded files are visible in the preview pane within_section("Preview", section_element: :aside) do expect(page).to have_embed(name: "My awesome track") expect(page).to have_embed(name: "test") expect(page).to have_embed(name: "magic") expect(page).to have_embed(name: "sample") expect(page).to have_embed(name: "My MP3 track") end save_change # Validate that the files are embedded correctly and saved in the database @product.reload expect(@product.description.scan(/<public-file-embed/).size).to eq(5) expect(@product.alive_public_files.pluck(:display_name, :file_type, :file_group)).to match_array([ ["My awesome track", "mp3", "audio"], ["My MP3 track", "mp3", "audio"], ["test", "wav", "audio"], ["magic", "mp3", "audio"], ["sample", "flac", "audio"], ]) @product.alive_public_files.pluck(:public_id).each do |public_id| expect(@product.description).to include("<public-file-embed id=\"#{public_id}\"></public-file-embed>") end # Validate that the files persist after a page reload refresh within find("[aria-label='Description']") do expect(page).to have_embed(name: "My awesome track") expect(page).to have_embed(name: "My MP3 track") expect(page).to have_embed(name: "test") expect(page).to have_embed(name: "magic") expect(page).to have_embed(name: "sample") end # Ensure that files render correctly in the description on the product page visit @product.long_url expect(page).to have_embed(name: "My awesome track") expect(page).to have_embed(name: "My MP3 track") expect(page).to have_embed(name: "test") expect(page).to have_embed(name: "magic") expect(page).to have_embed(name: "sample") within find_embed(name: "test") do click_on "Play" expect(page).to have_selector("[aria-label='Progress']", text: "00:00") expect(page).to have_selector("[aria-label='Progress']", text: "00:01") expect(page).to have_selector("[aria-label='Pause']") click_on "Pause" expect(page).to have_selector("[aria-label='Rewind15']") click_on "Close" expect(page).to_not have_selector("[aria-label='Rewind15']") end end end describe "More like this block" do let(:product) { create(:product, user: seller) } before { visit edit_link_path(product) + "/content" } it "allows inserting the More like this block with recommended products" do select_disclosure "Insert" do click_on "More like this" end expect(page).to have_selector("h2", text: "Customers who bought this product also bought") within ".node-moreLikeThis" do wait_for_ajax expect(page).to have_selector("article") find("[aria-label='Actions']").click within("[role='menu']") do click_on "Settings" end expect(page).to have_checked_field("Only my products") end end it "allows updating the More like this block with directly affiliated products" do select_disclosure "Insert" do click_on "More like this" end within ".node-moreLikeThis" do find("[aria-label='Actions']").click within("[role='menu']") do click_on "Settings" end find("label", text: "My products and affiliated").click expect(page).not_to have_selector("[role='menu']") end end it "shows a placeholder when no product recommendations are received" do allow(RecommendedProducts::CheckoutService).to receive(:fetch_for_cart).and_return([]) select_disclosure "Insert" do click_on "More like this" end within ".node-moreLikeThis" do wait_for_ajax expect(page).to have_content("No products found") end end end describe "post-purchase custom fields" do let!(:long_answer) { create(:custom_field, seller: @product.user, products: [@product], field_type: CustomField::TYPE_LONG_TEXT, is_post_purchase: true, name: "Long answer") } let!(:short_answer) { create(:custom_field, seller: @product.user, products: [@product], field_type: CustomField::TYPE_TEXT, is_post_purchase: true, name: "Short answer") } let!(:file_upload) { create(:custom_field, seller: @product.user, products: [@product], field_type: CustomField::TYPE_FILE, is_post_purchase: true) } let!(:rich_content) do create( :product_rich_content, entity: @product, description: [ { "type" => RichContent::LONG_ANSWER_NODE_TYPE, "attrs" => { "id" => long_answer.external_id, "label" => "Long answer" } }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "id" => short_answer.external_id, "label" => "Short answer" }, }, { "type" => RichContent::FILE_UPLOAD_NODE_TYPE, "attrs" => { "id" => file_upload.external_id } }, ] ) end before { Feature.activate(:product_edit_react) } it "allows creating and modifying post-purchase custom fields" do visit "#{edit_link_path(@product)}/content" expect(page).to have_field("Title", with: "Long answer") expect(page).to have_field("Long answer", with: "", type: "textarea") expect(page).to have_field("Title", with: "Short answer") expect(page).to have_field("Short answer", with: "") expect(page).to have_button("Upload files") set_rich_text_editor_input find("[aria-label='Content editor']"), to_text: "" save_change @product.reload expect(@product.custom_fields).to eq([]) expect(@product.rich_contents.alive.flat_map(&:custom_field_nodes)).to eq([]) select_disclosure "Insert" do click_on "Input" within("[role='menu']") do click_on "Short answer" end end click_on "Save changes" expect(page).to have_alert(text: "You must add titles to all of your inputs") fill_in "Title", with: "New short answer" select_disclosure "Insert" do click_on "Input" within("[role='menu']") do click_on "Long answer" end end find_field("Title", with: "").fill_in with: "New long answer" select_disclosure "Insert" do click_on "Input" within("[role='menu']") do click_on "Upload file" end end save_change @product.reload new_short_answer = @product.custom_fields.last expect(new_short_answer.name).to eq("New short answer") expect(new_short_answer.field_type).to eq(CustomField::TYPE_TEXT) expect(new_short_answer.is_post_purchase).to eq(true) expect(new_short_answer.products).to eq([@product]) expect(new_short_answer.seller).to eq(@product.user) new_long_answer = @product.custom_fields.second_to_last expect(new_long_answer.name).to eq("New long answer") expect(new_long_answer.field_type).to eq(CustomField::TYPE_LONG_TEXT) expect(new_long_answer.is_post_purchase).to eq(true) expect(new_long_answer.products).to eq([@product]) expect(new_long_answer.seller).to eq(@product.user) new_file_upload = @product.custom_fields.third_to_last expect(new_file_upload.name).to eq(CustomField::FILE_FIELD_NAME) expect(new_file_upload.field_type).to eq(CustomField::TYPE_FILE) expect(new_file_upload.is_post_purchase).to eq(true) expect(new_file_upload.products).to eq([@product]) expect(new_file_upload.seller).to eq(@product.user) expect(@product.rich_contents.alive.flat_map(&:description)).to eq( [ { "type" => RichContent::FILE_UPLOAD_NODE_TYPE, "attrs" => { "id" => new_file_upload.external_id } }, { "type" => RichContent::LONG_ANSWER_NODE_TYPE, "attrs" => { "id" => new_long_answer.external_id, "label" => "New long answer" } }, { "type" => RichContent::SHORT_ANSWER_NODE_TYPE, "attrs" => { "id" => new_short_answer.external_id,
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/edit/preview_spec.rb
spec/requests/products/edit/preview_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Product Edit Previews", type: :system, js: true) do include ProductEditPageHelpers def nth(index, selector) el = all(selector)[index] raise "no elements found using selector '#{selector}'" unless el el end let(:seller) { create(:named_seller) } let(:product) { create(:product_with_pdf_file, user: seller, size: 1024) } include_context "with switching account to user as admin for seller" it "opens the full-screen preview only after the changes have been saved" do visit edit_link_path(product.unique_permalink) fill_in("You'll get...", with: "This should be saved automatically") new_window = window_opened_by do click_on "Preview" end within_window new_window do expect(page).to have_content "This should be saved automatically" end end it("instantly preview changes to product name and price") do visit edit_link_path(product.unique_permalink) in_preview do expect(page).to have_content product.name expect(page).to have_content "$#{product.price_cents / 100}" end fill_in("Name", with: "Slot machine") in_preview do expect(page).to have_content "Slot machine" end fill_in("Amount", with: 777) in_preview do expect(page).to have_content "$777" end fill_in("Amount", with: "888") check "Allow customers to pay what they want" in_preview do expect(page).to have_content "$888+" end end it("instantly previews variants") do visit edit_link_path(product.unique_permalink) click_on "Add version" within version_rows[0] do fill_in "Version name", with: "Version 1" end click_on "Add version" within version_rows[0] do within version_option_rows[1] do fill_in "Version name", with: "Version 2" fill_in "Maximum number of purchases", with: 0 end end in_preview do within find(:radio_button, "Version 1") do expect(page).to have_text("$1") expect(page).to_not have_text("$1+") expect(page).to_not have_text("a month") end within find(:radio_button, "Version 2", disabled: true) do expect(page).to have_text("$1") expect(page).to_not have_text("$1+") expect(page).to_not have_text("a month") expect(page).to have_text("0 left") end end check "Hide sold out versions" in_preview do expect(page).to have_radio_button("Version 1", disabled: false) expect(page).to_not have_radio_button("Version 2") end end describe("sales count", :sidekiq_inline, :elasticsearch_wait_for_refresh) do it("instantly previews sales count on toggle change") do recreate_model_index(Purchase) product = create(:product, user: seller) create(:purchase, link: product, succeeded_at: 1.hour.ago) visit edit_link_path(product.unique_permalink) check "Publicly show the number of sales on your product page" in_preview do expect(page).to have_text("1 sale") end # Changes in setting should reflect in preview without browser reload uncheck "Publicly show the number of sales on your product page" in_preview do expect(page).not_to have_text("1 sale") end create(:purchase, link: product, succeeded_at: 1.hour.ago) visit edit_link_path(product.unique_permalink) # Sales count in preview should reflect the actual sales count check "Publicly show the number of sales on your product page" in_preview do expect(page).to have_text("2 sales") end end it("instantly previews supporters count on toggle change") do recreate_model_index(Purchase) product = create(:membership_product, user: seller) create(:membership_purchase, link: product, succeeded_at: 1.hour.ago, price_cents: 100) visit edit_link_path(product.unique_permalink) check "Publicly show the number of members on your product page" in_preview do expect(page).to have_text("1 member") end create(:membership_purchase, link: product, succeeded_at: 1.hour.ago, price_cents: 100) visit edit_link_path(product.unique_permalink) check "Publicly show the number of members on your product page" in_preview do expect(page).to have_text("2 members") end end end context "when initial price is $1 or above" do before do product.update!(price_cents: 100) end it "shows preview price tag at all times" do visit "/products/#{product.unique_permalink}/edit" in_preview do expect(page).to have_content "$1" end fill_in("Amount", with: "0") pwyw_toggle = find_field("Allow customers to pay what they want", disabled: true) expect(pwyw_toggle).to be_checked in_preview do expect(page).to have_content "$0+" end fill_in("Amount", with: "10") in_preview do expect(page).to have_content "$10" end end end context "when initial price is $0+" do before do product.update!(price_cents: 0, customizable_price: true) end it "does not hide the preview price tag when changed via PWYW setting" do visit "/products/#{product.unique_permalink}/edit" in_preview do expect(page).to have_content "$0+" end pwyw_toggle = find_field("Allow customers to pay what they want", disabled: true) expect(pwyw_toggle).to be_checked in_preview do expect(page).to have_content "$0+" end end end context "for a collab product" do let(:affiliate_user) { create(:user, name: "Jane Collab") } let!(:collaborator) { create(:collaborator, seller:, affiliate_user:, products: [product]) } shared_examples_for "displaying collaborator" do it "shows the collaborator's name if they should be shown as a co-creator" do visit edit_link_path(product.unique_permalink) in_preview do expect(page).to have_content affiliate_user.name end end it "does not show the collaborator's name if they should not be shown as a co-creator" do collaborator.update!(dont_show_as_co_creator: true) visit edit_link_path(product.unique_permalink) in_preview do expect(page).not_to have_content affiliate_user.name end end end it_behaves_like "displaying collaborator" context "that is a bundle" do let(:product) { create(:product, :bundle, user: seller) } it_behaves_like "displaying collaborator" end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/edit/purchase_flow_spec.rb
spec/requests/products/edit/purchase_flow_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("ProductPurchaseFlowScenario", type: :system, js: true) do include ProductEditPageHelpers let(:seller) { create(:named_seller) } let(:product) { create(:product_with_pdf_file, user: seller, size: 1024) } include_context "with switching account to user as admin for seller" it "always shows the Require shipping information toggle for all product types" do product.update!(require_shipping: true) visit edit_link_path(product.unique_permalink) expect(page).to have_field("Require shipping information") uncheck("Require shipping information") save_change visit current_path expect(page).to have_field("Require shipping information") expect(product.reload.require_shipping).to be false end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/edit/receipt_spec.rb
spec/requests/products/edit/receipt_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Product Edit Receipt Tab", type: :system, js: true) do include ProductEditPageHelpers include PreviewBoxHelpers let(:seller) { create(:named_seller) } let!(:product) { create(:product_with_pdf_file, user: seller, size: 1024) } include_context "with switching account to user as admin for seller" describe "Receipt customization" do it "allows updating custom view content button text" do visit "#{edit_link_path(product.unique_permalink)}/receipt" fill_in "Button text", with: "Download Now!" expect do save_change product.reload end.to change { product.custom_view_content_button_text }.from(nil).to("Download Now!") expect(find_field("Button text").value).to eq("Download Now!") end it "allows updating custom receipt text" do visit "#{edit_link_path(product.unique_permalink)}/receipt" custom_text = "Thank you for your purchase! Please check your email for download instructions." fill_in "Custom message", with: custom_text expect do save_change product.reload end.to change { product.custom_receipt_text }.from(nil).to(custom_text) expect(find_field("Custom message").value).to eq(custom_text) end end describe "Receipt preview" do it "shows live preview when the user makes changes", :js do visit "#{edit_link_path(product.unique_permalink)}/receipt" fill_in "Button text", with: "Access Content Now!" fill_in "Custom message", with: "Thank you for your purchase, we hope you enjoy it!" in_preview do expect(page).to have_text("Access Content Now!") expect(page).to have_text("Thank you for your purchase, we hope you enjoy it!") 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/products/edit/file_embeds_spec.rb
spec/requests/products/edit/file_embeds_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" require "shared_examples/file_group_download_all" describe("File embeds in product content editor", type: :system, js: true) do include ProductEditPageHelpers let(:seller) { create(:named_seller) } before :each do @product = create(:product_with_pdf_file, user: seller, size: 1024) @product.shipping_destinations << ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0) end include_context "with switching account to user as admin for seller" it "allows to mark PDF files as stampable" do visit edit_link_path(@product.unique_permalink) + "/content" select_disclosure "Upload files" do attach_product_file(file_fixture("Alice's Adventures in Wonderland.pdf")) end # TODO(ershad): Enable this once we have a way to slow down the upload process # button = find_button("Save changes", disabled: true) # button.hover # expect(button).to have_tooltip(text: "Files are still uploading...") wait_for_file_embed_to_finish_uploading(name: "Alice's Adventures in Wonderland") find_button("Save changes").hover expect(find_button("Save changes")).to_not have_tooltip(text: "Files are still uploading...") toggle_disclosure "Upload files" within find_embed(name: "Alice's Adventures in Wonderland") do click_on "Edit" check("Stamp this PDF with buyer information") end save_change @product = Link.find(@product.id) expect(@product.has_stampable_pdfs?).to eq(true) expect(@product.product_files.last.pdf_stamp_enabled?).to eq(true) visit edit_link_path(@product.unique_permalink) + "/content" within find_embed(name: "Alice's Adventures in Wonderland") do click_on "Edit" uncheck("Stamp this PDF with buyer information") end save_change @product = Link.find(@product.id) expect(@product.has_stampable_pdfs?).to eq(false) expect(@product.product_files.last.pdf_stamp_enabled?).to eq(false) end it "allows to mark video files as stream-only" do visit edit_link_path(@product.unique_permalink) + "/content" select_disclosure "Upload files" do attach_product_file(file_fixture("sample.mov")) end wait_for_file_embed_to_finish_uploading(name: "sample") within find_embed(name: "sample") do click_on "Edit" check("Disable file downloads (stream only)") end save_change @product = Link.find(@product.id) expect(@product.has_stream_only_files?).to eq(true) expect(@product.product_files.last.stream_only?).to eq(true) visit @product.long_url expect(page).to have_text("Watch link provided after purchase") visit edit_link_path(@product.unique_permalink) + "/content" within find_embed(name: "sample") do click_on "Edit" uncheck("Disable file downloads (stream only)") end save_change @product = Link.find(@product.id) expect(@product.has_stream_only_files?).to eq(false) expect(@product.product_files.last.stream_only?).to eq(false) visit @product.long_url expect(page).to have_text("Watch link provided after purchase") end it "displays file size after save properly" do @product.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png") visit edit_link_path(@product.unique_permalink) + "/content" select_disclosure "Upload files" do attach_product_file(file_fixture("Alice's Adventures in Wonderland.pdf")) end wait_for_file_embed_to_finish_uploading(name: "Alice's Adventures in Wonderland") expect(page).to have_embed(name: "Alice's Adventures in Wonderland") save_change within find_embed(name: "Alice's Adventures in Wonderland") do expect(page).to have_text "201.3 KB" end end it "displays file extension" do @product.product_files << create(:readable_document, display_name: "Book") @product.product_files << create(:listenable_audio, display_name: "Music") @product.product_files << create(:streamable_video, display_name: "Video") create(:rich_content, entity: @product, description: @product.product_files.alive.map { { "type" => "fileEmbed", "attrs" => { "id" => _1.external_id, "uid" => SecureRandom.uuid } } }) visit edit_link_path(@product.unique_permalink) + "/content" within find_embed(name: "Book") do expect(page).to have_text("PDF") end within find_embed(name: "Music") do expect(page).to have_text("MP3") end within find_embed(name: "Video") do expect(page).to have_text("MOV") end end it "allows users to upload subtitles with special characters in filenames" do allow(Aws::S3::Resource).to receive(:new).and_return(double(bucket: double(object: double(content_length: 1024, presigned_url: Addressable::URI.encode("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/0000063137454006b85553304efaffb7/original/[]&+.mp4"))))) product_file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/0000063137454006b85553304efaffb7/original/[]&+.mp4") @product.product_files << product_file subtitle_file = create(:subtitle_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/111113dbf4a6428597332c8d2efb51fc/original/[]&+_subtitles.vtt") product_file.subtitle_files << subtitle_file create(:rich_content, entity: @product, description: [{ "type" => "fileEmbed", "attrs" => { "id" => product_file.external_id, "uid" => SecureRandom.uuid } }]) visit edit_link_path(@product.unique_permalink) select_tab "Content" within find_embed(name: "[]&+") do click_on "Edit" expect(page).to have_subtitle_row(name: "[]&+_subtitles") end save_change refresh within find_embed(name: "[]&+") do click_on "Edit" expect(page).to have_subtitle_row(name: "[]&+_subtitles") end end describe "with video" do before do allow(Aws::S3::Resource).to receive(:new).and_return(double(bucket: double(object: double(content_length: 1024, presigned_url: Addressable::URI.encode("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/1111163137454006b85553304efaffb7/original/[]&+.mp4"))))) product_file = create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/0000063137454006b85553304efaffb7/original/[]&+.mp4") @product.product_files << product_file @rich_content = create(:rich_content, entity: @product, description: [{ "type" => "fileEmbed", "attrs" => { "id" => product_file.external_id, "uid" => SecureRandom.uuid } }]) visit edit_link_path(@product.unique_permalink) + "/content" end context "when uploading a valid subtitle file type" do it "displays the subtitle file and allows changing its language" do within find_embed(name: "[]&+") do click_on "Edit" page.attach_file("Add subtitles", Rails.root.join("spec/support/fixtures/sample.srt"), visible: false) expect(page).to have_subtitle_row(name: "sample") expect(page).to have_select("Language", selected: "English") select "Español", from: "Language" end wait_for_ajax save_change refresh within find_embed(name: "[]&+") do click_on "Edit" expect(page).to have_subtitle_row(name: "sample") expect(page).to have_select("Language", selected: "Español") end end end context "when uploading an invalid subtitle file type" do it "displays a flash error message" do within find_embed(name: "[]&+") do click_on "Edit" page.attach_file("Add subtitles", Rails.root.join("spec/support/fixtures/sample.gif"), visible: false) end wait_for_ajax expect(page).to have_alert(text: "Invalid file type.") within find_embed(name: "[]&+") do expect(page).to_not have_subtitle_row(name: "sample") end end end # Backwards compatibility test for existing products with invalid subtitle file types context "when an invalid subtitle file type" do before do @product = create(:product, user: seller) video_path = "attachments/43a5363194e74e9ee75b6203eaea6705/original/chapter2.mp4" video_uri = URI.parse("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{video_path}").to_s video_product_file = create(:product_file, url: video_uri.to_s) @product.product_files = [video_product_file] pdf_path = "attachments/23b2d41ac63a40b5afa1a99bf38a0982/original/test.pdf" pdf_uri = URI.parse("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{pdf_path}").to_s subtitle_file = build(:subtitle_file, url: pdf_uri.to_s, product_file_id: video_product_file.id) # Skip subtitle validation to allow saving an invalid file type subtitle_file.save!(validate: false) create(:rich_content, entity: @product, description: [{ "type" => "fileEmbed", "attrs" => { "id" => video_product_file.external_id, "uid" => SecureRandom.uuid } }]) s3_res_double = double bucket_double = double @s3_object_double = double allow(Aws::S3::Resource).to receive(:new).times.and_return(s3_res_double) allow(s3_res_double).to receive(:bucket).times.and_return(bucket_double) allow(bucket_double).to receive(:object).times.and_return(@s3_object_double) allow(@s3_object_double).to receive(:content_length).times.and_return(1) allow(@s3_object_double).to receive(:presigned_url).times.and_return(video_uri) visit edit_link_path(@product.unique_permalink) + "/content" within find_embed(name: "chapter2") do click_on "Edit" expect(page).to have_subtitle_row(name: "test") end end it "displays a subtitle error message when saving a product with an invalid subtitle file type" do fill_in "Name", with: "some other text so that the file is marked as `modified` and does not get ignored on 'Save Changes'" save_change(expect_message: "Subtitle type not supported. Please upload only subtitles with extension .srt, .sub, .sbv, or .vtt.") end it "saves the product after removing the invalid subtitle file" do within_fieldset "Subtitles" do click_on "Remove" end save_change end end end it "updates a file's name, description, and ISBN right away" do product = create(:product, user: seller) product.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/jimbo.pdf") create(:rich_content, entity: product, description: [{ "type" => "fileEmbed", "attrs" => { "id" => product.product_files.first.external_id, "uid" => SecureRandom.uuid } }]) visit edit_link_path(product.unique_permalink) + "/content" expect(product.product_files.first.name_displayable).to eq "jimbo" rename_file_embed from: "jimbo", to: "jimmy" within find_embed(name: "jimmy") do click_on "Edit" fill_in "Description", with: "brand-new jimmy" fill_in "ISBN", with: "978-3-16-148410-0" end save_change product.reload expect(product.product_files.first.name_displayable).to eq "jimmy" expect(product.product_files.first.description).to eq "brand-new jimmy" expect(product.product_files.first.isbn).to eq "978-3-16-148410-0" refresh within find_embed(name: "jimmy") do click_on "Edit" expect(page).to have_field("ISBN", with: "978-3-16-148410-0") end end it "shows validation error when ISBN isn't valid" do product = create(:product, user: seller) product.product_files << create(:product_file, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/jimbo.pdf") create(:rich_content, entity: product, description: [{ "type" => "fileEmbed", "attrs" => { "id" => product.product_files.first.external_id, "uid" => SecureRandom.uuid } }]) visit edit_link_path(product.unique_permalink) + "/content" within find_embed(name: "jimbo") do click_on "Edit" fill_in "ISBN", with: "invalid isbn" end click_on "Save changes" wait_for_ajax expect(page).to have_alert(text: "Validation failed: Isbn is not a valid ISBN-10 or ISBN-13") end it "allows setting ISBN on newly uploaded PDF files" do product = create(:product, user: seller) visit edit_link_path(product.unique_permalink) + "/content" select_disclosure "Upload files" do attach_product_file(file_fixture("Alice's Adventures in Wonderland.pdf")) end wait_for_file_embed_to_finish_uploading(name: "Alice's Adventures in Wonderland") within find_embed(name: "Alice's Adventures in Wonderland") do click_on "Edit" fill_in "ISBN", with: "978-3-16-148410-0" end save_change product.reload expect(product.product_files.last.isbn).to eq "978-3-16-148410-0" end it "allows to rename files multiple times", :sidekiq_inline do visit edit_link_path(@product.unique_permalink) + "/content" select_disclosure "Upload files" do attach_product_file(file_fixture("Alice's Adventures in Wonderland.pdf")) end wait_for_file_embed_to_finish_uploading(name: "Alice's Adventures in Wonderland") save_change product_file = @product.product_files.last refresh expect do rename_file_embed(from: "Alice's Adventures in Wonderland", to: "new name") save_change product_file.reload expect(product_file.display_name).to eq("new name") expect(product_file.url).to match(/new name.pdf\z/) rename_file_embed(from: "new name", to: "newest name") save_change product_file.reload expect(product_file.display_name).to eq("newest name") expect(product_file.url).to match(/newest name.pdf\z/) refresh expect(page).to have_embed(name: "newest name") end.not_to change(ProductFile, :count) end it "allows to rename files even if filenames have special characters [, ], &, +" do allow(Aws::S3::Resource).to receive(:new).and_return(double(bucket: double(object: double(content_length: 1024, presigned_url: Addressable::URI.encode("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/0000063137454006b85553304efaffb7/original/[]&+.mp4"))))) product_file = create(:product_file, link: @product, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/0000063137454006b85553304efaffb7/original/[]&+.mp4") create(:rich_content, entity: @product, description: [{ "type" => "fileEmbed", "attrs" => { "id" => product_file.external_id, "uid" => SecureRandom.uuid } }]) visit edit_link_path(@product.unique_permalink) + "/content" rename_file_embed(from: "[]&+", to: "[]&+new") save_change refresh expect(page).to have_embed(name: "[]&+new") expect(product_file.reload.display_name).to eq("[]&+new") end it "supports playing video embeds" do product = create(:product, user: seller) video = create(:streamable_video, link: product, display_name: "Pilot Episode") create(:rich_content, entity: product, description: [{ "type" => "fileEmbed", "attrs" => { "id" => video.external_id, "uid" => SecureRandom.uuid } }]) visit edit_link_path(product) select_tab "Content" within find_embed(name: "Pilot Episode") do expect(page).to have_field("Upload a thumbnail", visible: false) expect(page).to have_text("The thumbnail image is shown as a preview in the embedded video player.") expect(page).to have_selector("[role=separator]") expect(page).to have_button("Generate a thumbnail") expect(page).to_not have_button("Watch") click_on "Edit" fill_in "Description", with: "Episode 1 description" click_on "Close drawer" expect(page).to have_text("Episode 1 description") end select_disclosure "Upload files" do attach_product_file(file_fixture("sample.mov")) end wait_for_file_embed_to_finish_uploading(name: "sample") sleep 0.5 # wait for the editor to update the content within(find_embed(name: "sample")) do click_on "Watch" expect(page).to_not have_button("Watch") expect(page).to have_button("Pause") expect(page).to have_button("Rewind 10 Seconds") end save_change refresh 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") within(find_embed(name: "sample")) do file = ProductFile.last expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).with( file.s3_key, file.s3_filename, is_video: true ).and_return(video_blob.url) click_on "Watch" expect(page).to_not have_button("Watch") expect(page).to have_button("Pause") expect(page).to have_button("Rewind 10 Seconds") end end it "auto-creates a file grouping when multiple files are uploaded simultaneously" do product = create(:product, user: seller) visit edit_link_path(product) select_tab "Content" select_disclosure "Upload files" do attach_product_file([ file_fixture("test.mp3"), file_fixture("Alice's Adventures in Wonderland.pdf") ]) end sleep 0.5 # wait for the editor to update the content send_keys :enter within_file_group "Untitled" do expect(page).to have_embed(name: "test") expect(page).to have_embed(name: "Alice's Adventures in Wonderland") end within find_embed(name: "test") do click_on "Edit" fill_in "Description", with: "Pilot episode" click_on "Close drawer" expect(page).to have_text("Pilot episode") end end it "supports collapsing video thumbnails" do product = create(:product, user: seller) thumbnail = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "smilie.png") video1 = create(:streamable_video, link: product, display_name: "Pilot Episode", thumbnail:) video2 = create(:streamable_video, link: product, display_name: "Second Episode") create(:rich_content, entity: product, description: [ { "type" => "fileEmbed", "attrs" => { "id" => video1.external_id, "uid" => SecureRandom.uuid } }, { "type" => "fileEmbed", "attrs" => { "id" => video2.external_id, "uid" => SecureRandom.uuid } }, ]) visit edit_link_path(product) select_tab "Content" find_embed(name: "Pilot Episode").click within find_embed(name: "Pilot Episode") do click_on "Thumbnail view" click_on "Collapse selected" expect(page).not_to have_selector("figure") end within find_embed(name: "Second Episode") do expect(page).to have_button("Generate a thumbnail") end within find_embed(name: "Pilot Episode") do click_on "Thumbnail view" click_on "Expand selected" expect(page).to have_selector("figure") end within find_embed(name: "Pilot Episode") do click_on "Thumbnail view" click_on "Collapse all thumbnails" expect(page).not_to have_selector("figure") expect(page).to have_image(src: video1.thumbnail_url) end within find_embed(name: "Second Episode") do expect(page).not_to have_button("Generate a thumbnail") end within find_embed(name: "Pilot Episode") do click_on "Thumbnail view" expect(page).to have_menuitem("Expand all thumbnails") end end context "file downloads" do it "displays inline download buttons for files before and after saving" do product = create(:product, user: seller) visit edit_link_path(product) select_tab "Content" select_disclosure "Upload files" do attach_product_file(file_fixture("Alice's Adventures in Wonderland.pdf")) end wait_for_file_embed_to_finish_uploading(name: "Alice's Adventures in Wonderland") sleep 0.5 # wait for the editor to update the content within(find_embed(name: "Alice's Adventures in Wonderland")) do expect(page).to have_link("Download") end save_change refresh within(find_embed(name: "Alice's Adventures in Wonderland")) do file = ProductFile.last expect(page).to have_link("Download", href: download_product_files_path({ product_file_ids: [file.external_id], product_id: product.external_id })) expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).with( file.s3_key, file.s3_filename, is_video: false ).and_return("https://example.com/file.srt") click_on "Download" end end it_behaves_like "a product with 'Download all' buttons on file embed groups" do let!(:product) { @product } let!(:url_redirect) { nil } let!(:url) { edit_link_path(@product.unique_permalink) + "/content" } end it "displays download buttons for video embeds before and after saving" do product = create(:product, user: seller) visit edit_link_path(product) select_tab "Content" select_disclosure "Upload files" do attach_product_file(file_fixture("sample.mov")) end wait_for_file_embed_to_finish_uploading(name: "sample") sleep 0.5 # wait for the editor to update the content within(find_embed(name: "sample")) do click_link "Download" end save_change refresh within(find_embed(name: "sample")) do file = ProductFile.last expect(page).to have_link("Download", href: download_product_files_path({ product_file_ids: [file.external_id], product_id: product.external_id })) expect_any_instance_of(SignedUrlHelper).to receive(:signed_download_url_for_s3_key_and_filename).with( file.s3_key, file.s3_filename, is_video: true ).and_return("https://example.com/sample.mov") click_on "Download" end end end it "allows copy-pasting content with file embeds from one product to another" do file1 = create(:product_file, display_name: "File 1") file2 = create(:product_file, display_name: "File 2") file3 = create(:product_file, display_name: "File 3") folder_uid = SecureRandom.uuid product1_description = [ { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Paragraph 1" }] }, { "type" => "fileEmbedGroup", "attrs" => { "name" => "My folder", "uid" => folder_uid }, "content" => [ { "type" => "fileEmbed", "attrs" => { "id" => file1.external_id, "uid" => SecureRandom.uuid, "collapsed" => false } }, { "type" => "fileEmbed", "attrs" => { "id" => file2.external_id, "uid" => SecureRandom.uuid, "collapsed" => false } }, ] }, { "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Paragraph 2" }] }, { "type" => "fileEmbed", "attrs" => { "id" => file3.external_id, "uid" => SecureRandom.uuid, "collapsed" => false } } ] product1 = create(:product, user: seller) product1.product_files = [file1, file2, file3] create(:rich_content, entity: product1, description: product1_description) product2 = create(:product, user: seller) visit edit_link_path(product1) select_tab "Content" editor = find("[aria-label='Content editor']") rich_text_editor_select_all editor editor.native.send_keys(ctrl_key, "c") visit edit_link_path(product2) select_tab "Content" editor = find("[aria-label='Content editor']") rich_text_editor_select_all editor editor.native.send_keys(ctrl_key, "v") sleep 0.5 # Wait for the editor to update the content expect(page).to have_text("Paragraph 1") expect(page).to have_text("Paragraph 2") expect(page).to have_embed(name: "File 3") toggle_file_group "My folder" within_file_group "My folder" do expect(page).to have_embed(name: "File 1") expect(page).to have_embed(name: "File 2") end save_change product2_file1 = product2.product_files.find_by(display_name: "File 1") product2_file2 = product2.product_files.find_by(display_name: "File 2") product2_file3 = product2.product_files.find_by(display_name: "File 3") expected_product2_description = product1_description.deep_dup expected_product2_description[1]["content"][0]["attrs"]["id"] = product2_file1.external_id expected_product2_description[1]["content"][1]["attrs"]["id"] = product2_file2.external_id expected_product2_description[3]["attrs"]["id"] = product2_file3.external_id expect(product2.rich_contents.sole.description).to eq(expected_product2_description) end it "allows embedding the same existing files that were uploaded and saved to another version" do product = create(:product_with_digital_versions, user: seller) visit edit_link_path(product) select_tab "Content" select_disclosure "Upload files" do attach_product_file(file_fixture("Alice's Adventures in Wonderland.pdf")) end wait_for_file_embed_to_finish_uploading(name: "Alice's Adventures in Wonderland") save_change expect(page).to have_combo_box("Select a version", text: "Editing: Untitled 1") select_combo_box_option("Untitled 2", from: "Select a version") expect(page).to_not have_embed(name: "Alice's Adventures in Wonderland") select_disclosure "Upload files" do click_on "Existing product files" end within_modal "Select existing product files" do expect(page).to have_text("Alice's Adventures in Wonderland") check "Alice's Adventures in Wonderland" click_on "Select" end expect(page).to have_embed(name: "Alice's Adventures in Wonderland") save_change product.reload product_file_ids = product.alive_product_files.map(&:external_id) expect(product_file_ids.size).to eq(2) expect(product_file_ids).to include(product.alive_variants.find_by(name: "Untitled 1").alive_rich_contents.sole.description.first["attrs"]["id"]) expect(product_file_ids).to include(product.alive_variants.find_by(name: "Untitled 2").alive_rich_contents.sole.description.first["attrs"]["id"]) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/edit/custom_permalink_spec.rb
spec/requests/products/edit/custom_permalink_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Product Edit custom permalink edit", type: :system, js: true) do include ManageSubscriptionHelpers include ProductEditPageHelpers let(:seller) { create(:named_seller) } let!(:product) { create(:product_with_pdf_file, user: seller, size: 1024) } before :each do product.shipping_destinations << ShippingDestination.new( country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0 ) product.custom_permalink = SecureRandom.alphanumeric(5) product.save! end def custom_permalink_input find_field("URL") end def custom_permalink_field custom_permalink_input.find(:xpath, "..") end include_context "with switching account to user as admin for seller" it "has the correct domain prefix" do visit edit_link_path(product.unique_permalink) expect(custom_permalink_field).to have_text("#{seller.username}.#{ROOT_DOMAIN}/l/") end it "links to the correct product page" do visit edit_link_path(product.unique_permalink) prefix_from_page = custom_permalink_field.text custom_permalink_from_page = custom_permalink_input.value custom_permalink_url = "#{PROTOCOL}://#{prefix_from_page}#{custom_permalink_from_page}" using_session("visit custom permalink url") do visit(custom_permalink_url) expect(page).to have_text(product.name) expect(page).to have_text(product.user.name) end end it "allows copying the url" do visit edit_link_path(product.unique_permalink) within(find("label", text: "URL").ancestor("section")) do expect(page).not_to have_content("Copy to Clipboard") copy_link = find_button("Copy URL") copy_link.hover expect(page).to have_content("Copy to Clipboard") copy_link.click expect(page).to have_content("Copied!") # Hover somewhere else to trigger mouseout find("label", text: "URL").hover expect(page).not_to have_content("Copy to Clipboard") expect(page).not_to have_content("Copied!") end end describe "updates all share urls on change" do before :each do product.custom_permalink = SecureRandom.alphanumeric(5) product.save! @new_custom_permalink = SecureRandom.alphanumeric(5) end def visit_product_and_update_custom_permalink(product) visit edit_link_path(product.unique_permalink) custom_permalink_input.set("").set(@new_custom_permalink) save_change end def get_new_custom_permalink_url(subpath: "", query_params: {}) base_url = "#{seller.subdomain_with_protocol}/l/#{@new_custom_permalink}" base_url_with_subpath = subpath == "" ? base_url : "#{base_url}/#{js_style_encode_uri_component(subpath)}" query_params_string = URI.encode_www_form(query_params) full_url = query_params_string == "" ? base_url_with_subpath : "#{base_url_with_subpath}?#{query_params_string}" full_url end it "changes membership tier share url" do @membership_product = create(:membership_product, user: seller) first_tier = @membership_product.tier_category.variants.first first_tier.name = "First Tier" first_tier.save! visit_product_and_update_custom_permalink(@membership_product) within tier_rows[0] do expect(page).to have_link("Share", href: get_new_custom_permalink_url(query_params: { option: first_tier.external_id })) end end it "changes digital version share url" do @variant_category = product.variant_categories.new @variant_category.title = "Version Group 1" @variant_option = @variant_category.variants.new @variant_option.product_files << product.product_files.alive.first @variant_option.name = "Group 1 Version 1" @variant_option.save visit_product_and_update_custom_permalink(product) within version_rows[0] do within version_option_rows[0] do expect(page).to have_link("Share", href: get_new_custom_permalink_url(query_params: { option: @variant_option.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/products/edit/membership_tiers_spec.rb
spec/requests/products/edit/membership_tiers_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Product Edit Memberships", type: :system, js: true) do include ProductTieredPricingHelpers include ProductEditPageHelpers def reorder_rows(row:, place_before:) row.find("[aria-grabbed='false']").drag_to place_before end let(:seller) { create(:named_seller) } include_context "with switching account to user as admin for seller" describe "memberships" do before do @product = create(:membership_product, user: seller) create(:membership_purchase, link: @product, variant_attributes: [@product.default_tier]) end it "displays the number of active supporters for each tier", :sidekiq_inline, :elasticsearch_wait_for_refresh do visit edit_link_path(@product.unique_permalink) expect(tier_rows[0]).to have_text "1 supporter" end it "allows user to update product" do visit edit_link_path(@product.unique_permalink) new_name = "Slot machine" fill_in("Name", with: new_name, match: :first) save_change expect(@product.reload.name).to eq new_name end it "allows creator to update duration" do visit edit_link_path(@product.unique_permalink) check "Automatically end memberships after a number of months" fill_in("Number of months", with: 18) expect do save_change end.to(change { @product.reload.duration_in_months }.to(18)) uncheck "Automatically end memberships after a number of months" expect do save_change end.to(change { @product.reload.duration_in_months }.to(nil)) end it "allows creator to update duration of a membership product" do visit edit_link_path(@product.unique_permalink) check "Automatically end memberships after a number of months" fill_in("Number of months", with: 18) expect do save_change end.to(change { @product.reload.duration_in_months }.to(18)) end it "allows creator to share all posts with new members" do visit edit_link_path(@product.unique_permalink) check "New members will get access to all posts you have published" expect do save_change end.to(change { @product.reload.should_show_all_posts }.to(true)) end it "allows creator to enable a free trial and defaults to one week" do visit edit_link_path(@product.unique_permalink) check "Offer a free trial" in_preview do expect(page).to have_text "All memberships include a 1 week free trial" end save_change @product.reload expect(@product.free_trial_enabled?).to eq true expect(@product.free_trial_duration_amount).to eq 1 expect(@product.free_trial_duration_unit).to eq "week" end it "allows creator to enable a one month free trial" do visit edit_link_path(@product.unique_permalink) check "Offer a free trial" select "one month", from: "Charge members after" in_preview do expect(page).to have_text "All memberships include a 1 month free trial" end save_change @product.reload expect(@product.free_trial_enabled?).to eq true expect(@product.free_trial_duration_amount).to eq 1 expect(@product.free_trial_duration_unit).to eq "month" end context "changing an existing free trial" do before do @product.update!(free_trial_enabled: true, free_trial_duration_amount: 1, free_trial_duration_unit: "month") end it "allows creator to disable a free trial" do visit edit_link_path(@product.unique_permalink) in_preview do expect(page).to have_text "All memberships include a 1 month free trial" end uncheck "Offer a free trial" in_preview do expect(page).not_to have_text "All memberships include" end save_change @product.reload expect(@product.free_trial_enabled?).to eq false expect(@product.free_trial_duration_amount).to be_nil expect(@product.free_trial_duration_unit).to be_nil end it "allows creator to change the free trial duration" do visit edit_link_path(@product.unique_permalink) select "one week", from: "Charge members after" in_preview do expect(page).to have_text "All memberships include a 1 week free trial" end save_change @product.reload expect(@product.free_trial_enabled?).to eq true expect(@product.free_trial_duration_amount).to eq 1 expect(@product.free_trial_duration_unit).to eq "week" end end describe "cancellation discount" do context "when cancellation discounts are enabled" do before do Feature.activate_user(:cancellation_discounts, seller) @product.alive_variants.first.prices.first.update!(price_cents: 500) end it "allows the seller to create a cancellation discount" do visit edit_link_path(@product.unique_permalink) find_field("Offer a cancellation discount", checked: false).check fill_in "Fixed amount", with: 1 save_change cancellation_discount = @product.cancellation_discount_offer_code expect(cancellation_discount.user).to eq seller expect(cancellation_discount.products).to eq [@product] expect(cancellation_discount.amount_cents).to eq 100 expect(cancellation_discount.amount_percentage).to be_nil expect(cancellation_discount.duration_in_billing_cycles).to be_nil refresh expect(page).to have_checked_field("Offer a cancellation discount") expect(page).to have_field("Fixed amount", with: "1") choose "Percentage" fill_in "Percentage", with: 10 save_change cancellation_discount.reload expect(cancellation_discount).to eq(@product.cancellation_discount_offer_code) expect(cancellation_discount.amount_percentage).to eq 10 expect(cancellation_discount.amount_cents).to be_nil refresh find_field("Offer a cancellation discount", checked: true).uncheck save_change expect(@product.cancellation_discount_offer_code).to be_nil expect(cancellation_discount.reload).to be_deleted end end context "when cancellation discounts are disabled" do it "does not show the cancellation discount selector" do visit edit_link_path(@product.unique_permalink) expect(page).not_to have_field "Offer a cancellation discount" end end end end describe "membership tiers" do before do @product = create(:membership_product, user: seller) end it "starts out with one tier, named Untitled" do visit edit_link_path(@product.unique_permalink) expect(tier_rows.size).to eq 1 expect(tier_rows[0]).to have_text "Untitled" end it "has a valid share url" do first_tier = @product.tier_category.variants.first first_tier.update!(name: "First Tier") visit edit_link_path(@product.unique_permalink) within tier_rows[0] do new_window = window_opened_by { click_on "Share" } within_window new_window do expect(page).to have_text(@product.name) expect(page).to have_text(@product.user.name) expect(page).to have_radio_button(first_tier.name) end end end it "allows to create more tiers" do visit edit_link_path(@product.unique_permalink) click_on "Add tier" within tier_rows[1] do fill_in "Name", with: "Premium" check "Toggle recurrence option: Monthly" fill_in "Amount monthly", with: 3 end save_change expect(@product.variant_categories.first.variants.alive.size).to eq 2 expect(@product.variant_categories.first.variants.alive.last.name).to eq "Premium" end it "allows to edit quantity limit" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do fill_in "Maximum number of active supporters", with: "250" end save_change expect(@product.variant_categories.first.variants.alive.first.max_purchase_count).to eq 250 end context "when membership has rich content" do let(:membership_product) { create(:membership_product_with_preset_tiered_pricing, user: seller) } before do create(:rich_content, entity: membership_product.alive_variants.first, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is tier-level rich content 1", "type" => "text" }] }]) create(:rich_content, entity: membership_product.alive_variants.second, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is tier-level rich content 2", "type" => "text" }] }]) end it "allows deleting a tier with a confirmation dialog" do visit edit_link_path(membership_product.unique_permalink) within tier_rows[0] do click_on "Remove" end within_modal "Remove First Tier?" do expect(page).to have_text("If you delete this tier, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest tier as a fallback. If no tier exists, they will see the product-level content.") click_on "No, cancel" end save_change refresh expect(membership_product.alive_variants.size).to eq 2 within tier_rows[0] do click_on "Remove" end within_modal "Remove First Tier?" do expect(page).to have_text("If you delete this tier, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest tier as a fallback. If no tier exists, they will see the product-level content.") click_on "Yes, remove" end save_change expect(membership_product.alive_variants.pluck(:name)).to contain_exactly("Second Tier") end end context "when setting quantity limit" do before do tier_category = @product.tier_category first_tier = @product.default_tier second_tier = create(:variant, variant_category: tier_category, name: "2nd Tier") create(:variant_price, variant: second_tier, recurrence: @product.subscription_duration) # first tier has 2 active subscriptions, 1 inactive subscription, and 1 non-subscription purchase active_subscription = create(:subscription, link: @product) active_subscription2 = create(:subscription, link: @product) create(:purchase, link: @product, variant_attributes: [first_tier], subscription: active_subscription, is_original_subscription_purchase: true) create(:purchase, link: @product, variant_attributes: [first_tier], subscription: active_subscription2, is_original_subscription_purchase: true) inactive_subscription = create(:subscription, link: @product, deactivated_at: Time.current) create(:purchase, link: @product, variant_attributes: [first_tier], subscription: inactive_subscription, is_original_subscription_purchase: true) create(:purchase, link: @product, variant_attributes: [first_tier]) # second tier has 1 active subscription, 1 inactive subscription, and 1 non-subscription purchase active_subscription = create(:subscription, link: @product) create(:purchase, link: @product, variant_attributes: [second_tier], subscription: active_subscription, is_original_subscription_purchase: true) create(:purchase, link: @product, variant_attributes: [second_tier], subscription: active_subscription2, is_original_subscription_purchase: true) inactive_subscription = create(:subscription, link: @product, deactivated_at: Time.current) create(:purchase, link: @product, variant_attributes: [second_tier], subscription: inactive_subscription, is_original_subscription_purchase: true) create(:purchase, link: @product, variant_attributes: [second_tier]) end it "prohibits setting quantity limit lower than current active subscriptions + non-subscription purchases" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do fill_in "Maximum number of active supporters", with: "2" end save_change(expect_message: "You have chosen an amount lower than what you have already sold. Please enter an amount greater than 3.") expect(@product.variant_categories.first.variants.alive.first.max_purchase_count).to be_nil end it "excludes inactive subscriptions and purchases of other tiers from the current purchase count" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do fill_in "Maximum number of active supporters", with: "3" end save_change expect(@product.variant_categories.first.variants.alive.first.max_purchase_count).to eq 3 end end it "allows to re-order tiers" do visit edit_link_path(@product.unique_permalink) click_on "Add tier" within tier_rows[1] do fill_in "Name", with: "Second tier" check "Toggle recurrence option: Monthly" fill_in "Amount monthly", with: 3 end reorder_rows row: tier_rows[0], place_before: tier_rows[1] save_change expect(@product.tier_category.variants.reload.alive.in_order.pluck(:name)).to eq ["Second tier", "Untitled"] end it "allows to delete tiers" do visit edit_link_path(@product.unique_permalink) click_on "Add tier" within tier_rows[1] do fill_in "Name", with: "New" check "Toggle recurrence option: Monthly" fill_in "Amount monthly", with: 3 end save_change within tier_rows[0] do click_on "Remove" end within_modal "Remove Untitled?" do expect(page).to have_text("If you delete this tier, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest tier as a fallback. If no tier exists, they will see the product-level content.") click_on "Yes, remove" end save_change expect(@product.variant_categories.first.variants.alive.size).to eq 1 expect(@product.variant_categories.first.variants.alive.first.name).to eq "New" end it "does not allow to save with zero tiers" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do click_on "Remove" end within_modal "Remove Untitled?" do expect(page).to have_text("If you delete this tier, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest tier as a fallback. If no tier exists, they will see the product-level content.") click_on "Yes, remove" end save_change(expect_message: "Memberships should have at least one tier.") expect(@product.variant_categories.first.variants.alive.size).to eq 1 end describe "pricing" do it "allows to enable, disable, and change recurrence values for each tier" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do fill_in "Amount monthly", with: 3 check "Toggle recurrence option: Quarterly" # defaults to monthly x 3 expect(page).to have_field("Amount quarterly", with: "9") fill_in "Amount quarterly", with: 5 end save_change expect(tier_pricing_values(@product)).to eq [ { name: "Untitled", pwyw: false, values: { "monthly" => { enabled: true, price_cents: 300, price: "3", suggested_price_cents: nil, }, "quarterly" => { enabled: true, price_cents: 500, price: "5", suggested_price_cents: nil, }, "biannually" => { enabled: false }, "yearly" => { enabled: false }, "every_two_years" => { enabled: false }, } } ] within tier_rows[0] do uncheck "Toggle recurrence option: Quarterly" check "Toggle recurrence option: Yearly" fill_in "Amount yearly", with: 13 end save_change expect(tier_pricing_values(@product)).to eq [ { name: "Untitled", pwyw: false, values: { "monthly" => { enabled: true, price_cents: 300, price: "3", suggested_price_cents: nil, }, "quarterly" => { enabled: false }, "biannually" => { enabled: false }, "yearly" => { enabled: true, price_cents: 1300, price: "13", suggested_price_cents: nil, }, "every_two_years" => { enabled: false }, } } ] end it "does not allow to save if not all tiers have the same recurrences enabled" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do fill_in "Amount monthly", with: 3 end click_on "Add tier" within tier_rows[1] do fill_in "Name", with: "Second tier" check "Toggle recurrence option: Monthly" fill_in "Amount monthly", with: 3 check "Toggle recurrence option: Quarterly" fill_in "Amount quarterly", with: 3 end save_change(expect_message: "All tiers must have the same set of payment options.") end it "does not allow to save if any tier is missing a price for the product's default recurrence" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do uncheck "Toggle recurrence option: Monthly" end save_change(expect_message: "Please provide a price for the default payment option.") end context "with pay-what-you-want enabled" do it "allows to enable pay-what-you-want on a per-tier basis and enter suggested values per each enabled recurrence" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do fill_in "Amount monthly", with: 3 end click_on "Add tier" within tier_rows[1] do fill_in "Name", with: "Second tier" check "Toggle recurrence option: Monthly" fill_in "Amount monthly", with: 5 check "Allow customers to pay what they want" fill_in "Suggested amount monthly", with: 10 end save_change expect(tier_pricing_values(@product)).to eq [ { name: "Untitled", pwyw: false, values: { "monthly" => { enabled: true, price_cents: 300, price: "3", suggested_price_cents: nil, }, "quarterly" => { enabled: false }, "biannually" => { enabled: false }, "yearly" => { enabled: false }, "every_two_years" => { enabled: false }, } }, { name: "Second tier", pwyw: true, values: { "monthly" => { enabled: true, price_cents: 500, price: "5", suggested_price_cents: 1000, suggested_price: "10" }, "quarterly" => { enabled: false }, "biannually" => { enabled: false }, "yearly" => { enabled: false }, "every_two_years" => { enabled: false }, } } ] end it "requires that suggested price is >= price" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do fill_in "Amount monthly", with: 10 check "Allow customers to pay what they want" fill_in "Suggested amount monthly", with: 9 end save_change(expect_message: "The suggested price you entered was too low.") end it "automatically enables PWYW and disables toggle when tier prices are 0" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do check "Toggle recurrence option: Monthly" fill_in "Amount monthly", with: 0 pwyw_toggle = find_field("Allow customers to pay what they want", disabled: true) expect(page).to have_content("Free tiers require a pay what they want price.") expect(pwyw_toggle).to be_checked fill_in "Amount monthly", with: 10 expect(page).not_to have_content("Free tiers require a pay what they want price.") pwyw_toggle = find_field("Allow customers to pay what they want") expect(pwyw_toggle).to be_checked expect(pwyw_toggle).not_to be_disabled fill_in "Amount monthly", with: 0 check "Toggle recurrence option: Quarterly" fill_in "Amount quarterly", with: 0 expect(page).to have_content("Free tiers require a pay what they want price.") pwyw_toggle = find_field("Allow customers to pay what they want", disabled: true) expect(pwyw_toggle).to be_checked fill_in "Amount quarterly", with: 5 expect(page).not_to have_content("Free tiers require a pay what they want price.") pwyw_toggle = find_field("Allow customers to pay what they want") expect(pwyw_toggle).to be_checked expect(pwyw_toggle).not_to be_disabled end end end it "allows to change default recurrence in settings" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do check "Toggle recurrence option: Monthly" check "Toggle recurrence option: Quarterly" fill_in "Amount quarterly", with: 3 end select "every 3 months", from: "Default payment frequency" save_change expect(@product.reload.subscription_duration).to eq "quarterly" end describe "applying price changes to existing memberships" do let(:tier) { @product.tiers.first } it "allows applying price changes to existing memberships on that tier" do freeze_time do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do expect(page).not_to have_text "Effective date for existing customers" check "Apply price changes to existing customers" expect(page).not_to have_status(text: "You have scheduled a pricing update for existing customers on") expect(page).to have_text "Effective date for existing customers" end save_change expect(tier.apply_price_changes_to_existing_memberships).to eq true expect(tier.subscription_price_change_effective_date).to eq(Date.today + 7) expect(tier.subscription_price_change_message).to be_nil end end it "allows setting an effective date and custom message" do visit edit_link_path(@product.unique_permalink) effective_date = (7.days.from_now + 1.month).to_date.change(day: 12) within tier_rows[0] do check "Apply price changes to existing customers" fill_in "Effective date for existing customers", with: effective_date.strftime("%m%d%Y") set_rich_text_editor_input(find("[aria-label='Custom message']"), to_text: "hello") sleep(1) end save_change expect(tier.apply_price_changes_to_existing_memberships).to eq true expect(tier.subscription_price_change_effective_date).to eq effective_date expect(tier.subscription_price_change_message).to eq "<p>hello</p>" end it "does not allow setting an effective date less than 7 days in the future" do visit edit_link_path(@product.unique_permalink) within tier_rows[0] do check "Apply price changes to existing customers" fill_in "Effective date for existing customers", with: "01-01-2020\t" end expect(page).to have_text "The effective date must be at least 7 days from today" expect do click_on "Save changes" wait_for_ajax end.not_to change { tier.reload.subscription_price_change_effective_date } expect(page).to have_alert(text: "Validation failed: The effective date must be at least 7 days from today") within tier_rows[0] do fill_in "Effective date for existing customers", with: "01-01-#{Date.today.year + 2}\t" end expect(page).not_to have_text "The effective date must be at least 7 days from today" end it "allows turning off this setting" do tier.update!(apply_price_changes_to_existing_memberships: true, subscription_price_change_effective_date: 7.days.from_now.to_date, subscription_price_change_message: "<p>hello this is a description</p>") formatted_date = tier.subscription_price_change_effective_date.strftime("%B %-d, %Y") visit edit_link_path(@product.unique_permalink) within tier_rows[0] do expect(page).to have_alert(text: "You have scheduled a pricing update for existing customers on #{formatted_date}") uncheck "Apply price changes to existing customers" expect(page).not_to have_alert(text: "You have scheduled a pricing update for existing customers on #{formatted_date}") # displays the same values upon re-enabling check "Apply price changes to existing customers" expect(page).to have_alert(text: "You have scheduled a pricing update for existing customers on #{formatted_date}") expect(page).to have_field("Effective date for existing customers", with: tier.subscription_price_change_effective_date.iso8601[0..10]) expect(page).to have_text("hello this is a description") uncheck "Apply price changes to existing customers" end save_change tier.reload expect(tier.apply_price_changes_to_existing_memberships).to eq false expect(tier.subscription_price_change_effective_date).to be_nil expect(tier.subscription_price_change_message).to be_nil end describe "sample email" do before { tier.update!(apply_price_changes_to_existing_memberships: true, subscription_price_change_effective_date: 7.days.from_now.to_date) } it "allows sending a sample email when no attributes have changed" do mail = double("mail") expect(mail).to receive(:deliver_later) expect(CustomerLowPriorityMailer).to receive(:sample_subscription_price_change_notification). with(user: user_with_role_for_seller, tier:, effective_date: tier.subscription_price_change_effective_date, recurrence: "monthly", new_price: tier.prices.alive.find_by(recurrence: "monthly").price_cents, custom_message: nil). and_return(mail) visit edit_link_path(@product.unique_permalink) within tier_rows[0] do click_on "Get a sample" end expect(page).to have_alert(text: "Email sample sent! Check your email") end it "includes the edited price, effective date, and custom message if set" do effective_date = (7.days.from_now + 1.month).to_date.change(day: 12) new_price = 8_00 mail = double("mail") expect(mail).to receive(:deliver_later) expect(CustomerLowPriorityMailer).to receive(:sample_subscription_price_change_notification). with(user: user_with_role_for_seller, tier:, effective_date: effective_date.to_date, recurrence: "monthly", new_price:, custom_message: "<p>hello</p>"). and_return(mail) visit edit_link_path(@product.unique_permalink) within tier_rows[0] do fill_in "Amount monthly", with: new_price / 100 fill_in "Effective date for existing customers", with: effective_date.strftime("%m%d%Y") set_rich_text_editor_input(find("[aria-label='Custom message']"), to_text: "hello") sleep(1) click_on "Get a sample" end expect(page).to have_alert(text: "Email sample sent! Check your email") end it "defaults to a monthly $10 price if there is no price set" do mail = double("mail") expect(mail).to receive(:deliver_later) expect(CustomerLowPriorityMailer).to receive(:sample_subscription_price_change_notification). with(user: user_with_role_for_seller, tier:, effective_date: tier.subscription_price_change_effective_date, recurrence: "monthly", new_price: 10_00, custom_message: nil). and_return(mail) visit edit_link_path(@product.unique_permalink) within tier_rows[0] do uncheck "Toggle recurrence option: Monthly" click_on "Get a sample" end expect(page).to have_alert(text: "Email sample sent! Check your email") end it "shows an error message if error is raised", :realistic_error_responses do allow(CustomerLowPriorityMailer).to receive(:sample_subscription_price_change_notification).and_raise(StandardError) visit edit_link_path(@product.unique_permalink) within tier_rows[0] do click_on "Get a sample" end expect(page).to have_alert(text: "Error sending email") 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/products/edit/digital_versions_spec.rb
spec/requests/products/edit/digital_versions_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Product Edit Digital Versions", type: :system, js: true) do include ProductEditPageHelpers let(:seller) { create(:named_seller) } let!(:product) { create(:product_with_pdf_files_with_size, user: seller) } include_context "with switching account to user as admin for seller" describe "digital versions" do before :each do @variant_category = product.variant_categories.new @variant_category.title = "" @variant_option = @variant_category.variants.new @variant_option.product_files << product.product_files.alive.first @variant_option.name = "First Product Files Grouping" @variant_option.save! @variant_option_two = create(:variant, :with_product_file, variant_category: @variant_category, name: "Basic Bundle") end it "allows to edit price of digital version option" do visit edit_link_path(product.unique_permalink) within version_rows[0] do within version_option_rows[0] do fill_in "Additional amount", with: "9" end end save_change in_preview do expect(page).to have_text("$10") end expect(product.variant_categories.first.variants.alive.first.price_difference_cents).to eq 900 end it "does not change variant category price when changing version option prices" do visit edit_link_path(product.unique_permalink) within_section "Pricing", match: :first do expect(page).to have_field("Amount", with: "1") end within version_rows[0] do within version_option_rows[0] do fill_in "Additional amount", with: "9" end within version_option_rows[1] do fill_in "Additional amount", with: "9" end end save_change within_section "Pricing", match: :first do expect(page).to have_field("Amount", with: "1") end visit short_link_path(product) within_section @variant_option.name, match: :first do expect(page).to have_text("$10") end end it "allows to re-order options" do visit edit_link_path(product.unique_permalink) page.scroll_to version_rows[0], align: :center click_on "Add version" within version_rows[0] do within version_option_rows[2] do fill_in "Version name", with: "Second version" end # Fix flaky spec when the banner component is present. page.scroll_to version_option_rows[0].find("[aria-grabbed='false']"), align: :center version_option_rows[0].find("[aria-grabbed='false']").drag_to version_option_rows[1] end save_change expect(product.variant_categories.first.variants.reload.alive.in_order.pluck(:name)).to eq ["Basic Bundle", "First Product Files Grouping", "Second version"] end it "has a valid share URL" do visit edit_link_path(product.unique_permalink) within version_rows[0] do within version_option_rows[0] do new_window = window_opened_by { click_on("Share") } within_window new_window do expect(page).to have_text(product.name) expect(page).to have_text(product.user.name) expect(page).to have_radio_button(@variant_option.name) end end end end describe "deleting variant options" do before do create(:rich_content, entity: @variant_option, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is variant-level rich content 1", "type" => "text" }] }]) create(:rich_content, entity: @variant_option_two, description: [{ "type" => "paragraph", "content" => [{ "text" => "This is variant-level rich content 2", "type" => "text" }] }]) end it "deletes a variant option without purchases with a confirmation dialog" do visit edit_link_path(product.unique_permalink) within version_rows[0] do within version_option_rows[0] do click_on "Remove version" end end within_modal "Remove First Product Files Grouping?" do expect(page).to have_text("If you delete this version, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest version as a fallback. If no version exists, they will see the product-level content.") click_on "No, cancel" end save_change refresh expect(@variant_option.reload).to be_present within version_rows[0] do within version_option_rows[0] do click_on "Remove version" end end within_modal "Remove First Product Files Grouping?" do expect(page).to have_text("If you delete this version, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest version as a fallback. If no version exists, they will see the product-level content.") click_on "Yes, remove" end save_change expect(@variant_option.reload).to be_deleted end it "deletes a variant option with only test purchases" do create(:purchase, link: product, variant_attributes: [@variant_option], purchaser: seller, purchase_state: "test_successful") visit edit_link_path(product.unique_permalink) within version_rows[0] do within version_option_rows[0] do click_on "Remove version" end end within_modal "Remove First Product Files Grouping?" do expect(page).to have_text("If you delete this version, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest version as a fallback. If no version exists, they will see the product-level content.") click_on "Yes, remove" end save_change expect(@variant_option.reload).to be_deleted end it "deletes a variant option with non-test purchases" do create(:purchase, link: product, variant_attributes: [@variant_option], purchase_state: "successful") visit edit_link_path(product.unique_permalink) within version_rows[0] do within version_option_rows[0] do click_on "Remove version" end end within_modal "Remove First Product Files Grouping?" do expect(page).to have_text("If you delete this version, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest version as a fallback. If no version exists, they will see the product-level content.") click_on "Yes, remove" end save_change expect(@variant_option.reload).to be_deleted end it "deletes all variant options of a variant category" do visit edit_link_path(product.unique_permalink) within_section "Versions" do within version_option_rows[0] do click_on "Remove version" end within_modal "Remove First Product Files Grouping?" do expect(page).to have_text("If you delete this version, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest version as a fallback. If no version exists, they will see the product-level content.") click_on "Yes, remove" end within version_option_rows[0] do click_on "Remove version" end within_modal "Remove Basic Bundle?" do expect(page).to have_text("If you delete this version, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest version as a fallback. If no version exists, they will see the product-level content.") click_on "Yes, remove" end end save_change expect(@variant_option.reload).to be_deleted expect(@variant_option_two.reload).to be_deleted expect(@variant_category.reload).to be_deleted within_section "Versions" do expect(page).to_not have_text("First Product Files Grouping") expect(page).to_not have_text("Basic Bundle") expect(page).to have_button("Add version") end end it "deletes all variant options even if variant category title is not empty" do @variant_category.update!(title: "My Product Files Groupings") visit edit_link_path(product.unique_permalink) within_section "Versions" do within version_option_rows[0] do click_on "Remove version" end within_modal "Remove First Product Files Grouping?" do expect(page).to have_text("If you delete this version, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest version as a fallback. If no version exists, they will see the product-level content.") click_on "Yes, remove" end within version_option_rows[0] do click_on "Remove version" end within_modal "Remove Basic Bundle?" do expect(page).to have_text("If you delete this version, its associated content will be removed as well. Your existing customers who purchased it will see the content from the current cheapest version as a fallback. If no version exists, they will see the product-level content.") click_on "Yes, remove" end end save_change expect(@variant_option.reload).to be_deleted expect(@variant_option_two.reload).to be_deleted expect(@variant_category.reload).to be_deleted within_section "Versions" do expect(page).to_not have_text("First Product Files Grouping") expect(page).to_not have_text("Basic Bundle") expect(page).to have_button("Add version") 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/products/edit/covers_spec.rb
spec/requests/products/edit/covers_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Product Edit Covers", type: :system, js: true do include ProductEditPageHelpers def upload_image(filenames) click_on "Upload images or videos" page.attach_file(filenames.map { |filename| file_fixture(filename) }) do select_tab "Computer files" end end let(:seller) { create(:named_seller) } let!(:product) { create(:product_with_pdf_file, user: seller, size: 1024) } before do product.shipping_destinations << ShippingDestination.new( country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0 ) end include_context "with switching account to user as admin for seller" it "supports attaching covers" do visit edit_link_path(product.unique_permalink) upload_image(["test.png"]) wait_for_ajax sleep 1 select_disclosure "Add cover" do upload_image(["test-small.jpg"]) end wait_for_ajax within "[role=tablist][aria-label='Product covers']" do expect(page).to have_tab_button(count: 2) end end it "instantly previews product cover changes" do visit edit_link_path(product.unique_permalink) upload_image(["test.png"]) wait_for_ajax in_preview do expect(page).to have_selector("[aria-label='Product preview'] img") end end it "does not allow uploading invalid images" do visit edit_link_path(product.unique_permalink) upload_image(["disguised_html_script.png"]) allow_any_instance_of(ActiveStorage::Blob).to receive(:purge).and_return(nil) expect(page).to have_alert(text: "Could not process your preview, please try again.") end it "allows uploading valid image after trying an invalid one" do visit edit_link_path(product.unique_permalink) upload_image(["disguised_html_script.png"]) allow_any_instance_of(ActiveStorage::Blob).to receive(:purge).and_return(nil) expect(page).to have_alert(text: "Could not process your preview, please try again.") upload_image(["test-small.jpg"]) wait_for_ajax within "[role=tablist][aria-label='Product covers']" do expect(page).to have_tab_button(count: 1) end end it "allows uploading video files" do visit edit_link_path(product.unique_permalink) upload_image(["ScreenRecording.mov"]) wait_for_ajax within "[role=tablist][aria-label='Product covers']" do expect(page).to have_tab_button(count: 1) end end it("allows multiple images to be uploaded simultaneously") do visit edit_link_path(product.unique_permalink) upload_image(["test-small.jpg", "test.png"]) wait_for_ajax within "[role=tablist][aria-label='Product covers']" do expect(page).to have_tab_button(count: 2) end end it("does not allow more than 8 images to be uploaded simultaneously") do allow_any_instance_of(ActiveStorage::Blob).to receive(:purge).and_return(nil) visit edit_link_path(product.unique_permalink) upload_image([ "test-small.jpg", "test.png", "test.jpg", "test.gif", "smilie.png", "test-small.jpg", "test-small.png", "test-squashed.png", "Austin's Mojo.png" ]) wait_for_ajax expect(page).to have_alert(text: "Sorry, we have a limit of 8 previews. Please delete an existing one before adding another.") within "[role=tablist][aria-label='Product covers']" do expect(page).to have_tab_button(count: 8) end end describe "External links" do it "allows attaching embeds from a supported provider" do vcr_turned_on do VCR.use_cassette("Product Edit Covers - External links - Supported provider") do visit edit_link_path(product.unique_permalink) expect do within_section "Cover", section_element: "section" do click_on "Upload images or videos" select_tab "External link" fill_in "https://", with: "https://youtu.be/YE7VzlLtp-4" click_on "Upload" end expect(page).to_not have_alert(text: "A URL from an unsupported platform was provided. Please try again.") within "[role=tablist][aria-label='Product covers']" do expect(page).to have_selector("img[src='https://i.ytimg.com/vi/YE7VzlLtp-4/hqdefault.jpg']") end end.to change { AssetPreview.count }.by(1) end end end it "does not allow attaching embeds from unsupported providers" do vcr_turned_on do VCR.use_cassette("Product Edit Covers - External links - Unsupported provider") do visit edit_link_path(product.unique_permalink) expect do within_section "Cover", section_element: "section" do click_on "Upload images or videos" select_tab "External link" fill_in "https://", with: "https://www.tiktok.com/@soflofooodie/video/7164885074863787307" click_on "Upload" end expect(page).to have_alert(text: "A URL from an unsupported platform was provided. Please try again.") end.to_not change { AssetPreview.count } end end end end it "allows to re-order covers" do asset1 = create(:asset_preview, link: product) asset2 = create(:asset_preview, link: product) asset3 = create(:asset_preview, link: product) visit edit_link_path(product.unique_permalink) within "[role=tablist][aria-label='Product covers']" do preview_mini_node1 = all(:tab_button)[0] preview_mini_node2 = all(:tab_button)[1] preview_mini_node3 = all(:tab_button)[2] expect(preview_mini_node1).not_to be nil expect(preview_mini_node2).not_to be nil expect(preview_mini_node3).not_to be nil # Fix flaky spec when the banner component is present. page.scroll_to preview_mini_node3, align: :center # Drag the second cover to the end preview_mini_node2.drag_to preview_mini_node3 # Drag the second cover to the start preview_mini_node2.drag_to preview_mini_node1 tabs = all(:tab_button) expect(tabs[0].find("img")[:src]).to include(asset2.url) expect(tabs[1].find("img")[:src]).to include(asset1.url) expect(tabs[2].find("img")[:src]).to include(asset3.url) end save_change expect(product.reload.display_asset_previews.pluck(:id)).to eq [ asset2.id, asset1.id, asset3.id ] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/edit/calls_spec.rb
spec/requests/products/edit/calls_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Calls Edit", type: :system, js: true do def upload_image(filenames) click_on "Upload images or videos" page.attach_file(filenames.map { |filename| file_fixture(filename) }) do select_tab "Computer files" end end let(:seller) { create(:user, :eligible_for_service_products) } let(:call) { create(:call_product, user: seller) } include_context "with switching account to user as admin for seller" before { Feature.activate_user(:product_edit_react, seller) } it "supports attaching covers on calls without durations" do call = create(:call_product, user: seller, durations: []) visit edit_link_path(call.unique_permalink) upload_image(["test.png"]) wait_for_ajax sleep 1 select_disclosure "Add cover" do upload_image(["test-small.jpg"]) end wait_for_ajax within "[role=tablist][aria-label='Product covers']" do expect(page).to have_tab_button(count: 2) end end it "allows editing durations" do call = create(:call_product, user: seller, durations: []) visit edit_link_path(call.unique_permalink) click_on "Add duration" expect(page).to have_selector("h3", text: "Untitled") click_on "Save changes" expect(page).to have_alert(text: "Calls must have at least one duration") fill_in "Duration", with: 30 expect(page).to have_selector("h3", text: "30 minutes") fill_in "Description", with: "An epic call with me!" fill_in "Additional amount", with: 100 fill_in "Maximum number of purchases", with: 10 click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") thirty_minutes = call.alive_variants.first expect(thirty_minutes.name).to eq("30 minutes") expect(thirty_minutes.duration_in_minutes).to eq(30) expect(thirty_minutes.description).to eq("An epic call with me!") expect(thirty_minutes.price_difference_cents).to eq(10000) expect(thirty_minutes.max_purchase_count).to eq(10) refresh within "[role='listitem']", text: "30 minutes" do expect(page).to have_field("Duration", with: 30) expect(page).to have_field("Description", with: "An epic call with me!") expect(page).to have_field("Additional amount", with: "100") expect(page).to have_field("Maximum number of purchases", with: "10") click_on "Remove" end click_on "Yes, remove" click_on "Add duration" fill_in "Duration", with: 60 expect(page).to have_selector("h3", text: "60 minutes") click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(thirty_minutes.reload).to be_deleted sixty_minutes = call.reload.alive_variants.first expect(sixty_minutes.name).to eq("60 minutes") expect(sixty_minutes.duration_in_minutes).to eq(60) expect(sixty_minutes.description).to eq("") expect(sixty_minutes.price_difference_cents).to eq(0) expect(sixty_minutes.max_purchase_count).to eq(nil) end it "allows editing availabilities" do visit edit_link_path(call.unique_permalink) click_on "Add day of availability" within "[aria-label='Availability 1']" do fill_in "Date", with: "01/01/2024" find_field("From", with: "09:00").fill_in with: "1000AM" find_field("To", with: "17:00").fill_in with: "1100AM" end click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") availability1 = call.call_availabilities.first expect(availability1.start_time).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2024-01-01 10:00")) expect(availability1.end_time).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2024-01-01 11:00")) click_on "Add day of availability" within "[aria-label='1/2/2024']" do within "[aria-label='Availability 1']" do expect(page).to have_field("Date", with: "2024-01-02") find_field("From", with: "09:00").fill_in with: "1200PM" find_field("To", with: "17:00").fill_in with: "1300PM" click_on "Add hours" end within "[aria-label='Availability 2']" do expect(page).to_not have_button("Add hours") expect(page).to_not have_field("Date") find_field("From", with: "13:00").fill_in with: "1400PM" find_field("To", with: "14:00").fill_in with: "1500PM" end end within "[aria-label='1/1/2024']" do within "[aria-label='Availability 1']" do click_on "Delete hours" end end click_on "Save changes" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") expect { availability1.reload }.to raise_error(ActiveRecord::RecordNotFound) call.call_availabilities.reload availability2 = call.call_availabilities.first expect(availability2.start_time).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2024-01-02 12:00")) expect(availability2.end_time).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2024-01-02 13:00")) availability3 = call.call_availabilities.second expect(availability3.start_time).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2024-01-02 14:00")) expect(availability3.end_time).to eq(ActiveSupport::TimeZone[seller.timezone].parse("2024-01-02 15:00")) end it "allows editing call limitations" do visit edit_link_path(call.unique_permalink) expect(page).to have_field("Notice period", with: 3) find_field("Units", with: "hours", visible: false).find(:option, "minutes").select_option fill_in "Notice period", with: 1440 find_field("Daily limit", with: "").fill_in with: 5 # Outside click to trigger notice period field update click_on "Save changes" expect(page).to have_select("Units", selected: "days", visible: false) expect(page).to have_field("Notice period", with: 1) expect(page).to have_alert(text: "Changes saved!") call_limitation_info = call.call_limitation_info.reload expect(call_limitation_info.minimum_notice_in_minutes).to eq(1440) expect(call_limitation_info.maximum_calls_per_day).to eq(5) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/edit/edit_spec.rb
spec/requests/products/edit/edit_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Product Edit Scenario", type: :system, js: true) do include ManageSubscriptionHelpers include ProductEditPageHelpers let(:seller) { create(:named_seller) } let!(:product) { create(:product_with_pdf_file, user: seller, size: 1024) } before :each do product.shipping_destinations << ShippingDestination.new( country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0 ) end include_context "with switching account to user as admin for seller" it "allows a Gumroad admin to view a seller's product edit page" do product = create(:product_with_digital_versions) admin = create(:admin_user) login_as(admin) visit edit_link_path(product.unique_permalink) expect(page).to have_text product.name end it "allows user to update their custom permalinks and then immediately view their products" do visit edit_link_path(product.unique_permalink) fill_in product.unique_permalink, with: "woof" save_change end describe "Custom domain" do let(:valid_domain) { "valid-domain.com" } let(:invalid_domain) { "invalid-domain.com" } it "saves a valid custom domain" do expect(CustomDomainVerificationService) .to receive(:new) .twice .with(domain: valid_domain) .and_return(double(process: true)) visit edit_link_path(product.unique_permalink) fill_in "Custom domain", with: valid_domain click_on "Verify" wait_for_ajax expect(page).to have_text("valid-domain.com domain is correctly configured!") save_change expect(product.custom_domain.domain).to eq("valid-domain.com") expect(product.custom_domain.verified?).to eq(true) end it "shows a validation error for an invalid domain" do expect(CustomDomainVerificationService) .to receive(:new) .with(domain: invalid_domain) .and_return(double(process: false)) visit edit_link_path(product.unique_permalink) fill_in "Custom domain", with: invalid_domain expect do click_on "Save changes" wait_for_ajax end.to change { product.reload.custom_domain&.domain }.from(nil).to(invalid_domain) expect(product.reload.custom_domain.failed_verification_attempts_count).to eq(0) expect(product.custom_domain.verified?).to eq(false) visit edit_link_path(product.unique_permalink) expect(page).to have_text("Domain verification failed. Please make sure you have correctly configured the DNS" \ " record for invalid-domain.com.") end it "does not enable the verify button for an empty domain" do visit edit_link_path(product.unique_permalink) fill_in "Custom domain", with: " " expect(page).not_to have_button("Verify") end end it "allows users to edit their physical product's content" do product.update!(is_physical: true, require_shipping: true) visit edit_link_path(product.unique_permalink) + "/content" select_disclosure "Upload files" do attach_product_file(file_fixture("Alice's Adventures in Wonderland.pdf")) end expect(page).to have_embed(name: "Alice's Adventures in Wonderland") wait_for_file_embed_to_finish_uploading(name: "Alice's Adventures in Wonderland") save_change file = product.reload.alive_product_files.sole expect(file.is_linked_to_existing_file).to eq false rich_content = [{ "type" => "fileEmbed", "attrs" => a_hash_including({ "id" => file.external_id }) }, { "type" => "paragraph" }] expect(product.rich_contents.alive.sole.description).to match rich_content select_tab "Product" click_on "Add version" click_on "Add version" within_section "Versions" do all(:field, "Name").last.set "Version 2" end select_tab "Content" find(:combo_box, "Select a version").click uncheck "Use the same content for all versions" find(:combo_box, "Select a version").click select_combo_box_option "Version 2", from: "Select a version" rich_text_editor = find("[contenteditable=true]") rich_text_editor.send_keys "Text!" save_change expect(product.rich_contents.alive.count).to eq 0 variants = product.alive_variants rich_content[0]["attrs"] = a_hash_including({ "id" => variants.first.alive_product_files.sole.external_id }) expect(variants.first.rich_contents.alive.sole.description).to match rich_content rich_content[1]["content"] = [{ "type" => "text", "text" => "Text!" }] expect(variants.last.rich_contents.alive.sole.description).to match rich_content end it "allows creating and deleting an upsell in the product description" do product = create(:product, user: seller, name: "Sample product", price_cents: 1000) create(:purchase, :with_review, link: product) visit edit_link_path(product.unique_permalink) set_rich_text_editor_input(find("[aria-label='Description']"), to_text: "Hi there!") 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" within("[aria-label='Description']") do within_section "Sample product", section_element: :article do expect(page).to have_text("5.0 (1)", normalize_ws: true) expect(page).to have_text("$10 $9") end end 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]) product.reload expect(product.description).to eq("<p>Hi there!</p><upsell-card productid=\"#{product.external_id}\" discount='{\"type\":\"fixed\",\"cents\":100}' id=\"#{upsell.external_id}\"></upsell-card>") set_rich_text_editor_input(find("[aria-label='Description']"), to_text: "") click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") upsell.reload expect(upsell.deleted?).to be(true) expect(upsell.offer_code.deleted?).to be(true) product.reload expect(product.description).to eq("<p><br></p>") end it "allows creating and deleting an upsell with variants in the product description" do product = create(:product_with_digital_versions_with_price_difference_cents, user: seller, name: "Sample product", price_cents: 1000) variant1 = product.alive_variants.first variant2 = product.alive_variants.last create(:purchase, :with_review, link: product) visit edit_link_path(product.unique_permalink) set_rich_text_editor_input(find("[aria-label='Description']"), to_text: "Hi there!") select_disclosure "Insert" do click_on "Upsell" end # The product itself should be listed but disabled, variants listed with icon within_modal do find(:combo_box, "Product").click product_option = find("[role='option']", text: "Sample product", exact_text: true) expect(product_option).not_to have_selector("span.icon.icon-arrow-right-reply"); # icon for variant variant1_option = find("[role='option']", text: "Sample product (#{variant1.name})") expect(variant1_option).to have_selector("span.icon.icon-arrow-right-reply"); # icon for variant variant2_option = find("[role='option']", text: "Sample product (#{variant2.name})") expect(variant2_option).to have_selector("span.icon.icon-arrow-right-reply"); # icon for variant end # When searching, only variants should appear, not the product itself, and no icon within_modal do fill_in "Product", with: "Sample product" expect(page).not_to have_selector("[role='option']", text: "Sample product", exact_text: true) variant1_option = find("[role='option']", text: "Sample product (#{variant1.name})") expect(variant1_option).not_to have_selector("span.icon.icon-arrow-right-reply"); # icon for variant variant2_option = find("[role='option']", text: "Sample product (#{variant2.name})") expect(variant2_option).not_to have_selector("span.icon.icon-arrow-right-reply"); # icon for variant end # Select the first variant select_combo_box_option search: "Sample product (#{variant1.name})", from: "Product" check "Add a discount to the offered product" choose "Fixed amount" discount_amount_cents = 100 discount_amount = discount_amount_cents / 100.0 fill_in "Fixed amount", with: discount_amount click_on "Insert" within_section "Sample product", section_element: :article do expect(page).to have_selector("span", text: "(#{variant1.name})") expect(page).to have_text("5.0 (1)", normalize_ws: true) price_cents = variant1.price_difference_cents + product.price_cents price = price_cents / 100 discounted_price = price_cents - discount_amount_cents discounted_price = discounted_price / 100 expect(page).to have_text("$#{price} $#{discounted_price}") end click_on "Save" expect(page).to have_alert(text: "Changes saved!") upsell = Upsell.last expect(upsell.product_id).to eq(product.id) expect(upsell.variant_id).to eq(variant1.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]) product.reload expect(product.description).to eq("<p>Hi there!</p><upsell-card productid=\"#{product.external_id}\" variantid=\"#{variant1.external_id}\" discount='{\"type\":\"fixed\",\"cents\":100}' id=\"#{upsell.external_id}\"></upsell-card>") set_rich_text_editor_input(find("[aria-label='Description']"), to_text: "") click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") upsell.reload expect(upsell.deleted?).to be(true) expect(upsell.offer_code.deleted?).to be(true) product.reload expect(product.description).to eq("<p><br></p>") end it "allows creating and deleting an upsell in the product rich content" do 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_tab "Content" set_rich_text_editor_input(find("[aria-label='Content editor']"), to_text: "Hi there!") 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" within_section "Sample product", section_element: :article do expect(page).to have_text("5.0 (1)", normalize_ws: true) expect(page).to have_text("$10 $9") end 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]) product.reload expect(product.rich_contents.alive.map(&:description)).to eq( [ [ { "type" => "paragraph", "content" => [{ "text" => "Hi there!", "type" => "text" }] }, { "type" => "upsellCard", "attrs" => { "id" => upsell.external_id, "discount" => { "type" => "fixed", "cents" => 100 }, "productId" => product.external_id, "variantId" => nil } } ] ] ) refresh set_rich_text_editor_input(find("[aria-label='Content editor']"), to_text: "") click_on "Save" wait_for_ajax expect(page).to have_alert(text: "Changes saved!") upsell.reload expect(upsell.deleted?).to be(true) expect(upsell.offer_code.deleted?).to be(true) product.reload expect(product.rich_contents.alive.map(&:description)).to eq( [ [ { "type" => "paragraph" } ] ] ) end it "displays video transcoding notice" do product = create(:product_with_video_file, user: seller) video_file = product.product_files.first create(:rich_content, entity: product, description: [{ "type" => "fileEmbed", "attrs" => { "id" => video_file.external_id, "uid" => SecureRandom.uuid } }]) create(:transcoded_video, streamable: video_file, original_video_key: video_file.s3_key, state: "processing") visit edit_link_path(product) + "/content" within find_embed(name: video_file.display_name) do expect(page).to have_text("Transcoding in progress") end video_file.transcoded_videos.first.mark_completed refresh within find_embed(name: video_file.display_name) do expect(page).not_to have_text("Transcoding in progress") end end it "allows to edit suggested price of PWYW products" do visit edit_link_path(product.unique_permalink) fill_in "Amount", with: "20" check "Allow customers to pay what they want" fill_in "Suggested amount", with: "50" save_change expect(page).to have_text("$20+") product.reload expect(product.suggested_price_cents).to be(50_00) visit edit_link_path(product.unique_permalink) expect(page).to have_field("Suggested amount", with: "50") find_field("Suggested amount", with: "50").fill_in with: "" click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") expect(product.reload.suggested_price_cents).to be_nil end it "allows user to update name and price", :sidekiq_inline, :elasticsearch_wait_for_refresh do visit edit_link_path(product.unique_permalink) new_name = "Slot machine" fill_in("Name", with: new_name) fill_in("Amount", with: 777) save_change expect(product.reload.name).to eq new_name expect(product.price_cents).to eq 77_700 document = EsClient.get(id: product.id, index: Link.index_name)["_source"] expect(document["name"]).to eq(new_name) expect(document["price_cents"]).to eq(77_700) end it "allows updating installment plans for paid product" do product.installment_plan&.destroy! visit edit_link_path(product.unique_permalink) within_section "Pricing" do fill_in "Amount", with: 100 check "Allow customers to pay in installments" fill_in "Number of installments", with: 3 end save_change expect(product.reload.installment_plan.number_of_installments).to eq(3) within_section "Pricing" do fill_in "Amount", with: 100 check "Allow customers to pay in installments" fill_in "Number of installments", with: 4 end save_change expect(product.reload.installment_plan.number_of_installments).to eq(4) within_section "Pricing" do fill_in "Amount", with: 0 end save_change expect(product.reload.installment_plan).to be_nil end it "allows user to update custom permalink and limit product sales" do visit edit_link_path(product.unique_permalink) new_custom_permalink = "cba" new_limit = 12 fill_in(product.unique_permalink, with: new_custom_permalink) check "Limit product sales" fill_in("Maximum number of purchases", with: new_limit) expect do expect do save_change product.reload end.to(change { product.custom_permalink }.to(new_custom_permalink)) end.to(change { product.max_purchase_count }.to(new_limit)) uncheck "Limit product sales" expect do save_change product.reload end.to(change { product.max_purchase_count }.to(nil)) end it "allows a product to be edited and published without files" do product = create(:product, user: seller, draft: true, purchase_disabled_at: Time.current) visit edit_link_path(product.unique_permalink) expect(product.has_files?).to be(false) fill_in "Amount", with: 1 click_on "Save and continue" expect(page).to have_alert(text: "Changes saved!") click_on "Publish and continue" expect(page).to have_alert(text: "Published!") expect(page).to have_button "Unpublish" expect(product.reload.alive?).to be(true) end it "does not allow publishing when creator's email is empty" do allow_any_instance_of(User).to receive(:email).and_return("") product = create(:product, user: seller, draft: true, purchase_disabled_at: Time.current) visit edit_link_path(product.unique_permalink) + "/content" click_on "Publish and continue" within :alert, text: "To publish a product, we need you to have an email. Set an email to continue." do expect(page).to have_link("Set an email", href: settings_main_url(host: UrlService.domain_with_protocol)) end expect(page).to have_current_path(edit_link_path(product.unique_permalink) + "/content") expect(page).to have_button "Publish and continue" expect(product.reload.alive?).to be(false) end describe "tier supporters count", :sidekiq_inline, :elasticsearch_wait_for_refresh do before do shared_setup login_as(@product.user) end context "without any tier members subscribed" do it "does not display a text count" do visit edit_link_path(@product.unique_permalink) wait_for_ajax expect(page).to_not have_text("0 supporters") end end context "when one tier member subscribed" do before do create_subscription(product_price: @monthly_product_price, tier: @original_tier, tier_price: @original_tier_monthly_price) index_model_records(Purchase) end it "shows singular supporter version with count" do visit edit_link_path(@product.unique_permalink) wait_for_ajax expect(page).to have_text("1 supporter") end end context "when multiple tier members subscribed" do before do create_subscription(product_price: @monthly_product_price, tier: @original_tier, tier_price: @original_tier_monthly_price) create_subscription(product_price: @monthly_product_price, tier: @original_tier, tier_price: @original_tier_monthly_price) index_model_records(Purchase) end it "shows pluralized supporter version with count" do visit edit_link_path(@product.unique_permalink) wait_for_ajax expect(page).to have_text("2 supporters") end end end it "allows creator to show or hide the sales count" do index_model_records(Purchase) product = create(:product, user: seller) product.product_files << create(:product_file) expect(product.should_show_sales_count).to eq false visit edit_link_path(product.unique_permalink) check "Publicly show the number of sales on your product page" expect(page).to have_text("0 sales") expect do save_change end.to(change { product.reload.should_show_sales_count }.to(true)) uncheck "Publicly show the number of sales on your product page" expect(page).not_to have_text("0 sales") expect do save_change end.to(change { product.reload.should_show_sales_count }.to(false)) end it "allows creator to limit the number of sales" do product = create(:product, user: seller) product.product_files << create(:product_file) expect(product.quantity_enabled).to eq false visit edit_link_path(product.unique_permalink) expect(page).not_to have_field("Quantity") check "Allow customers to choose a quantity" expect(page).to have_field("Quantity") expect do save_change end.to(change { product.reload.quantity_enabled }.to(true)) uncheck "Allow customers to choose a quantity" expect(page).not_to have_field("Quantity") expect do save_change end.to(change { product.reload.quantity_enabled }.to(false)) end it "allows creator to show or hide the supporters count" do index_model_records(Purchase) product = create(:membership_product, user: seller) expect(product.should_show_sales_count).to eq false visit edit_link_path(product.unique_permalink) check "Publicly show the number of members on your product page" expect(page).to have_text("0 members") expect do save_change end.to(change { product.reload.should_show_sales_count }.to(true)) uncheck "Publicly show the number of members on your product page" expect(page).not_to have_text("0 members") expect do save_change end.to(change { product.reload.should_show_sales_count }.to(false)) end describe "membership ui vs non membership ui" do before do @non_membership_product = create(:physical_product) user = @non_membership_product.user login_as user @membership_product = create(:membership_product, user:) end it "doesn't show the option to show supporter count for non-membership products" do visit "/products/#{@non_membership_product.unique_permalink}/edit" wait_for_ajax expect(page).not_to have_text("Publicly show the number of members on your product page") end it "shows the option to show sales count for non-membership products" do visit "/products/#{@non_membership_product.unique_permalink}/edit" wait_for_ajax expect(page).to have_text("Publicly show the number of sales on your product page") end it "shows the option to show supporter count for membership products" do visit "/products/#{@membership_product.unique_permalink}/edit" wait_for_ajax expect(page).to have_text("Publicly show the number of members on your product page") end it "doesn't show the option to show sales count for membership products" do visit "/products/#{@membership_product.unique_permalink}/edit" wait_for_ajax expect(page).not_to have_text("Publicly show the number of sales on your product page") end it "doesn't show the option to change currency code for membership products" do visit "/products/#{@membership_product.unique_permalink}/edit" wait_for_ajax expect(page).not_to have_select("Currency", visible: :all) end end describe "discover notices" do let(:recommendable_seller) { create(:recommendable_user, name: "Seller") } let(:recommendable_product) { create(:product, :recommendable, user: recommendable_seller, name: "product 1") } it "shows eligibility notice until dismissed and success notice if recommendable product" do expect(product.recommendable?).to be(false) visit edit_link_path(product.unique_permalink) + "/share" expect(page).not_to have_status(text: "#{product.name} is listed on Gumroad Discover.") click_on "Close" expect(page).not_to have_status(text: "To appear on Gumroad Discover, make sure to meet all the") visit edit_link_path(product.unique_permalink) + "/share" expect(page).not_to have_status(text: "To appear on Gumroad Discover, make sure to meet all the") login_as(recommendable_seller) expect(recommendable_product.recommendable?).to be(true) visit edit_link_path(recommendable_product.unique_permalink) + "/share" expect(page).to have_status(text: "#{recommendable_product.name} is listed on Gumroad Discover.") within(:status, text: "#{recommendable_product.name} is listed on Gumroad Discover.") do click_on "View" end expect(current_url).to include(UrlService.discover_domain_with_protocol) expect_product_cards_with_names("product 1") end end describe "changing product tags" do it "allows user to add a tag" do visit edit_link_path(product.unique_permalink) + "/share" within :fieldset, "Tags" do select_combo_box_option search: "Test1", from: "Tags" expect(page).to have_button "test1" select_combo_box_option search: "Test2", from: "Tags" expect(page).to have_button "test2" end save_change expect(product.tags.size).to eq 2 expect(product.tags[0].name).to eq "test1" expect(product.tags[1].name).to eq "test2" end it "allows to add no more than five tags" do visit edit_link_path(product.unique_permalink) + "/share" expect(page).to have_combo_box "Tags" select_combo_box_option search: "Test1", from: "Tags" select_combo_box_option search: "Test2", from: "Tags" select_combo_box_option search: "Test3", from: "Tags" select_combo_box_option search: "Test4", from: "Tags" select_combo_box_option search: "Test5", from: "Tags" %w[test1 test2 test3 test4 test5].each do |tag| within :fieldset, "Tags" do expect(page).to have_button(tag) end end fill_in "Tags", with: "Test6" expect(page).to_not have_combo_box "Tags", expanded: true end it "recommends tag suggestions from other products" do tag = create(:tag, name: "other-product-tag") create(:product, tags: [tag]) create(:product, tags: [tag]) visit edit_link_path(product.unique_permalink) + "/share" fill_in("Tags", with: "oth") expect(page).to have_combo_box "Tags", expanded: true, with_options: ["other-product-tag (2)"] end it "displays existing product tags" do product.tags.create(name: "test1") product.tags.create(name: "test2") visit edit_link_path(product.unique_permalink) + "/share" expect(page).to have_combo_box "Tags" within :fieldset, "Tags" do expect(page).to have_button "test1" expect(page).to have_button "test2" end end it "deletes existing product tag" do product.tags.create(name: "test1") product.tags.create(name: "test2") visit edit_link_path(product.unique_permalink) + "/share" expect(page).to have_combo_box "Tags" within :fieldset, "Tags" do expect(page).to have_button "test2" click_on "test2" expect(page).not_to have_button "test2" end save_change expect(product.tags.size).to eq 1 expect(product.tags[0].name).to eq "test1" end end describe "changing discover taxonomy settings" do it "shows previously selected category, shows all available categories, and saves a newly selected category" do product.update_attribute(:taxonomy, Taxonomy.find_by(slug: "design")) visit edit_link_path(product.unique_permalink) + "/share" within :fieldset, "Category" do expect(page).to have_text("Design") end click_on "Clear value" expect(page).to have_combo_box "Category", expanded: true, with_options: [ "3D", "3D > 3D Modeling", "3D > Character Design", "Design", "Design > Entertainment Design", "Design > Industrial Design" ] within :fieldset, "Category" do select_combo_box_option search: "3D > 3D Modeling", from: "Category" end save_change product.reload expect(product.taxonomy.slug).to eq("3d-modeling") end it "searches for category by partial text regardless of hierarchy" do visit edit_link_path(product.unique_permalink) + "/share" within :fieldset, "Category" do select_combo_box_option search: "Entertainment", from: "Category" end save_change product.reload expect(product.taxonomy.slug).to eq("entertainment-design") end it "unsets category when value is cleared" do product.update_attribute(:taxonomy, Taxonomy.find_by(slug: "design")) visit edit_link_path(product.unique_permalink) + "/share" within :fieldset, "Category" do click_on "Clear value" end save_change product.reload expect(product.taxonomy_id).to be_nil expect(product.taxonomy).to be_nil end end describe "changing discover fee settings" do describe "profile sections" do it "allows updating profile sections" do product2 = create(:product, user: seller, name: "Product 2") product3 = create(:product, user: seller, name: "Product 3") section1 = create(:seller_profile_products_section, seller:, header: "Section 1", add_new_products: false, shown_products: [product, product2, product3].map(&:id)) section2 = create(:seller_profile_products_section, seller:, header: "Section 2", hide_header: true, shown_products: [product.id]) section3 = create(:seller_profile_products_section, seller:, add_new_products: false, shown_products: [product2.id]) visit edit_link_path(product.unique_permalink) + "/share" expect(page).to_not have_text "You currently have no sections in your profile to display this" within_section "Profile", section_element: :section do expect(page).to have_selector(:checkbox, count: 3) # these assertions don't work in the field selectors below for some reason expect(page).to have_text "Section 1\n#{product.name}, #{product2.name}, and 1 other" expect(page).to have_text "Section 2 (Default)\n#{product.name}" expect(page).to have_text "Unnamed section\n#{product2.name}" uncheck "Section 1" uncheck "Section 2" check "Unnamed section" end click_on "Save changes" wait_for_ajax expect(section1.reload.shown_products).to eq [product2.id, product3.id] expect(section2.reload.shown_products).to eq [] expect(section3.reload.shown_products).to eq [product2, product].map(&:id) within_section "Profile", section_element: :section do uncheck "Unnamed section" end click_on "Save changes" wait_for_ajax expect([section1, section2, section3].any? { _1.reload.shown_products.include?(product.id) }).to eq false end it "shows an info message when none exists" do visit edit_link_path(product.unique_permalink) + "/share" expect(page).to have_text "You currently have no sections in your profile to display this" expect(page).to have_link "create one here", href: root_url(host: seller.subdomain) end end end describe "offer code validation" do context "when the price invalidates an offer code" do context "amount validations" do before do create(:offer_code, user: seller, products: [product], code: "bad", amount_cents: 100) end it "displays a warning message" do visit edit_link_path(product.unique_permalink) fill_in "Amount", with: "1.50" click_on "Save changes" expect(page).to have_alert(text: "The following offer code discounts this product below $0.99, but not to $0: bad. Please update it or it will not work at checkout.") end end context "currency validations" do before do create(:offer_code, user: seller, products: [product], code: "usd", amount_cents: 100) end it "displays a warning message" do visit edit_link_path(product.unique_permalink) select "£", from: "Currency", visible: false expect(page).to have_select("Currency", selected: "£", visible: false) click_on "Save changes" expect(page).to have_alert(text: "The following offer code has currency mismatch with this product: usd. Please update it or it will not work at checkout.") expect(product.reload.price_currency_type).to eq "gbp" end end end end context "product currency" do it "allows updating currency" do
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/edit/thumbnails_spec.rb
spec/requests/products/edit/thumbnails_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Product Edit Thumbnail Scenario", type: :system, js: true) do include ManageSubscriptionHelpers let(:seller) { create(:named_seller) } before :each do @product = create(:product_with_pdf_file, user: seller, size: 1024) @product.shipping_destinations << ShippingDestination.new(country_code: Product::Shipping::ELSEWHERE, one_item_rate_cents: 0, multiple_items_rate_cents: 0) end include_context "with switching account to user as admin for seller" it "allows uploading images as thumbnails and validates them" do visit("/products/#{@product.unique_permalink}/edit") within_section "Thumbnail", section_element: :section do page.attach_file("Upload", file_fixture("sample.mov"), visible: false) end expect(page).to have_alert(text: "Invalid file type.") expect(page).to have_no_alert within_section "Thumbnail", section_element: :section do page.attach_file("Upload", file_fixture("error_file.jpeg"), visible: false) end expect(page).to have_alert(text: "Could not process your thumbnail, please upload an image with size smaller than 5 MB") expect(page).to have_no_alert within_section "Thumbnail", section_element: :section do page.attach_file("Upload", file_fixture("test-small.png"), visible: false) end expect(page).to have_alert(text: "Image must be at least 600x600px.") expect(page).to have_no_alert within_section "Thumbnail", section_element: :section do page.attach_file("Upload", file_fixture("test-squashed-horizontal.gif"), visible: false) end expect(page).to have_alert(text: "Image must be square.") expect(page).to have_no_alert within_section "Thumbnail", section_element: :section do page.attach_file("Upload", file_fixture("disguised_html_script.png"), visible: false) end expect(page).to have_alert(text: "Invalid file type.") expect(page).to have_no_alert within_section "Thumbnail", section_element: :section do page.attach_file("Upload", file_fixture("smilie.png"), visible: false) expect(page).to have_selector("[role=progressbar]") wait_for_ajax expect(page).to_not have_selector("[role=progressbar]") expect(page).to have_image("Thumbnail image", src: @product.reload.thumbnail.url) end expect(page).to have_no_alert expect(@product.reload.thumbnail).to be_present end context "when product has a saved thumbnail" do before do create(:thumbnail, product: @product) @product.reload visit("/products/#{@product.unique_permalink}/edit") end it "shows the thumbnail" do expect(page).to have_image("Thumbnail image", src: @product.thumbnail.url) end it "allows user to remove the thumbnail and persists the removal immediately" do within_section "Thumbnail", section_element: :section do click_on "Remove" end wait_for_ajax expect(page).to have_alert(text: "Thumbnail has been deleted.") within_section "Thumbnail", section_element: :section do expect(page).to_not have_image expect(page).to have_field("Upload", visible: false) end expect(@product.reload.thumbnail).not_to be_alive end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/edit/coffee_spec.rb
spec/requests/products/edit/coffee_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe "Coffee Edit", type: :system, js: true do let(:seller) { create(:user, :eligible_for_service_products, name: "Caffeine Addict") } let(:coffee) do create( :product, user: seller, name: "Coffee", description: "Buy me a coffee", native_type: Link::NATIVE_TYPE_COFFEE, purchase_disabled_at: Time.current ) end include_context "with switching account to user as admin for seller" before { Feature.activate_user(:product_edit_react, seller) } it "allows editing coffee products" do visit edit_link_path(coffee.unique_permalink) suggested_amount1 = coffee.alive_variants.first find_field("Header", with: "Coffee").fill_in with: "Coffee product" find_field("Body", with: "Buy me a coffee").fill_in with: "Buy me a coffee product" find_field("Call to action", with: "donate_prompt").select "Support" expect(page).to have_field("URL", with: custom_domain_coffee_url(host: seller.subdomain), disabled: true) expect(page).to have_field("Suggested amount 1", with: 1) in_preview do expect(page).to have_link("Caffeine Addict") expect(page).to have_selector("h1", text: "Coffee product") expect(page).to have_selector("h3", text: "Buy me a coffee product") expect(page).to have_field("Price", with: "1") expect(page).to have_link("Support") end click_on "Add amount" fill_in "Suggested amount 2", with: 2 click_on "Delete", match: :first in_preview { expect(page).to have_field("Price", with: "2") } click_on "Add amount" fill_in "Suggested amount 2", with: 4 select "Tip", from: "Call to action" in_preview do expect(page).to have_radio_button("$2") expect(page).to have_radio_button("$4") expect(page).to have_radio_button("Other", checked: true) expect(page).to have_field("Price") expect(page).to have_link("Tip") end click_on "Save changes" expect(page).to have_alert(text: "Changes saved!") refresh in_preview { expect(page).to have_radio_button("Other", checked: true) } expect(suggested_amount1.reload).to be_deleted coffee.reload expect(coffee.name).to eq("Coffee product") expect(coffee.description).to eq("Buy me a coffee product") expect(coffee.custom_button_text_option).to eq("tip_prompt") suggested_amount2 = coffee.alive_variants.first expect(suggested_amount2.name).to eq("") expect(suggested_amount2.price_difference_cents).to eq(200) suggested_amount3 = coffee.alive_variants.second expect(suggested_amount3.name).to eq("") expect(suggested_amount3.price_difference_cents).to eq(400) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/requests/products/edit/publishing_spec.rb
spec/requests/products/edit/publishing_spec.rb
# frozen_string_literal: true require "spec_helper" require "shared_examples/authorize_called" describe("Product Edit - Publishing Scenario", type: :system, js: true) do include ProductEditPageHelpers let(:seller) { create(:named_seller, payment_address: nil) } include_context "with switching account to user as admin for seller" describe("already published") do before do @product = create(:product_with_pdf_file, user: seller) @tag = create(:tag, name: "camel", humanized_name: "Bactrian 🐫s Have Two Humps") @product.tag!("camel") create(:product_review, purchase: create(:purchase, link: @product)) create(:merchant_account_stripe_connect, user: seller) visit edit_link_path(@product.unique_permalink) end it("allows user to publish and unpublish product") do click_on "Unpublish" wait_for_ajax select_tab "Content" expect(page).to have_button("Publish and continue") expect(@product.reload.alive?).to be(false) click_on "Publish and continue" wait_for_ajax expect(page).to have_button("Unpublish") expect(@product.reload.alive?).to be(true) end it "allows creator to copy product url" do select_tab "Share" copy_button = find_button("Copy URL") copy_button.hover expect(copy_button).to have_tooltip(text: "Copy to Clipboard") copy_button.click expect(copy_button).to have_tooltip(text: "Copied!") # Hover somewhere else to trigger mouseout first("a").hover expect(copy_button).not_to have_tooltip(text: "Copy to Clipboard") expect(copy_button).not_to have_tooltip(text: "Copied!") copy_button.hover expect(copy_button).to have_tooltip(text: "Copy to Clipboard") end it "allows user to mark their product as adult" do wait_for_ajax select_tab "Share" check "This product contains content meant only for adults, including the preview" expect do save_change end.to change { @product.reload.is_adult }.to(true) end it "allows user to toggle product review display on their product" do wait_for_ajax select_tab "Share" uncheck "Display your product's 1-5 star rating to prospective customers" expect(page).not_to have_text("Ratings") expect do save_change end.to change { @product.reload.display_product_reviews }.to(false) check "Display your product's 1-5 star rating to prospective customers" expect(page).to have_text("Ratings") expect do save_change end.to change { @product.reload.display_product_reviews }.to(true) end end describe("unpublished") do before do @product = create(:product_with_pdf_file, user: seller, draft: false, purchase_disabled_at: Time.current) end it("does not allow publishing a product if no payout method is setup") do visit edit_link_path(@product.unique_permalink) click_on "Save and continue" wait_for_ajax click_on "Publish and continue" wait_for_ajax expect(page).to have_alert("You must connect at least one payment method before you can publish this product for sale.") expect(@product.reload.alive?).to be(false) expect(@product.published?).to be(false) end it("allows user to publish and unpublish product if a payout method is setup") do create(:merchant_account_stripe_connect, user: seller) visit edit_link_path(@product.unique_permalink) click_on "Save and continue" wait_for_ajax click_on "Publish and continue" wait_for_ajax expect(page).to have_button("Unpublish") expect(@product.reload.alive?).to be(true) expect(@product.published?).to be(true) click_on "Unpublish" wait_for_ajax expect(page).to have_button("Publish and continue") expect(@product.reload.alive?).to be(false) expect(@product.published?).to be(false) end context "Merchant migration enabled" do before do allow(StripeMerchantAccountHelper).to receive(:ensure_charges_enabled).and_return(true) seller.check_merchant_account_is_linked = false seller.save! create(:ach_account_stripe_succeed, user: seller) vcr_turned_on do VCR.use_cassette("Product Edit Scenario-Merchant migration enabled", record: :once) do @merchant_account = create(:merchant_account_stripe, user: seller) end end Feature.activate_user(:merchant_migration, seller) end after do Feature.deactivate_user(:merchant_migration, seller) end it "allows publishing if new account and has a valid merchant account connected" do visit edit_link_path(@product.unique_permalink) select_tab "Content" click_on "Publish and continue" wait_for_ajax expect(page).to have_button("Unpublish") expect(@product.reload.alive?).to be(true) expect(@product.published?).to be(true) end end context "when user is admin team member" do before do seller.update!(is_team_member: true) end it "allows publishing a product without payment method setup" do visit edit_link_path(@product.unique_permalink) click_on "Save and continue" wait_for_ajax click_on "Publish and continue" wait_for_ajax expect(page).to have_button("Unpublish") expect(@product.reload.alive?).to be(true) expect(@product.published?).to be(true) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false